我正在编写一个作为 Logback Logger 包装器的类。具体来说,它是为了便于审计日志记录。它应该是一个人们应该能够导入和使用的独立库。我遇到的问题与以编程方式声明 LogBack 的文档数量最少有关。我将一般声明基于另一个堆栈溢出问题(以编程方式设置 Logback Appender 路径)。
我目前的定义如下。目前我无法让标记过滤器正常工作。正如我所声明的那样,标记过滤器似乎没有做任何事情。最终,我想确保除了审计日志之外没有其他信息进入审计日志文件。这就是为什么我在不匹配时拒绝它。从我的测试看来,它只是被忽略了。
任何有关以编程方式创建的 Logback 文件的信息或指导将不胜感激。当用户使用我的类进行审计日志记录然后使 Logback.xml 进行自己的单独日志记录时,还有什么我应该担心的吗?谢谢
import ch.qos.logback.classic.Level;
import ch.qos.logback.core.spi.FilterReply;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.filter.EvaluatorFilter;
import ch.qos.logback.classic.boolex.OnMarkerEvaluator;
public class AuditLogger {
private static Logger logbackLogger;
final static Marker AUDIT = MarkerFactory.getMarker("AUDIT");
static {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
RollingFileAppender rfAppender = new RollingFileAppender();
rfAppender.setContext(loggerContext);
rfAppender.setFile("auditLogFile.currentDay.log");
TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy();
rollingPolicy.setContext(loggerContext);
// rolling policies need to know their parent
// it's one of the rare cases, where a sub-component knows about its parent
rollingPolicy.setParent(rfAppender);
rollingPolicy.setFileNamePattern("auditLogFile.%d{yyyy-MM-dd}.log");
rollingPolicy.start();
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(loggerContext);
encoder.setPattern("[%d{ISO8601}] %5marker - %msg%n");
encoder.start();
rfAppender.setEncoder(encoder);
rfAppender.setRollingPolicy(rollingPolicy);
rfAppender.start();
EvaluatorFilter evalFilter= new EvaluatorFilter();
OnMarkerEvaluator markerEval= new OnMarkerEvaluator();
markerEval.addMarker("AUDIT");
evalFilter.setEvaluator(markerEval);
evalFilter.setOnMatch(FilterReply.ACCEPT);
evalFilter.setOnMismatch(FilterReply.DENY);
rfAppender.addFilter(evalFilter);
logbackLogger = loggerContext.getLogger("AUDIT_LOGGER");
logbackLogger.addAppender(rfAppender);
logbackLogger.setLevel(Level.DEBUG);
}
public AuditLogger(){}
public void log(String msg){
logbackLogger.debug(AUDIT, msg);
}
}