paulwong

SPRINGMVC增加LOGBACK

Maven的pom.xml增加两个JAR
<dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.2</version>      
</dependency>
      
<dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.0.9</version>      
</dependency>


web.xml
<!-- spring logback -->  
<context-param>  
    <param-name>logbackConfigLocation</param-name>  
    <param-value>classpath:logback.xml</param-value>  
</context-param>    
<listener>  
    <listener-class>mypackage.LogbackConfigListener</listener-class>  
</listener>  


logback.xml
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>bookstore.log</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <logger name="org.springframework" level="INFO" />
    <logger name="org.springframework.web" level="INFO" />


    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <!-- <appender-ref ref="FILE" /> -->
    </root>

</configuration>



LogbackConfigurer.java
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;

import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;


public abstract class LogbackConfigurer {

    /** Pseudo URL prefix for loading from the class path: "classpath:" */
    public static final String       CLASSPATH_URL_PREFIX = "classpath:";

    /** Extension that indicates a logback XML config file: ".xml" */
    public static final String       XML_FILE_EXTENSION   = ".xml";

    private static LoggerContext     lc                   = (LoggerContext) LoggerFactory.getILoggerFactory();
    private static JoranConfigurator configurator         = new JoranConfigurator();

    /**
     * Initialize logback from the given file location, with no config file refreshing. Assumes an XML file in case of a ".xml" file extension, and a properties file otherwise.
     * 
     * 
@param location
     *            the location of the config file: either a "classpath:" location (e.g. "classpath:mylogback.properties"), an absolute file URL (e.g. "file:C:/logback.properties), or a plain absolute path in the file system (e.g. "C:/logback.properties")
     * 
@throws FileNotFoundException
     *             if the location specifies an invalid file path
     
*/
    public static void initLogging(String location) throws FileNotFoundException {
        String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);
        URL url = ResourceUtils.getURL(resolvedLocation);
        if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION)) {
//            DOMConfigurator.configure(url);
            configurator.setContext(lc);
            lc.reset();
            try {
                configurator.doConfigure(url);
            } catch (JoranException ex) {
                throw new FileNotFoundException(url.getPath());
            }
            lc.start();
        }
//        else {
//            PropertyConfigurator.configure(url);
//        }
    }

    /**
     * Shut down logback, properly releasing all file locks.
     * <p>
     * This isn't strictly necessary, but recommended for shutting down logback in a scenario where the host VM stays alive (for example, when shutting down an application in a J2EE environment).
     
*/
    public static void shutdownLogging() {
        lc.stop();
    }

    /**
     * Set the specified system property to the current working directory.
     * <p>
     * This can be used e.g. for test environments, for applications that leverage logbackWebConfigurer's "webAppRootKey" support in a web environment.
     * 
     * 
@param key
     *            system property key to use, as expected in logback configuration (for example: "demo.root", used as "${demo.root}/WEB-INF/demo.log")
     * 
@see org.springframework.web.util.logbackWebConfigurer
     
*/
    public static void setWorkingDirSystemProperty(String key) {
        System.setProperty(key, new File("").getAbsolutePath());
    }

}


LogbackWebConfigurer.java
import java.io.FileNotFoundException;

import javax.servlet.ServletContext;

import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;
import org.springframework.web.util.WebUtils;

public abstract class LogbackWebConfigurer {

    /** Parameter specifying the location of the logback config file */
    public static final String CONFIG_LOCATION_PARAM     = "logbackConfigLocation";

    /** Parameter specifying the refresh interval for checking the logback config file */
    public static final String REFRESH_INTERVAL_PARAM    = "logbackRefreshInterval";

    /** Parameter specifying whether to expose the web app root system property */
    public static final String EXPOSE_WEB_APP_ROOT_PARAM = "logbackExposeWebAppRoot";

    /**
     * Initialize logback, including setting the web app root system property.
     * 
     * 
@param servletContext
     *            the current ServletContext
     * 
@see WebUtils#setWebAppRootSystemProperty
     
*/
    public static void initLogging(ServletContext servletContext) {
        // Expose the web app root system property.
        if (exposeWebAppRoot(servletContext)) {
            WebUtils.setWebAppRootSystemProperty(servletContext);
        }

        // Only perform custom logback initialization in case of a config file.
        String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
        if (location != null) {
            // Perform actual logback initialization; else rely on logback's default initialization.
            try {
                // Return a URL (e.g. "classpath:" or "file:") as-is;
                
// consider a plain file path as relative to the web application root directory.
                if (!ResourceUtils.isUrl(location)) {
                    // Resolve system property placeholders before resolving real path.
                    location = SystemPropertyUtils.resolvePlaceholders(location);
                    location = WebUtils.getRealPath(servletContext, location);
                }

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

                // Initialize without refresh check, i.e. without logback's watchdog thread.
                LogbackConfigurer.initLogging(location);

            } catch (FileNotFoundException ex) {
                throw new IllegalArgumentException("Invalid 'logbackConfigLocation' parameter: " + ex.getMessage());
            }
        }
    }

    /**
     * Shut down logback, properly releasing all file locks and resetting the web app root system property.
     * 
     * 
@param servletContext
     *            the current ServletContext
     * 
@see WebUtils#removeWebAppRootSystemProperty
     
*/
    public static void shutdownLogging(ServletContext servletContext) {
        servletContext.log("Shutting down logback");
        try {
            LogbackConfigurer.shutdownLogging();
        } finally {
            // Remove the web app root system property.
            if (exposeWebAppRoot(servletContext)) {
                WebUtils.removeWebAppRootSystemProperty(servletContext);
            }
        }
    }

    /**
     * Return whether to expose the web app root system property, checking the corresponding ServletContext init parameter.
     * 
     * 
@see #EXPOSE_WEB_APP_ROOT_PARAM
     
*/
    private static boolean exposeWebAppRoot(ServletContext servletContext) {
        String exposeWebAppRootParam = servletContext.getInitParameter(EXPOSE_WEB_APP_ROOT_PARAM);
        return (exposeWebAppRootParam == null || Boolean.valueOf(exposeWebAppRootParam));
    }

}


LogbackConfigListener.java
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class LogbackConfigListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        LogbackWebConfigurer.initLogging(event.getServletContext());
    }

    public void contextDestroyed(ServletContextEvent event) {
        LogbackWebConfigurer.shutdownLogging(event.getServletContext());
    }
}



posted on 2013-11-11 13:44 paulwong 阅读(4747) 评论(0)  编辑  收藏 所属分类: SPRINGSPRING MVC


只有注册用户登录后才能发表评论。


网站导航: