假设我有一个公共类,其logger由其名称初始化:
public class SomeCalculationLogic {
private static final Log log = LogFactory.getLog(SomeCalculationLogic .class);
public void doCalculation() {
log.info("doing calculations...");
...
}
}
这个类由两个逻辑上不同的流使用 - 比如从类“BackgroundTask”和“UserRequest”调用它。 如何使SomeCalculationLogic的记录器的输出重定向到不同的日志文件(如background.log和main.log),具体取决于调用类是什么?
答案 0 :(得分:3)
我看到三种可能的方式:
子类化解决方案的工作实现将是这样的:
public class SomeCalculationLogic {
protected abstract Log getLog();
public void doCalculation() {
getLog().info("doing calculations...");
...
}
}
public class BackgroundCalculationLogic extends SomeCalculationLogic {
private static Log log = LogFactory.getLog(BackgroundCalculationLogic.class);
protected Log getLog() {
return log;
}
}
public class UserRequestCalculationLogic extends SomeCalculationLogic {
private static Log log = LogFactory.getLog(UserRequestCalculationLogic.class);
protected Log getLog() {
return log;
}
}
答案 1 :(得分:1)
如何在log4j.xml中编写类似的内容
<appender name="main-logfile" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="${user.home}/.logs/main.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="conversionPattern" value="%d %-5p %c{1}: %m%n"/>
</layout>
</appender>
<logger name="com.calculationlogic.main" additivity="false">
<appender-ref ref="main-logfile"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="conversionPattern" value="%d %-5p %c{1}: %m%n"/>
</layout>
</logger>
<appender name="background-logfile" class="org.apache.log4j.RollingFileAppender">
<param name="file" value="${user.home}/.logs/background.log"/>
</appender>
<logger name="com.calculationlogic.background" additivity="false">
<appender-ref ref="background-logfile"/>
</logger>
然后是java部分:
public class SomeCalculationLogic {
private final Category logger;
public SomeCalculationLogic(final Category logger){
this.logger = logger;
}
public void doCalculation() {
log.info("doing calculations...");
}
}
public class BackgroundTask{
public BackgroundTask(){
new SomeCalculationLogic(Logger.getLogger("com.calculationlogic.background")).doCalculation()
}
}
public class MainTask{
public MainTask(){
new SomeCalculationLogic(Logger.getLogger("com.calculationlogic.main")).doCalculation()
}
}
结果是: 在background.log中: 2010-06-25 14:23:35,496 INFO背景:做计算......
在main.log中: 2010-06-25 14:23:35,495 INFO主要:做计算......
答案 2 :(得分:0)
我建议使用继承而不是声明最终字段。
public class SomeCalculationLogic {
private static Log log = LogFactory.getLog(SomeCalculationLogic .class);
public void doCalculation() {
log.info("doing calculations...");
...
}
}
public class BackgroundCalculationLogic {
private static Log log = LogFactory.getLog(BackgroundCalculationLogic .class);
}
public class UserRequestCalculationLogic {
private static Log log = LogFactory.getLog(UserRequestCalculationLogic .class);
}