3 回答
TA贡献1833条经验 获得超4个赞
听起来您正在尝试从“两端”(使用者端和配置端)使用log4j。
如果要针对slf4j api进行编码,但要提前(并以编程方式)确定类路径将返回的log4j Logger的配置,则绝对必须具有某种利用惰性构造的日志记录适配。
public class YourLoggingWrapper {
private static boolean loggingIsInitialized = false;
public YourLoggingWrapper() {
// ...blah
}
public static void debug(String debugMsg) {
log(LogLevel.Debug, debugMsg);
}
// Same for all other log levels your want to handle.
// You mentioned TRACE and ERROR.
private static void log(LogLevel level, String logMsg) {
if(!loggingIsInitialized)
initLogging();
org.slf4j.Logger slf4jLogger = org.slf4j.LoggerFactory.getLogger("DebugLogger");
switch(level) {
case: Debug:
logger.debug(logMsg);
break;
default:
// whatever
}
}
// log4j logging is lazily constructed; it gets initialized
// the first time the invoking app calls a log method
private static void initLogging() {
loggingIsInitialized = true;
org.apache.log4j.Logger debugLogger = org.apache.log4j.LoggerFactory.getLogger("DebugLogger");
// Now all the same configuration code that @oers suggested applies...
// configure the logger, configure and add its appenders, etc.
debugLogger.addAppender(someConfiguredFileAppender);
}
使用这种方法,您无需担心log4j记录器的配置位置/时间。类路径第一次要求它们时,它们会被延迟构造,传递回并通过slf4j提供。希望这对您有所帮助!
添加回答
举报