Java知识总结----日志系统在项目中的应用(五)

现在的工作过程中,日志在项目中的角色越来越重要,环境出问题了,遇到bug了,我们都要从日志查起。所以在项目中记录日志就显得很重要。今天就跟大家简单聊聊如何在项目中引入日志。

现在市面上比较流行的日志框架有log4j,logback等,大家可能还听说过sjf4j,当然了还有apache的commons-logging,jdk的java.util.log。那么slf4j是什么呢?slf4j,Simple Logging Facade for Java,简单日志门面,只是一个接口,没有具体的实现。它不是具体的日志解决方案,它只服务于各种各样的日志系统。我们可以把各种各样的日志实现接入slf4j,在项目中只使用slf4j就可以了。今天我们就来看看如何把log4j接入slf4j中。

首先我们需要slf4j和log4j的依赖包:log4j的核心包,slf4j的接口包,以及slf4j对log4j的实现包。

 

<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>1.2.17</version>
</dependency>
		
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-api</artifactId>
	<version>1.7.12</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.7.12</version>
</dependency>

然后,我们需要再项目中创建log4j的配置文件,默认在src下,文件名为log4j.properties。配置文件示例内容如下:

 

 

 ### set log levels ###
log4j.rootLogger = info,stdout,file

### 输出到控制台 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =  %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出到文件 ###
log4j.appender.file = org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File = logs/log.log
log4j.appender.file.Append = true
log4j.appender.file.Threshold = DEBUG ## 
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n


log4j.rootLogger:指定了项目的全局配置,第一个参数表示当前工程默认的日志级别,后面的参数表示日志的输出形式。

 

ConsoleAppender:表示输出到控制台,DailyRollingFileAppender:表示每天生成一个日志文件。

ConversionPattern:表示日志的输出格式,其内容代表的具体含义,大家可以参考log4j的其他资料,这里就不一一讲解了。

在项目中的使用也非常简单,只要在类中定义如下的变量即可:

 

private static Logger logger = LoggerFactory.getLogger(UserController.class);


注意:Logger和LoggerFactory都是org.slf4j包下的。

 

在使用的时候直接调用logger.info(),logger.debug().logger.error()即可使用了。

 

如果我们想把jdk的java.util.log和Apache的commons-logging怎么接入slf4j呢?只需要引入一下依赖:

 

<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>jcl-over-slf4j</artifactId>
	<version>1.7.12</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>jul-to-slf4j</artifactId>
	<version>1.7.12</version>
</dependency>

jcl-over-slf4j:把commmons-logging接入slf4j,jul-to-slf4j:把java.util.log接入slf4j。

 

 

下面呢,我们再说说logback。Logback是由log4j创始人设计的又一个开源日志组件。相比较log4j,logback不仅继承了log4j的有点,对log4j也进行了非常大的改进。那么如何在项目中使用logback呢?

首先引入相关的依赖:

 

<!-- log配置 -->
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-api</artifactId>
	<version>1.7.12</version>
</dependency>

<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-core</artifactId>
	<version>1.1.1</version>
</dependency>
<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-classic</artifactId>
	<version>1.1.1</version>
</dependency>
        <dependency>  
	<groupId>org.logback-extensions</groupId>  
	<artifactId>logback-ext-spring</artifactId>  
        <version>0.1.1</version>  
</dependency>
 <!-- logback兼容java.util.log -->
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>jul-to-slf4j</artifactId>
	<version>1.7.6</version>
</dependency>
<!-- for common-logging -->
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>jcl-over-slf4j</artifactId>
	<version>1.7.6</version>
</dependency>
<!-- logback兼容log4j -->
<dependency>
        <groupId>org.slf4j</groupId>
	<artifactId>log4j-over-slf4j</artifactId>
	<version>1.7.6</version>
</dependency>

在上边的要特别注意的是,我们要把log4j也接入slf4j,并且在项目中不能再引入log4j的jar包和slf4j-log4j-*的jar包,这个在打包的时候,要特别注意。

 

