[英]Log4j2 - How to add message and log level to keyValuePair value
[英]how to log only one level with log4j2?
我在应用程序中使用log4j2。
我想要的是将要进行调试的所有内容都放入控制台,将要进行“信息”的所有内容都进入myapp.log,仅将“信息”的所有内容都进入“ myapp-audit.log”。
原因是,INFO主要包含成功的数据修改(例如,“用户创建”,“用户更新”,“用户删除”等)。 如果有效,则为数据修改的审核日志。
但是我不知道该怎么做。
如何仅获取“信息”以登录到“ myapp-audit.log”? 这是我当前的配置...
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<File name="LogFile" fileName="myapp.log">
<PatternLayout
pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</File>
<File name="AuditFile" fileName="myapp-audit.log">
<PatternLayout
pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</File>
</appenders>
<loggers>
<root level="debug">
<appender-ref ref="Console" level="debug" />
<appender-ref ref="LogFile" level="info" />
<appender-ref ref="AuditFile" level="info" /> <!-- I want ONLY 'info' here -->
</root>
</loggers>
</configuration>
如果在appender-ref中指定INFO,则附加程序将接收INFO,WARN,ERROR和FATAL事件。 您可以通过过滤掉WARN,ERROR和FATAL级别的事件来进一步限制为仅INFO:
<File name="AuditFile" fileName="myapp-audit.log">
<PatternLayout
pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%nZ" />
<Filters>
<!-- First deny warn, error and fatal messages -->
<ThresholdFilter level="warn" onMatch="DENY" onMismatch="NEUTRAL"/>
<ThresholdFilter level="error" onMatch="DENY" onMismatch="NEUTRAL"/>
<ThresholdFilter level="fatal" onMatch="DENY" onMismatch="NEUTRAL"/>
<!-- Then accept info, warn, error, fatal and deny debug/trace -->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
</File>
您无法直接执行此操作,因为info
级别包含“上方”的所有内容-警告,错误,致命。 您可以做的是创建一个单独的审核记录器。
在课堂里:
Logger log = LogManager.getLogger("audit");
在xml中:
<Logger name="audit" level="info">
<Appender-ref ref="AuditFile" level="info" />
</Logger>
或者,您可以使用RoutingAppender (可以使用ThreadContext
以外的其他东西):
ThreadContext.put("ROUTINGFLAG", "audit");
log.info("...");
ThreadContext.remove("ROUTINGFLAG");
在xml中:
...
<Routing name="Routing">
<Routes pattern="$${ctx:ROUTINGFLAG}">
<Route AppenderRef="LogFile"/>
<Route AppenderRef="AuditFile" key="audit"/>
</Routes>
</Routing>
</Appenders>
<Loggers>
<Root level="debug">
<Appender-ref ref="Console" level="debug"/>
<AppenderRef ref="Routing" level="info"/>
</Root>
</Loggers>
您可以使用LevelRangeFilter 。 它具有minLevel和maxLevel属性(当然还有onMatch和onMismatch)。
例如(在json中),我们只需要在信息和警告级别上打印控制台中的日志:
"Appenders": {
"Console": {
"PatternLayout": {
"pattern": "%d{yyyy-MMM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n"
},
"name": "Console",
"target": "SYSTEM_OUT",
"LevelRangeFilter": {
"minLevel": "warn",
"maxLevel": "info",
"onMatch": "ACCEPT",
"onMismatch": "DENY"
}
}
}
如果只希望信息级别,则将“ info”写入属性min和max。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.