日志带参输出 The Art of Logging: Advanced message formatting
2017-07-17 18:02
302 查看
The
Art of Logging: Advanced message formatting
https://garygregory.wordpress.com/tag/org-apache-logging-log4j-logger/In this post, I’ll show you how to format your Log4j logging message like a pro.
Let’s start with a bland and inefficient logging statement:
You are always building the full string before calling debug()
You are always calling getUserCount()
Both of the above happens even if debug logging is disabled!
In the old days of logging, you avoided these problems with more code like this:
method is still called whenever the debug() method is called. That part is still Lame.
As I point out in this
post, Log4j 2.4 and Java 8 come to the rescue with lambdas to clean this up as follows:
The getUserCount() function is only called when debug logging is enabled. This happens because the expression “() -> getUserCount()” does not call the getUserCount() method before debug() is called. Instead, Java creates a block of code that Log4j executes
later, if it needs the result.
The complete message is only built with the result of getUserCount() when debug logging is enabled.
The only possible drawback is that the getUserCount() function is called a little later in the code path which could be an issue if the method relies on precise and exact timing or position on the stack, that would be unusual but possible.
Next up is the actual format of the message.
Using “{}” parameter markers causes Log4j to call toString() on each argument you pass to logger methods like debug().
This is ugly when it comes to printing large numbers for example:
You can format numbers like this as well:
The only caveat is that you will not get the same performance out of a formatter logger as you would out of the default logger. Still, pretty neat.
相关文章推荐
- 系统日志输出工具类 → AppLogMessageMgr
- 不让应用的日志输出到message文件中
- Qt 日志输出 QMessageLogger QtMessageHandler qInstallMessageHandler()
- CI框架中 日志输出方法log_message()只允许输出字符串解决方案
- 配置tomcat输出详细日志
- spark脚本日志输出级别设置
- Xcode8禁止输出无用日志
- tomcat中日志输出的位置
- 详解log4j2(下) - Async/MongoDB/Flume Appender 按日志级别区分文件输出
- Log4j将不同Package的日志输出到不同的文件
- Linux/Tomcat动态输出日志
- 一句话输出NGINX日志访问IP前十位排行
- log4j日志信息输出文件配置
- Common.Logging.dll----------配置方式,可选引用,用于日志输出
- springboot 学习之路 4(日志输出)
- 输出重定向和多命令顺序执行(记录日志)
- .LOG4J的配置(输出到控制台、文件、回滚文件、发送日志邮件、输出到数据库日志表、自定义标签等全套功能)
- logback只输出WARN级别的日志
- C#输出日志测试代码
- 有效Log4j按指定级别定向输出日志到指定的输出文件地址配置Threshold,log4j中如何屏蔽父logger输出源rootlogger的additivity配置,log4j向多个文件记录日志