In java web application, how to read log4j.xml from WEB-INB/conf location with spring 3.0 annotations

后端 未结 1 602
小鲜肉
小鲜肉 2021-01-14 20:49

I wanted to put my log4j.xml file in WEB-INF/conf directory where I have many other configuration files. And I wanted the web application to read log4.xml from there.

相关标签:
1条回答
  • 2021-01-14 21:34

    Not sure what you really wanna do....

    if your log4j.xml is in the classpath, when you start your app-server, it should be loaded automatically.

    Check the console when you start your server and you should see your log4j info.

    You can also put debug=true:

    <log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">
    

    in your xml. you will be able to see a lot of info about your config.

    Now if you want to access the appenders you configured in the log4j.xml, all you have to do is:

    Logger mylogger = Logger.getLogger("MyAppenderName");
    

    Ok, i think you wanna load a custom log4j config file! In a web app context, you will need 2 things:

    create a contextListnerServlet; modify your web.xml

    ServletListner:

    public class StartupListener implements ServletContextListener
    {
    @Override
    public void contextDestroyed(ServletContextEvent arg0)
    {
        // Cleanup code goes here
    }
    
    @Override
    public void contextInitialized(ServletContextEvent sce)
    {
        Logger logger = null;
        String log4jFile = sce.getServletContext().getInitParameter("log4jFileName");
        DOMConfigurator.configure(sce.getServletContext().getRealPath(log4jFile));
        logger = LogManager.getLogger(StartupListener.class.getName());
        logger.debug("Loaded: " + log4jFile);
    }
    

    web.xml:

    <context-param>
    <param-name>log4jFileName</param-name>
    <param-value>
         WEB-INF/config/log4j-my.xml
    </param-value>
    </context-param>
    
    <listener>
    <listener-class>
        com.yourpackage.StartupListener
    </listener-class>
    </listener>
    

    Hope it helps

    0 讨论(0)
提交回复
热议问题