常规实现:
- Log4j默认配置会去读log4j.properties文件 每个类都会提
- 前实例化一个logger变量,实例化时便使用了默认的配置
动态配置实现:
- 可先调用PropertyConfigurator.configure(path)动态控制配置文件
private static void init(String[] args) {
String configPath = null;
if (args.length > 0) {
configPath = args[0];
}
initLog4jPath(configPath);
Conf.init(configPath);
}
private static void initLog4jPath(String path) {
if (path == null) {
PropertyConfigurator.configure(Main.class.getClassLoader().getResourceAsStream("log4jtemp.properties"));
} else {
PropertyConfigurator.configure(path + "/log4j.properties");
}
}
- logger单例使用懒加载,用到的时候再实例化,便会使用动态配置文件
public class LogHelper {
private static final ConcurrentHashMap<String, Logger> loggerMap = new ConcurrentHashMap<String, Logger>();
public static Logger getLogger() {
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
String callerName = stack[0].getClassName();
if (loggerMap.get(callerName) == null) {
loggerMap.put(callerName, Logger.getLogger(callerName));
}
return loggerMap.get(callerName);
}
}