然后在src下创建logback的配置文件logback.xml:

 

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
        <property name="log.home" value="/data/application/logs" />
       <!-- 默认输出文件 -->
	<appender name="DEFAULT-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log.home}/default/common-default.log.%d{yyyyMMdd}</fileNamePattern>
			<maxHistory>30</maxHistory>
		</rollingPolicy>
		<encoder charset="UTF-8">
			<pattern>%d [%t] %-5p %c{2} [%X{traceRootId}/%X{userId}/%X{userEmail}/%X{userPhone}] - [%m]%n</pattern>
		</encoder>
	</appender>
	<!-- 默认错误文件 -->
	<appender name="ERROR-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log.home}/error/common-error.log.%d{yyyyMMdd}</fileNamePattern>
		</rollingPolicy>
		<encoder charset="UTF-8">
			<pattern>%d [%t] %-5p %c{2} [%X{traceRootId}/%X{userId}/%X{userEmail}/%X{userPhone}] - [%m]%n</pattern>
		</encoder>
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
    		<level>ERROR</level>
    	</filter>
	</appender>
	<!-- 性能日志文件 -->
	<appender name="PERF-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log.home}/perf/common-perf.log.%d{yyyyMMdd}</fileNamePattern>
			<maxHistory>30</maxHistory>
		</rollingPolicy>
		<encoder charset="UTF-8">
			<pattern>%d [%t] %-5p %c{2} [%X{traceRootId}/%X{userId}/%X{userEmail}/%X{userPhone}] - [%m]%n</pattern>
		</encoder>
	</appender>
	<!-- 默认dao日志文件 -->
	<appender name="DAO-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log.home}/dao/common-dao.log.%d{yyyyMMdd}</fileNamePattern>
			<minIndex>1</minIndex>    
	      	<maxIndex>5</maxIndex>
		</rollingPolicy>
		<encoder charset="UTF-8">
			<pattern>%d [%t] %-5p %c{2} [%X{traceRootId}/%X{userId}/%X{userEmail}/%X{userPhone}] - [%m]%n</pattern>
		</encoder>
	</appender>
	<!-- 默认dlock日志文件 -->
	<appender name="DLOCK-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log.home}/dlock/common-dlock.log.%d{yyyyMMdd}</fileNamePattern>
			<minIndex>1</minIndex>    
	      	<maxIndex>5</maxIndex>
		</rollingPolicy>
		<encoder charset="UTF-8">
			<pattern>%d [%t] %-5p %c{2} [%X{traceRootId}/%X{userId}/%X{userEmail}/%X{userPhone}] - [%m]%n</pattern>
		</encoder>
	</appender>
	<!-- service日志文件 -->
	<appender name="SERVICE-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log.home}/service/common-service.log.%d{yyyyMMdd}</fileNamePattern>
			<maxHistory>30</maxHistory>
		</rollingPolicy>
		<encoder charset="UTF-8">
			<pattern>%d [%t] %-5p %c{2} [%X{traceRootId}/%X{userId}/%X{userEmail}/%X{userPhone}] - [%m]%n</pattern>
		</encoder>
	</appender>
	<!-- 业务日志文件 -->
	<appender name="BUSINESS-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log.home}/business/common-business.log.%d{yyyyMMdd}</fileNamePattern>
			<maxHistory>30</maxHistory>
		</rollingPolicy>
		<encoder charset="UTF-8">
			<pattern>%d [%t] %-5p %c{2} [%X{traceRootId}/%X{userId}/%X{userEmail}/%X{userPhone}] - [%m]%n</pattern>
		</encoder>
	</appender>
	<!-- 报警日志 -->
	<appender name="ALARM-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
      <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 
    		<fileNamePattern>${log.home}/alarm/common-alarm.log.%d{yyyyMMdd}</fileNamePattern> 
    		<maxHistory>30</maxHistory>  
  	</rollingPolicy>                                                                                    
	<encoder charset="UTF-8">
		<pattern>%d [%t] %-5p %c{2} [%X{traceRootId}/%X{userId}/%X{userEmail}/%X{userPhone}] - [%m]%n</pattern>
	</encoder>                                                                                                                                                                                                                                                                                    
	</appender> 
	<appender name="TRACE-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender"> 
	     <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 
	   		<fileNamePattern>${log.home}/trace/tracing.log.%d{yyyy-MM-dd-HH}.gz</fileNamePattern> 
	   		<maxHistory>72</maxHistory>  
	 	</rollingPolicy> 	                                                                                         
	<encoder charset="UTF-8">
		<pattern>%d - [%m]%n</pattern>
	</encoder>                                                                                                                                                                                                                                                                                    
	</appender>
	<logger name="java.sql" additivity="false">
		<level value="INFO"/>
		<appender-ref ref="DAO-APPENDER"/>
		<appender-ref ref="ERROR-APPENDER"/>
	</logger>
	
	<logger name="businessLogger" additivity="false">
		<level value="${log.root.level}"/>
		<appender-ref ref="BUSINESS-APPENDER"/>
		<appender-ref ref="ERROR-APPENDER"/>
	</logger>
	<logger name="serviceLogger" additivity="false">
		<level value="${log.root.level}"/>
		<appender-ref ref="SERVICE-APPENDER"/>
	</logger>
	<!-- 屏蔽logger -->
	<logger name="org.springframework" level="WARN" />
	<logger name="org.apache" level="WARN" />
	<logger name="org.mybatis.spring" level="WARN" />
	<!-- 屏蔽jdk日志 -->
	<logger name="java" level="WARN" />
	<logger name="com.mchange" additivity="false">
		<level value="WARN"/>
		<appender-ref ref="DAO-APPENDER"/>
	</logger>	
	<!-- 屏蔽logger 结束-->
	<root level="${log.root.level}">
		<appender-ref ref="DEFAULT-APPENDER"></appender-ref>
		<appender-ref ref="ALARM-APPENDER"/>
		<appender-ref ref="ERROR-APPENDER"></appender-ref>
	</root>
</configuration> 


logback的配置文件大体上分为3个部分,第一个部分是appender标签,里边配置了不同的appender日志存放的位置,日志格式等信息。第二部分是logger标签,只要指定不同的日志使用不同的appender,用于区分,如businessLogger,表示logger的名字为businessLogger的,日志输出到DEFAULT_APPENDER和ERRPR_APPENDER中。第三部分是root标签,表示项目的全局配置,包括日志级别和默认的日志输出。

 

最后要在web.xml中进行配置:

 

  	<context-param>
		<param-name>logbackConfigLocation</param-name>
		<param-value>classpath:logback.xml</param-value>
	</context-param>
	<listener>
		<listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
	</listener>

 

在使用方式上,和log4j是一样的,使用org.slf4j的两个类即可。

private static Logger logger = LoggerFactory.getLogger(UserController.class);

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(java,log4j,logback,slf4j)