我有一个logback XML配置文件,我使用自定义标记转换器标记我的日志消息。
<configuration scan="true">
<conversionRule conversionWord="tag"
converterClass="com.foo.MyCustomTagConverter" />
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are by default assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
<encoder>
<pattern>%tag - %m%n</pattern>
</encoder>
</appender>
...
</configuration>
如何通过Java以编程方式执行此操作?
答案 0 :(得分:1)
public class loggerutils {
static Logger foo = createLoggerFor("foo", "foo.log");
public static void main(String[] args) {
foo.info("test");
}
private static Logger createLoggerFor(String string, String file) {
String conversionWord = "tag";
String converterClass = "com.foo.MyCustomTagConverter";
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
Map<String, String> ruleRegistry = (Map) lc
.getObject(CoreConstants.PATTERN_RULE_REGISTRY);
if (ruleRegistry == null) {
ruleRegistry = new HashMap<String, String>();
}
lc.putObject(CoreConstants.PATTERN_RULE_REGISTRY, ruleRegistry);
ruleRegistry.put(conversionWord, converterClass);
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("%-20tag %-30(%d{HH:mm:ss.SSS} [%thread]) - %-15(%M) - %-5level -%logger{32} - %msg%n ");
ple.setContext(lc);
ple.start();
ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<ILoggingEvent>();
consoleAppender.setEncoder(ple);
consoleAppender.setContext(lc);
consoleAppender.start();
Logger logger = (Logger) LoggerFactory.getLogger(string);
logger.addAppender(fileAppender);
logger.setLevel(Level.DEBUG);
logger.setAdditive(false); /* set to true if root should log too */
logger.addAppender(consoleAppender);
logger.setLevel(Level.DEBUG);
logger.setAdditive(false);
return logger;
}
}