logback自定義寫入,和不加載入問題
阿新 • • 發佈:2019-02-20
一,自定寫入日誌到檔案
其實寫入的日誌內容是通過MDC將內容寫入,這裡需要注意的是,在logback.xml的檔案中取值要對應MDC中的key值。
下面提供介面和實現類例項:
public interface ILogService
{
/**
* 在Spring中使用時建立的Bean名稱.
*/
public static final String SERVICE_BEAN_NAME = "logService";
public void writeOutLog(String jobID,String jName, String jobStartTime,String jobRunTime,String jobRunResult,String description);
}
package com.logstatistics.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.stereotype.Service;
import com.southgis.ibase.logstatistics.consts.LogItemNames;
import com.southgis.ibase.logstatistics.service.ILogService;
@Service (ILogService.SERVICE_BEAN_NAME)
public class LogService implements ILogService
{
/**
* 日誌元件.
*/
private final Logger logger;
/**
* 預設建構函式.
*/
public LogService()
{
this.logger = LoggerFactory.getLogger(LogService.class);
}
@Override
public void writeOutLog(String jobID,String jName ,String jobStartTime, String jobRunTime, String jobRunResult,String description) {
if (jobID == null){
jobID="";
}
if(jName == null){
jName="";
}
if(jobStartTime == null){
jobStartTime="";
}
if(jobRunTime == null){
jobRunTime="";
}
if(jobRunResult == null){
jobRunResult="success";
}
MDC.put(LogItemNames.JOBID, jobID);
MDC.put(LogItemNames.JNAME, jName);
MDC.put(LogItemNames.JOBSTARTTIME, jobStartTime);
MDC.put(LogItemNames.JOBRUNTIME, jobRunTime);
MDC.put(LogItemNames.JOBRUNRESULT, jobRunResult);
Marker marker = MarkerFactory.getMarker(LogItemNames.JOB_MARKER);
this.logger.info(marker,description);
MDC.remove(LogItemNames.JOBID);
MDC.remove(LogItemNames.JOBSTARTTIME);
MDC.remove(LogItemNames.JOBRUNTIME);
MDC.remove(LogItemNames.JOBRUNRESULT);
}
}
public final class LogItemNames
{
public static final String JOB_MARKER="JOBMARKER";
public static final String JOBID="JOBID";
public static final String JOBRUNTIME="JOBRUNTIME";
public static final String JOBRUNRESULT="JOBRUNRESULT";
public static final String JOBSTARTTIME="JOBSTARTTIME";
public static final String JNAME="JNAME";
}
只需要將logback.xml放到src目錄下便會自動載入。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- Linux: /usr/logs
Windows: D:/logs -->
<property name="logRoot" value="D:/logs" />
<property name="logModule" value="main" />
<appender name="JOBLOG"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator class="ch.qos.logback.classic.boolex.OnMarkerEvaluator">
<marker>JOBMARKER</marker>
</evaluator>
<OnMismatch>DENY</OnMismatch>
<OnMatch>NEUTRAL</OnMatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logRoot}/${logModule}/jobscheduleLog/%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern> [jobID: %X{JOBID}] [jName: %X{JNAME}] [jobStartTime: %X{JOBSTARTTIME}] [jobRunTime: %X{JOBRUNTIME}秒] [jobRunResult: %X{JOBRUNRESULT}] %logger - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<fileNamePattern>${logRoot}/${logModule}/errorLog/%d{yyyy-MM-dd}.log</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logRoot}/${logModule}/errorLog/%d{yyyy-MM-dd}.log.zip</fileNamePattern>
<maxHistory>5</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg [%file:%line] %n</pattern>
</encoder>
</appender>
<logger name="com.logstatistics.service;" level="DEBUG">
<appender-ref ref="JOBLOG" />
</logger>
<root level="DEBUG">
<appender-ref ref="FILE" />
</root>
</configuration>
想要對應內容的寫出到日誌時可以在類中引入服務呼叫方法即可以:
1,獲得日誌物件
ILogService mLogService= (ILogService) wac.getBean(ILogService.SERVICE_BEAN_NAME);
2,獲得日誌物件:
@Inject
@Named(ILogService.SERVICE_BEAN_NAME)
private ILogService mLogService;
將結果記錄到日誌
mLogService.writeOutLog(Rid, Jname,startTimeString,
Long.toString(runtime), exception, null);
二,SLF4J包衝突引起logback.xml不載入,導致日誌不能寫出。
我們在用maven的時候可能會引入相同slf4j,導致logback不能載入。一般這類解決方法就是去除相同的包,或者用下面的方法解決忽略相同的包。
下面給出Tomcat啟動時報出的衝突資訊,這個不留心看真的看不出。
1,有衝突的Tomcat資訊,這裡activemq-all-5.7.0.jar中也slf4j包導致logback中的載入衝突:
息: No Spring WebApplicationInitializer types detected on classpath
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/eclipseworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/casWebService/WEB-INF/lib/cas-server-core-4.1.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/eclipseworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/casWebService/WEB-INF/lib/log4j-slf4j-impl-2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/eclipseworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/casWebService/WEB-INF/lib/slf4j-log4j12-1.7.20.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Multiple ILoggerFactory bindings are found on the classpath:
SLF4J: * org.apache.logging.slf4j.Log4jLoggerFactory
SLF4J: * org.slf4j.impl.Log4jLoggerFactory
SLF4J: ILoggerFactory to be used for logging is: org.apache.logging.slf4j.Log4jLoggerFactory
SLF4J: Actual binding is of type [org.slf4j.impl.CasLoggerFactory]
SLF4J: The following set of substitute loggers may have been accessed
SLF4J: during the initialization phase. Logging calls during this
SLF4J: phase were not honored. However, subsequent logging calls to these
SLF4J: loggers will work as normally expected.
SLF4J: See also http://www.slf4j.org/codes.html#substituteLogger
SLF4J: org.reflections.Reflections
資訊: No Spring WebApplicationInitializer types detected on classpath
SLF4J: Class path contains multiple SLF4J bindings.
***SLF4J: Found binding in [jar:file:/D:/eclipseworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/mainWeb/WEB-INF/lib/activemq-all-5.7.0.jar!/org/slf4j/impl/StaticLoggerBinder.class]***
***SLF4J: Found binding in [jar:file:/D:/eclipseworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/mainWeb/WEB-INF/lib/logback-classic-1.1.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]***
***SLF4J: Found binding in [jar:file:/D:/eclipseworkspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/mainWeb/WEB-INF/lib/slf4j-log4j12-1.7.20.jar!/org/slf4j/impl/StaticLoggerBinder.class]***
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]