SpringMVC自定义配置Log4j及其工作原理

本文介绍如何在Spring MVC项目中配置Log4j,包括web.xml中的配置参数、Log4jConfigListener的工作原理及其如何配合Log4jConfigurer完成日志框架的初始化和关闭过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Log4j应该是目前项目开发中使用最广的日志记录框架,一般配置Log4j只需要配置Log4j的属性文件在src目录以及引入Log4j的jar包即可,但是如果项目比较大的时候,我们需要将一些配置文件放入自定义的项目目录里面,传统的方法显然不能满足需求,下面讲解一下Log4j在Springmvc项目中的配置及工作原理:

web.xml文件配置:

<context-param>   
      <param-name>log4jConfigLocation</param-name>   
      <param-value>classpath:config/log4j.properties</param-value>   
  </context-param>   
  <context-param>   
      <param-name>log4jRefreshInterval</param-name>   
      <param-value>6000</param-value>   
  </context-param>   
  <listener>   
      <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>   
  </listener> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

context-param:配置ServletContext的初始化参数 
Log4jConfigListener:配置Log4j的监听器

Log4jConfigListener的工作原理: 
源码:

@Deprecated
public class Log4jConfigListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        Log4jWebConfigurer.initLogging(event.getServletContext());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        Log4jWebConfigurer.shutdownLogging(event.getServletContext());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

很显然Log4jConfigListener 通过实现ServletContextListener接口,随着Servlet容器的启动,其监听器的contextInitialized()方法就会被调用,Log4jConfigListener借助于Log4jWebConfigurer实现Log4j的初始化和关闭等操作

Log4jWebConfigurer的initLogging(ServletContext servletContext)方法:

public static void initLogging(ServletContext servletContext) {
        // Expose the web app root system property.
        if (exposeWebAppRoot(servletContext)) {
            WebUtils.setWebAppRootSystemProperty(servletContext);
        }

        // Only perform custom log4j initialization in case of a config file.
        String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
        if (location != null) {
            // Perform actual log4j initialization; else rely on log4j's default initialization.
            try {
                // Resolve property placeholders before potentially resolving a real path.
                location = ServletContextPropertyUtils.resolvePlaceholders(location, servletContext);

                // Leave a URL (e.g. "classpath:" or "file:") as-is.
                if (!ResourceUtils.isUrl(location)) {
                    // Consider a plain file path as relative to the web application root directory.
                    location = WebUtils.getRealPath(servletContext, location);
                }

                // Write log message to server log.
                servletContext.log("Initializing log4j from [" + location + "]");

                // Check whether refresh interval was specified.
                String intervalString = servletContext.getInitParameter(REFRESH_INTERVAL_PARAM);
                if (StringUtils.hasText(intervalString)) {
                    // Initialize with refresh interval, i.e. with log4j's watchdog thread,
                    // checking the file in the background.
                    try {
                        long refreshInterval = Long.parseLong(intervalString);
                        org.springframework.util.Log4jConfigurer.initLogging(location, refreshInterval);
                    }
                    catch (NumberFormatException ex) {
                        throw new IllegalArgumentException("Invalid 'log4jRefreshInterval' parameter: " + ex.getMessage());
                    }
                }
                else {
                    // Initialize without refresh check, i.e. without log4j's watchdog thread.
                    org.springframework.util.Log4jConfigurer.initLogging(location);
                }
            }
            catch (FileNotFoundException ex) {
                throw new IllegalArgumentException("Invalid 'log4jConfigLocation' parameter: " + ex.getMessage());
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

工作流程:将web应用绝对路径添加到系统属性(支持log4j ${key}等获功能),方法内部读取ServletContext的初始化参数然后调用 
org.springframework.util.Log4jConfigurer.initLogging(location, refreshInterval)完成Log4j的初始化工作

Log4j的关闭流程:

public static void shutdownLogging(ServletContext servletContext) {
        servletContext.log("Shutting down log4j");
        try {
            org.springframework.util.Log4jConfigurer.shutdownLogging();
        }
        finally {
            // Remove the web app root system property.
            if (exposeWebAppRoot(servletContext)) {
                WebUtils.removeWebAppRootSystemProperty(servletContext);
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

总之:真正的Log4j的初始化和关闭真正的执行者Log4jConfigurer,Log4jWebConfigurer只是Log4j在web环境下的支持

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值