log4j 与 System.out.println - 记录器的优势?

2022-01-13 00:00:00 logging timestamp logfiles java junit

我第一次在项目中使用 log4j.一位程序员同事告诉我,使用 System.out.println 被认为是一种不好的风格,而 log4j 就像现在记录事务的标准一样.

I'm using log4j for the first time in a project. A fellow programmer told me that using System.out.println is considered a bad style and that log4j is something like standard for logging matters nowadays.

我们进行了大量的 JUnit 测试 - System.out 的东西最终变得更难测试.

We do lots of JUnit testing - System.out stuff turns out to be harder to test.

因此我开始将 log4j 用于控制台控制器类,它只是处理命令行参数.

Therefore I began utilizing log4j for a Console controller class, that's just handling command-line parameters.

// log4j logger config 
org.apache.log4j.BasicConfigurator.configure();
Logger logger = LoggerFactory.getLogger(Console.class);
Category cat = Category.getRoot(); 

似乎有效:

logger.debug("String");

生产:

1 [main] DEBUG project.prototype.controller.Console  - String

我有两个关于此的问题:

  1. 根据我对使用此记录器的基本理解,如果在记录器上启用了调试模式,那么使用此记录器应该可以为我提供舒适的选项来编写带有时间戳的日志文件 - 而不是向控制台发送垃圾邮件?
  2. 为什么 System.out.println 更难测试?我搜索了 stackoverflow,发现了一个测试配方.所以我想知道使用 log4j 真正获得了什么样的优势.
  1. From my basic understanding using this logger should provide me comfortable options to write a logfile with timestamps - instead of spamming the console - if debug mode is enabled at the logger?
  2. Why is System.out.println harder to test? I searched stackoverflow and found a testing recipe. So I wonder what kind of advantage I really get by using log4j.

推荐答案

记录器能够定义记录消息的不同重要性级别,并能够使用不同的接收器进行输出 - 控制台、文件等.

The logger gives to ability to define different levels of importance of the logged messages and the ability to use different sink for the output - the console, a file, etc.

此外,在使用记录器时,仅启用或禁用某种类型的消息也很容易 - 例如,您不希望在生产中看到每条调试消息.

Also it's easy to enable or disable only some type of message when using a logger - for example you don't want to see every debug message in production.

我不认为使用记录器在单元测试中提供任何显着优势,但我还是更喜欢它.在单元测试中,断言通常是我最关心的问题.

I don't think that using loggers offers any significant advantages in unit tests, but I'd prefer it even there anyways. In unit tests asserts are usually my primary concern.

顺便说一句,你真的应该考虑使用类似 Commons Logging 或 SLF4J 作为日志框架外观 - 将代码绑定到特定日志框架是不好的风格.如果您愿意,Common Logging 和 SLF4J 可以让您轻松切换日志框架.

Btw you should really consider using something like Commons Logging or SLF4J as a log framework facade - it's bad style to tie your code to a specific logging framework. Common Logging and SLF4J make it easy to switch logging frameworks if you choose to.

相关文章