一招给你的log4j2日志穿件花衣服

概述

大家项目中打印在Console中的日志是什么样的呢?是否都是清一色的黑色字体,如下图所示,这样会导致一些关键日志信息,比如error、warn日志被忽视掉,那有什么办法可以修改Console中日志的样式,让一些关键日志能够显著地被找到?

一招给你的log4j2日志穿件花衣服

修改Log4j2日志样式

通过修改log4j2.xml中的日志样式配置,可以打印出下图的日志,是不是很清楚。

一招给你的log4j2日志穿件花衣服

如何做到的呢?

一招给你的log4j2日志穿件花衣服
  1. 修改日志配置中pattern属性, 通过%style{xxxx}{styleValue1,styleValue2}%highlight{}可以很容易修改日志样式,下一章节详细讲解下相关样式。
%style{%d{ISO8601}}{bright,green} %highlight{%-5level} [%style{%t}{bright,blue}] %style{%C{}}{bright,yellow}: %msg%n%style{%throwable}{red}
  1. 设置属性disableAnsi为false,表示开启Ansi,这样才会输出有样式的日志。

样式配置详解

highlight{pattern}{style}

说明: 根据当前事件的日志记录级别添加ANSI颜色。

默认颜色如下:

一招给你的log4j2日志穿件花衣服

颜色表:

一招给你的log4j2日志穿件花衣服

例子:

%highlight{%d [%t] %-5level: %msg%n%throwable}

你可以在可选的{style}选项中覆盖默认颜色。例如:

%highlight{%d [%t] %-5level: %msg%n%throwable}{FATAL=white, ERROR=red, WARN=bright_blue, INFO=black, DEBUG=bright_green, TRACE=blue}

同时也可以使用真颜色(24位)。例如:

%highlight{%d [%t] %-5level: %msg%n%throwable}{FATAL=white, ERROR=red, WARN=bg_#5792e6 fg_#eef26b bold, INFO=black, DEBUG=#3fe0a8, TRACE=blue}

你只能突出显示日志事件的一部分:

%d [%t] %highlight{%-5level: %msg%n%throwable}

你也可以使用STYLE键来使用预定义的一组颜色:

%highlight{%d [%t] %-5level: %msg%n%throwable}{STYLE=Logback}
一招给你的log4j2日志穿件花衣服

style{pattern}{ANSI style}

说明: 使用ANSI转义序列对封闭模式的结果设置样式。样式可以由下表中样式名称的逗号分隔列表组成。

样式 描述
Normal Normal display
Bright Bold
Dim Dimmed or faint characters
Underline Underlined characters
Blink Blinking characters
Reverse Reverse video
Hidden
Black or FG_Black Set foreground color to black
Red or FG_Red Set foreground color to red
Green or FG_Green Set foreground color to green
Yellow or FG_Yellow Set foreground color to yellow
Blue or FG_Blue Set foreground color to blue
Magenta or FG_Magenta Set foreground color to magenta
Cyan or FG_Cyan Set foreground color to cyan
White or FG_White Set foreground color to white
Default or FG_Default Set foreground color to default (white)
BG_Black Set background color to black
BG_Red Set background color to red
BG_Green Set background color to green
BG_Yellow Set background color to yellow
BG_Blue Set background color to blue
BG_Magenta Set background color to magenta
BG_Cyan Set background color to cyan
BG_White Set background color to white

例子:

%style{%d{ISO8601}}{black} %style{[%t]}{blue} %style{%-5level:}{yellow} %style{%msg%n%throwable}{green}

你也可以组合不同的风格:

%d %highlight{%p} %style{%logger}{bright,cyan} %C{1.} %msg%n

您还可以将%和颜色组合,比如 %black, %blue, %cyan一起使用。例如:

%black{%d{ISO8601}} %blue{[%t]} %yellow{%-5level:} %green{%msg%n%throwable}

总结

本文讲解了log4j2框架下如何美化你输出的日志,不过这只针对控制台输出的日志起效,文件中的日志并不生效,希望大家都用起来呀。


原文始发于微信公众号(JAVA旭阳):一招给你的log4j2日志穿件花衣服

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/63454.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!