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目录下)

logback + slf4j + jboss + spring mvc的更多相关文章

  1. Spring MVC集成slf4j-logback

    转自: Spring MVC集成slf4j-logback 1.  Spring MVC集成slf4j-log4j 关于slf4j和log4j的相关介绍和用法,网上有很多文章可供参考,但是关于logb ...

  2. mybatis 3.2.7 与 spring mvc 3.x、logback整合

    github上有一个Mybatis-Spring的项目,专门用于辅助完成mybatis与spring的整合,大大简化了整合难度,使用步骤: 准备工作: maven依赖项: <properties ...

  3. Java日志框架-Spring中使用Logback(Spring/Spring MVC)

    继上一篇文章http://www.cnblogs.com/EasonJim/p/7800880.html中所集成的是基于Java的普通项目,如果要在Spring和Spring MVC上集成,需要做如下 ...

  4. jboss developers studio 快速创建 spring mvc 项目

    1. 2. 部署运行 还有一个 rest very good !! ps:其实就是 一个 jboss 的 spring mvc maven 原型

  5. IntelliJ IDEA 13.x 下使用Hibernate + Spring MVC + JBoss 7.1.1

    从2004年开始做.NET到现在.直到最近要做一些JAVA的项目,如果说100个人写一篇关于.NET的文章,估计这10个人写的内容都是一样.但是如果说10个人写Java的文章,那真的是10个人10种写 ...

  6. spring boot 1.x完整学习指南(含各种常见问题servlet、web.xml、maven打包,spring mvc差别及解决方法)

    spring boot 入门 关于版本的选择,spring boot 2.0开始依赖于 Spring Framework 5.1.0,而spring 5.x和之前的版本差距比较大,而且应该来说还没有广 ...

  7. Spring MVC教程——检视阅读

    Spring MVC教程--检视阅读 参考 Spring MVC教程--一点--蓝本 Spring MVC教程--c语言中午网--3.0版本太老了 Spring MVC教程--易百--4.0版本不是通 ...

  8. spring mvc+ELK从头开始搭建日志平台

    最近由于之前协助前公司做了点力所能及的事情,居然收到了一份贵重的端午礼物,是给我女儿的一个乐高积木,整个有7大包物件,我花了接近一天的时间一砖一瓦的组织起来,虽然很辛苦但是能够从过程中体验到乐趣.这次 ...

  9. 使用Maven创建一个Spring MVC Web 项目

    使用Maven创建java web 项目(Spring MVC)用到如下工具: 1.Maven 3.2 2.IntelliJ IDEA 13 3.JDK 1.7 4.Spring 4.1.1 rele ...

随机推荐

  1. 系统吞吐量、TPS(QPS)、用户并发量、性能测试概念和公式

    PS:下面是性能测试的主要概念和计算公式,记录下: 一.系统吞度量要素: 一个系统的吞度量(承压能力)与request对CPU的消耗.外部接口.IO等等紧密关联.单个reqeust 对CPU消耗越高, ...

  2. RFID应用范围

    RFID应用范围 (1)物流: 物流过程中的货物追踪,信息自动采集,仓储应用,港口应用,邮政,快递 (2)零售: 商品的销售数据实时统计,补货,防盗 (3)制造业: 生产数据的实时监控,质量追踪,自动 ...

  3. spring annotation简述

    一.Annotation基本概念 Annotation是jdk5以后出现的新特性,在jdk中,其内置了许多自己的Annotation,例如@Override,@SuppresWarning,@Depr ...

  4. 0016 Java学习笔记-异常-如果try-catch-finally中都存在return语句会怎样?

    上午在搜索"System.runFinalization"的时候,搜到 http://www.cnblogs.com/Skyar/p/5962253.html ,其中有关于try- ...

  5. 伪造http的ip地址,突破ip限制的投票程序

    某WEB投票程序, 使用 ip 限制和cookie限制技术,来限制每个ip每天只能投一次票,使用的是php开发,获取访问者的 ip 使用了搜狐的接口: http://txt.go.sohu.com/i ...

  6. Vim指令备忘

    从网上找来的记忆图,适合于刚上手的童鞋形象记忆. 接下来的是个人在使用过程中容易忘记的命令,特此备份查看. n<space> 会向右移动这一行的n 个字元 n<Enter> 向 ...

  7. 优化SQL查询:如何写出高性能SQL语句

    1. 首先要搞明白什么叫执行计划? 执行计划是数据库根据SQL语句和相关表的统计信息作出的一个查询方案,这个方案是由查询优化器自动分析产生的,比如一条SQL语句如果用来从一个 10万条记录的表中查1条 ...

  8. CSS background-position 用法详细介绍

    语法: background-position : length || length background-position : position || position 取值: length  : ...

  9. Java开发之Servlet生命周期

    Servlet会在服务器启动或第一次请求该Servlet的时候开始生命周期,在服务器结束的时候结束生命周期.无论请求多少次Servlet,最多只有一个Servlet实例.多个客户端并发请求Servle ...

  10. POJ 2540 Hotter Colder --半平面交

    题意: 一个(0,0)到(10,10)的矩形,目标点不定,从(0,0)开始走,如果走到新一点是"Hotter",那么意思是离目标点近了,如果是"Colder“,那么就是远 ...