log4j.properties:
# configure the root logger
log4j.rootLogger=INFO, SYSLOG
# configure Syslog facility LOCAL6 appender
log4j.appender.SYSLOG=org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG.threshold=INFO
log4j.appender.SYSLOG.syslogHost=localhost
log4j.appender.SYSLOG.facility=LOCAL6
log4j.appender.SYSLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.SYSLOG.layout.conversionPattern="MyApp: %d\{ISO8601\}%m\n"
记录器类
import org.apache.log4j.Logger;
public class Log4jAuditLogger {
private static Logger LOG = Logger.getLogger(Log4jAuditLogger.class);
public static void log(String message) {
LOG.info(message);
}
}
我想将信息(这些是审计消息,我不想在此处记录错误消息)记录到SYSLOG LOCAL6中,并将错误消息(这些是java程序的内部错误消息)记录到SYSLOG LOCAL7中。
我应该如何扩展此类和配置文件来执行此操作?
我使用log4j 1.2。
答案 0 :(得分:3)
将另一个appender添加到log4j.properties:
# configure the root logger
log4j.rootLogger=INFO, SYSLOG, SYSLOG7
# configure Syslog facility LOCAL6 appender
log4j.appender.SYSLOG=org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG.threshold=INFO
log4j.appender.SYSLOG.syslogHost=localhost
log4j.appender.SYSLOG.facility=LOCAL6
log4j.appender.SYSLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.SYSLOG.layout.conversionPattern="MyApp: %d\{ISO8601\}%m\n"
# configure Syslog facility LOCAL7 appender
log4j.appender.SYSLOG7=org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG7.threshold=ERROR
# vv change to whatever the host is
log4j.appender.SYSLOG7.syslogHost=localhost
log4j.appender.SYSLOG7.facility=LOCAL7
log4j.appender.SYSLOG7.layout=org.apache.log4j.PatternLayout
log4j.appender.SYSLOG7.layout.conversionPattern="MyApp: %d\{ISO8601\}%m\n"
关于评论的编辑:
如果SYSLOG7只记录ERROR(和更高):将阈值设置为ERROR级别。所有使用较低级别记录的消息都不会显示。
棘手的部分只是在Syslog中显示低级别:
您可以使用过滤器仅记录消息" lower"比例如ERROR
级别。
在log4j 2中:PropertyConfigurator不支持过滤器。因此,您必须更改为XML配置才能使用它。请参阅log4j-Wiki about filters。
示例"特定级别"
<appender name="info-out" class="org.apache.log4j.FileAppender">
<param name="File" value="info.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelMatchFilter">
<param name="LevelToMatch" value="info" />
<param name="AcceptOnMatch" value="true"/>
</filter>
<filter class="org.apache.log4j.varia.DenyAllFilter" />
</appender>
或&#34;等级范围&#34;
<appender name="info-out" class="org.apache.log4j.FileAppender">
<param name="File" value="info.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMax" value="info"/>
<param name="LevelMin" value="info"/>
<param name="AcceptOnMatch" value="true"/>
</filter>
</appender>