What is right way to supply initialization for log4j2 in a Spring MVC Webapp using Java Config and no web.xml?

前端 未结 3 834
青春惊慌失措
青春惊慌失措 2021-01-22 15:59

I have a Spring MVC Web App (4.0) with log4j2. This webapp uses no web.xml and takes care of configuration through Java Config. Log4j2 configuration needs to take plac

相关标签:
3条回答
  • 2021-01-22 16:45

    I believe you can reconfigure log4j2 to a new config file during runtime like this.

         LoggerContext context = (LoggerContext)LogManager.getContext(false);
         context.setConfigLocation(URI.create("path to file"));
         context.reconfigure();
    

    Could just add this to your onStartup.

    0 讨论(0)
  • 2021-01-22 16:50

    I haven’t tested it but the following should be worth a try; replace your servletContext.setAttribute(…) call in the onStartup(…) method with the following Log4jConfigurer call:

    Log4jConfigurer.initLogging("file:///path/to/log4j2.xml")
    

    This is basically what happens under the hood when you use log4jConfigLocation in the <context-param> of a web.xml file (via Log4jWebConfigurer, see code).

    I’m only wondering if this will also work with log4j2, although I wouldn’t expect the <context-param> way to work with it either. Did you also use log4j2 when you were still using the web.xml file?

    0 讨论(0)
  • 2021-01-22 16:56

    Probably this is a little too late, but you can do the following to set the log4j2 configuration to an external path:

    public class ApplicationInitializer implements WebApplicationInitializer {
        @Override
        public void onStartup(ServletContext servletContext)
            throws ServletException {
            servletContext.setInitParameter(Log4jWebSupport.LOG4J_CONFIG_LOCATION, "file:///path/to/log4j2.xml");
    
    0 讨论(0)
提交回复
热议问题