我第一次在项目中使用 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
我有两个关于此的问题:
记录器能够定义记录消息的不同重要性级别,并能够使用不同的接收器进行输出 - 控制台、文件等.
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.
这篇关于log4j 与 System.out.println - 记录器的优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!