Log4j动态配置

常规实现:

  • 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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Log4j的包下载完成后,解压,将其中打包好的的log4j-1.x.x.jar导入你的工程LIB中。 Log4j之所以受欢迎的原因之一是它的灵活性。Log4j提供了灵活的配置方法,默认是调用BasicConfigurator.configure()来进行配置,但如果只是简单的调用BasicConfigurator.configure()来进行配置工作,那么所有的配置都是固定的,不方便以后修改配置。另一种是动态配置Log4j提供了PropertyConfigurator.configure(……)来动态配置,参数可以是一个properties文件所在路径的String对象,可以是一个properties文件所在路径的URL对象,也可以是一个properties对象。如果要用XML文件来配置信息,则可用类型的DOMConfigurator()函数来从一个XML文件中加载配置信息。这种方式更方便修改配置动态配置 package http; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; public class Log4jDemo { static Logger log = Logger.getLogger(Log4jDemo.class.getClass()); /** * main * @param args */ public static void main(String[] args) { BasicConfigurator.configure();//默认配置 PropertyConfigurator.configure("c:/log4j.properties"); //动态配置,参数可以是一个properties文件所在路径的String对象 //可以是一个properties文件所在路径的URL对象,也可以是一个properties对象 DOMConfigurator.configure("c:/log4j.xml");//XML配置文件 //PropertyConfigurator.configure()的参数还可以是XML、Properties对象 //下面就可使用log4j log.info("info"); log.debug("debug"); log.error("error"); log.warn("warn"); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值