logback自定义写入,和不加加载问题

一,自定写入日志到文件
其实写入的日志内容是通过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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值