logback + slf4j + jboss + spring mvc

时间:2023-03-09 01:20:17
logback + slf4j + jboss + spring mvc

logbacklog4jlog4j2 全是以同一个人为首的团伙搞出来的(日志专业户!),这几个各有所长,log4j性能相对最差,log4j2性能不错,但是目前跟mybatis有些犯冲(log4j2的当前版本,已经将AbstractLoggerWrapper更名成ExtendedLoggerWrapper,但是mybatis 2.3.7依赖的仍然是旧版本的log4j2,所以mybatis使用log4j2会报错),说到日志,还要注意另一外项目SLF4J( java的世界里,记日志的组件真是多!),SLF4J只一个接口标准,并不提供实现(就好象JSF/JPA 与 RichFaces/Hibernate的关系类似),而LogBack是SLF4J的一个实现,下面介绍logback的基本用法

一、基本用法

1.1 maven依赖项

         <!-- log -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency> <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version>
</dependency> <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency>

1.2 配置文件logback.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="1800 seconds"
debug="false"> <property name="USER_HOME" value="logs" />
<property scope="context" name="FILE_NAME" value="mylog-logback" /> <timestamp key="byDay" datePattern="yyyy-MM-dd" /> <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.rolling.RollingFileAppender">
<file>${USER_HOME}/${FILE_NAME}.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>${USER_HOME}/${byDay}/${FILE_NAME}-${byDay}-%i.log.zip
</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>10</maxIndex>
</rollingPolicy> <triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n
</pattern>
</encoder> </appender> <logger name="com.cnblogs.yjmyzz.App2" level="debug" additivity="true">
<appender-ref ref="file" />
<!-- <appender-ref ref="STDOUT" /> -->
</logger> <root level="info">
<appender-ref ref="STDOUT" />
</root>
</configuration>

1.3 示例程序
跟前面log4j2的示例程序几乎完全一样:

 package com.cnblogs.yjmyzz;

 import org.slf4j.*;

 public class App2 {

     static Logger logger = LoggerFactory.getLogger(App2.class);

     public static void main(String[] args) {
for (int i = 0; i < 100000; i++) {
logger.trace("trace message " + i);
logger.debug("debug message " + i);
logger.info("info message " + i);
logger.warn("warn message " + i);
logger.error("error message " + i);
}
System.out.println("Hello World! 2");
}
}

运行后,会在当前目录下创建logs目录,生成名为mylog-logback.log的日志文件,该文件体积>5M后,会自动创建 yyyy-mm-dd的目录,将历史日志打包生成类似:mylog-logback-2014-09-24-1.log.zip 的压缩包,每天最多保留10个

二、与spring -mvc的集成 

2.1 maven依赖项

注:${springframework.version},我用的是3.2.8.RELEASE 版本

 <!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${springframework.version}</version>
</dependency> <!-- logback -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency> <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version>
</dependency> <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency> <!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>

2.2 web.xml里增加下面的内容

 <!-- logback-begin -->
<context-param>
<param-name>logbackConfigLocation</param-name>
<param-value>classpath:logback.xml</param-value>
</context-param>
<listener>
<listener-class>com.cnblogs.yjmyzz.util.LogbackConfigListener</listener-class>
</listener>
<!-- logback-end -->

其中com.cnblogs.yjmyzz.util.LogbackConfigListener 是自己开发的类,代码如下:(从网上掏来的)

注:该处理方式同样适用于struts 2.x

 package com.cnblogs.yjmyzz.util;

 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());
}
}

LogbackConfigListener

 package com.cnblogs.yjmyzz.util;

 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));
} }

LogbackWebConfigurer

 package com.cnblogs.yjmyzz.util;

 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());
} }

LogbackConfigurer

2.3 JBOSS EAP 6+ 的特殊处理

jboss 默认已经集成了sf4j模块,会与上面新加的3个类有冲突,app启动时会报错:

java.lang.ClassCastException: org.slf4j.impl.Slf4jLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext

所以,需要手动排除掉jboss默认的slf4j模块,在web-inf下创建名为jboss-deployment-structure.xml的文件,内容如下:

 <?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
<deployment>
<exclusions>
<module name="org.slf4j" />
<module name="org.slf4j.impl" />
<module name="org.slf4j.jcl-over-slf4j" />
<module name="org.slf4j.ext" />
</exclusions>
</deployment>
</jboss-deployment-structure>

2.4 最后将logback.xml放到resouces目录下即可(打包后,会自动复制到classpath目录下)