Java 服务端架构
🎨 视觉封面log4j2 与 log4j使用时的几点小区别 - log4j2上手说明
虽然log4j2 目前还是beta版,不过OneCoder已经忍不住要尝试一下。跟使用log4j 比起来,上手上主要的区别有。
1、依赖的jar包。使用slf4j+log4j2 时,依赖的jar包如下:(gradle配置,Maven对照修改即可)
dependencies{
compile(
"org.apache.logging.log4j:log4j-api:$log4j_version",
"org.apache.logging.log4j:log4j-core:$log4j_version",
"org.apache.logging.log4j:log4j-slf4j-impl:$log4j_version"
)
}其中,log4j_version=2.0-beta9
2、默认配置文件名字
默认搜索的配置文件名字变为log4j2或log4j-test开头的配置文件,这个变化,让OneCoder吃了些苦头。没注意观察,还自以为配置文件还是log4j.xml,结果怎么都不管用。后来仔细阅读官方文档才发现问题。log4j2中,支持json和xml两个格式的配置文件,配置文件的搜索顺序为:
1. Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension.
2. If no system property is set the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.
3. If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
4. If a test file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.
5. If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.
6. If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.
环境变量log4j.configurationFile指定的文件->log4j2-test.json/log4j2-test.jsn -> log4j2-test.xml -> log4j2.json/log4j2.jsn -> log4j2.xml - > 默认配置DefaultConfiguration
3、配置文件格式
配置文件样例,跟1比起来有所简化。
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %l - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>其他的变化和优势,您可以在使用中慢慢体会了。
所有代码开源上传至 GitHub:yummy-code 仓库 · GESP 专题站:GESP WIKI
欢迎加入:C++ GESP/CSP 考级答疑群(688906745) 与 Java/Python交流群(982860385),点击可直接加群。
猜你想读 · 相关文章推荐
log4j自定义appender实现,处理异常堆栈
在项目中需要自定义实现一个log4j的appender。根据log中MDC里的信息,构造日志存储的目录结构。自定义实现log4j appender的方法已经介绍过了。主要是覆盖AppenderSkeleton中的appender方法。 日志内容的获取和格式处理,通过La...
slf4j+log4j2 控制台输出错误解决
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: S...
log4j 多classloader重复加载配置问题解决
最近 OneCoder 在开发隔离任务运行的沙箱,用于隔离用户不同任务间以及任务和框架本身运行代码的隔离和解决潜在的jar包冲突问题。 运行发现,隔离的任务正常运行,但是却没有任何日志记录。从控制台可看到如下错误信息: log4j:ERROR A "org.apache...
OneCoder
一个中年人的自留地,记录学习 C++、GESP/NOI、Java、Python 与算法架构的心得体会。本站唯一网址:coderli.com

