logback externalization

前端 未结 5 1245
庸人自扰
庸人自扰 2021-02-07 23:26

Currently I have logback configuration file i.e logback.xml which is src/main/resources. I want to set the logging level but i want control outside of

5条回答
  •  时光取名叫无心
    2021-02-07 23:49

    I've managed to put an external configuration file with tomcat/Spring logback

    Context file of tomcat :

    
    
    
    
    

    web.xml :

    
        contextConfigLocation
        
            classpath:/web-application-context.xml
        
    
    
        org.springframework.web.context.ContextLoaderListener
    
    
    
        com.package.client.servlet.LogbackConfiguratorContextListener
    
    

    web-application-context.xml

    
    
    
    
    
        
    
    
    
    

    the logback configurator class:

    package com.package.client.servlet;
    
    import java.io.File;
    import java.io.IOException;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    import org.apache.commons.lang.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.core.io.Resource;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    
    import ch.qos.logback.classic.BasicConfigurator;
    import ch.qos.logback.classic.LoggerContext;
    import ch.qos.logback.classic.joran.JoranConfigurator;
    import ch.qos.logback.classic.util.ContextInitializer;
    import ch.qos.logback.core.joran.spi.JoranException;
    
    /**
     * Servlet context listener in order to use an external configuration file for logback.
     * 
     */
    public class LogbackConfiguratorContextListener implements ServletContextListener
    {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(LogbackConfiguratorContextListener.class);
    
        /**
         * Logback configuration file uri.
         */
        @Value("#{environnementProperties['logback.configuration.file.uri']}")
        private String logbackConfigurationUri;
    
        /**
         * Configuration path resource for configuration files.
         */
        @Value("#{configurationPathResource}")
        private Resource configurationPathResource;
    
        /**
         * initialize logback with external configuration file.
         */
        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent)
        {
            autowireThis(servletContextEvent.getServletContext());
            Resource logbackConfigurationResource = null;
            if (StringUtils.isNotBlank(logbackConfigurationUri))
            {
                if (StringUtils.containsAny(logbackConfigurationUri, new char[] { '/', '\\' }))
                {
                    logbackConfigurationResource = new FileSystemResource(logbackConfigurationUri);
                }
                else if (configurationPathResource != null)
                {
                    try
                    {
                        logbackConfigurationResource = new FileSystemResource(new File(configurationPathResource.getFile(),
                                logbackConfigurationUri));
                    }
                    catch (IOException exception)
                    {
                        LOGGER.error("Can't read resource " + configurationPathResource.getFilename(), exception);
                    }
                }
            }
            if (logbackConfigurationResource != null)
            {
                if (logbackConfigurationResource.exists())
                {
                    LOGGER.info("Found logback configuration " + logbackConfigurationResource.getDescription()
                            + " - Overriding default configuration");
                    JoranConfigurator configurator = new JoranConfigurator();
                    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
                    loggerContext.reset();
                    configurator.setContext(loggerContext);
                    try
                    {
                        configurator.doConfigure(logbackConfigurationResource.getFile());
                        LOGGER.info("default configuration overrided by logback configuration "
                                + logbackConfigurationResource.getDescription());
                    }
                    catch (Exception exception)
                    {
                        try
                        {
                            new ContextInitializer(loggerContext).autoConfig();
                        }
                        catch (JoranException e)
                        {
                            BasicConfigurator.configureDefaultContext();
                            LOGGER.error("Can't configure default configuration", exception);
                        }
                        LOGGER.error(
                                "Can't configure logback with specified " + logbackConfigurationResource.getDescription()
                                        + " - Keep default configuration", exception);
                    }
                }
                else
                {
                    LOGGER.error("Can't read logback configuration specified file at "
                            + logbackConfigurationResource.getDescription() + " - Keep default configuration");
                }
            }
            else
            {
                LOGGER.info("No logback configuration file specified - Keep default configuration");
            }
        }
    
        /**
         * Autowire this bean by spring
         * @param servletContext le contexte de la servlet
         */
        private void autowireThis(ServletContext servletContext)
        {
            WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getAutowireCapableBeanFactory()
                    .autowireBean(this);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce)
        {
        }
    }
    

    and finally the environnement.properties

    # Configuration file
    logback.configuration.file.uri=C:/Users/olejacques/applications/appName/cfg/log.xml
    

提交回复
热议问题