我有一个多线程的 Java 类,我希望它记录到一个单独的文件中。我正在使用 Dropwizard,它使用 logback 并在我的 YAML 文件中进行配置,如下所示:
logging:
# The default level of all loggers. Can be OFF, ERROR, WARN, INFO, DEBUG, TRACE, or ALL.
level: INFO
# Logger-specific levels.
loggers:
# Sets the level for 'com.example.app' to DEBUG.
com.mycode: DEBUG
appenders:
- type: console
threshold: DEBUG
- type: file
threshold: INFO
logFormat: "%-6level [%d{HH:mm:ss.SSS}] [%t] %logger{5} - %X{code} %msg %n"
currentLogFilename: /tmp/fingage.log
archivedLogFilenamePattern: /tmp/project-%d{yyyy-MM-dd}-%i.log.gz
archivedFileCount: 7
timeZone: UTC
maxFileSize: 10MB
在我的特殊班级中,我正在尝试类似的事情:
//Obtain an instance of LoggerContext
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
//Create a new FileAppender
FileAppender<ILoggingEvent> file = new FileAppender<ILoggingEvent>();
file.setName("FileLogger");
file.setFile("specialclass.log");
file.setContext(context);
file.setAppend(true);
//Filter out anything < WARN
ThresholdFilter warningFilter = new ThresholdFilter();
warningFilter.setLevel("WARN");
warningFilter.setContext(context);
warningFilter.start();
file.addFilter(warningFilter);
//Message Encoder
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setContext(context);
ple.setPattern("%date %level [%thread] %logger{10} %msg%n");
ple.start();
file.setEncoder(ple);
file.start();
//Get ROOT logger, and add appender to it
log = context.getLogger(MySpecialClass.class);
log.setLevel(Level.DEBUG);
log.addAppender(file);
log.info("Hello Special Class");
不幸的是,它似乎没有改变任何东西,尽管我确实看到了一个空白文件specialclass.log,并且我的日志消息仅出现在控制台中。
答案是在 dropwizard YAML 文件中添加以下内容:
logging:
# The default level of all loggers. Can be OFF, ERROR, WARN, INFO, DEBUG, TRACE, or ALL.
level: INFO
# Logger-specific levels.
loggers:
com.mycode:
level: DEBUG
additive: false
appenders:
- type: file
currentLogFilename: /tmp/myclass.log
appenders:
- type: console
threshold: DEBUG
- type: file
threshold: INFO
logFormat: "%-6level [%d{HH:mm:ss.SSS}] [%t] %logger{5} - %X{code} %msg %n"
currentLogFilename: /tmp/project.log
archivedLogFilenamePattern: /tmp/project-%d{yyyy-MM-dd}-%i.log.gz
archivedFileCount: 7
timeZone: UTC
maxFileSize: 10MB