slf4j日志工具类

工具类:

import java.io.Serializable;
import java.util.Objects;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MarkerIgnoringBase;
import org.slf4j.helpers.MessageFormatter;
import org.slf4j.spi.LocationAwareLogger;

/**
 * slf4j日志工具类
 * @author zql
 * @createTime 2020-12-13 22:49:28
 * @version 1.0
 *
 */
public class LogUtils {
	
	/**
	 * 默认日志级别
	 */
	private static Level LEVEL = Level.INFO;
	
	/**
	 * 默认日志最低输出级别
	 */
	private static Level PRIORITY = Level.INFO;
	
	/**
	 * 默认日志输出编码UTF-8
	 */
	private static String ENCODING = "utf-8";

	/**
	 * 默认日志文件名
	 */
	private static String LOG_FILE_NAME = "info";
	
	/**
	 * 用于获取org.apache.log4j.Logger
	 * @author zql
	 * @createTime 2020-12-13 22:51:11
	 *
	 * @return
	 */
	private static org.apache.log4j.Logger getlog4jLogger() {
		String code = LogUtils.LOG_FILE_NAME;
		
		// 判断logger是否已经存在,logger存在且该logger已配置code命名appender则直接返回
		if (Objects.nonNull(LogManager.exists(code))) {
			org.apache.log4j.Logger logger = LogManager.getLogger(code);
			if (Objects.nonNull(logger)) {
				return logger;
			}
		}
		
		// 生成logger
		org.apache.log4j.Logger logger = LogManager.getLogger(code);
		
		// 不继承父类的Additivity
		logger.setAdditivity(true);
		// 设置日志级别
		logger.setLevel(LogUtils.LEVEL);
		// 生成新的Additivity
		RollingFileAppender appender = new RollingFileAppender();
		// 重命名appender
		appender.setName(code);
		
		// log的输出形式
		PatternLayout layout = new PatternLayout();
		String cp = "[ %p ] [%d{yyyy-MM-dd HH:mm:ss,SSS} %l ]:%m%n";
		layout.setConversionPattern(cp);
		appender.setLayout(layout);
		// 日志输出路径,实际通过项目配置文件进行读取
		String logOutPath = "E:\\logs";
		appender.setFile(logOutPath + "\\" + code + ".log");
		// log文件备份数量
		appender.setMaxBackupIndex(10);
		// log文件大小
		appender.setMaxFileSize("30MB");
		// log的文字码
		appender.setEncoding(LogUtils.ENCODING);
		// 设置日志信息的最低输出级别
		appender.setThreshold(LogUtils.PRIORITY);
		// true:在已存在log文件后面追加,false:新log覆盖以前的log
		appender.setAppend(true);
		// 适用当前的配置
		appender.activateOptions();
		
		// 默认不输出到控制台,实际通过项目配置文件进行读取
		boolean isOutConsole = true;
		ConsoleAppender console = null;
		if (isOutConsole) {
			console = new ConsoleAppender();
			// 设置控制台最低输出级别
			console.setThreshold(Level.DEBUG);
			console.setLayout(layout);
			console.setEncoding(LogUtils.ENCODING);
			console.activateOptions();
		}
		
		// 将新的Appender设置到Logger中,利用同步代码块防止多线程环境下,同一个logger下加入两个同名appender,导致日志重复打印
		synchronized(LogUtil.class) {
			if (Objects.isNull(logger.getAppender(code))) {
				logger.addAppender(appender);
			}
			if (isOutConsole) {
				logger.addAppender(console);
			}
		}		
		return logger;
	}
	
	/**
	 * 重置日志文件名
	 * @author zql
	 * @createTime 2020-12-13 23:14:49
	 *
	 * @param code
	 */
	public static void resetLogFileName(String code) {
		LogUtils.LOG_FILE_NAME = code;
	}
	
	/**
	 * 重置日志打印级别
	 * @author zql
	 * @createTime 2020-12-13 23:17:01
	 *
	 * @param level
	 */
	public static void setLevel(Level level) {
		LogUtils.LEVEL = level;
	}
	
	/**
	 * 重置日志最低输出级别
	 * @author zql
	 * @createTime 2020-12-13 23:19:16
	 *
	 * @param priority
	 */
	public static void setPriority(Level priority) {
		LogUtils.PRIORITY = priority;
	}
	
	/**
	 * 获取slf4j日志
	 * @author zql
	 * @createTime 2020-12-15 22:20:26
	 *
	 * @return
	 */
	public static Logger getLogger() {
		org.apache.log4j.Logger log4jLogger = LogUtils.getlog4jLogger();
		Logger slf4jLogger = new Log4jLoggerAdapter(log4jLogger);
		return slf4jLogger;
	}
	
	/**
	 * A wrapper over {@link org.apache.log4j.Logger org.apache.log4j.Logger} in
	 * conforming to the {@link Logger} interface.
	 * 
	 * <p>
	 * Note that the logging levels mentioned in this class refer to those defined
	 * in the <a
	 * href="http://logging.apache.org/log4j/docs/api/org/apache/log4j/Level.html">
	 * <code>org.apache.log4j.Level</code></a> class.
	 * 
	 * <p>
	 * The TRACE level was introduced in log4j version 1.2.12. In order to avoid
	 * crashing the host application, in the case the log4j version in use predates
	 * 1.2.12, the TRACE level will be mapped as DEBUG. See also <a
	 * href="http://bugzilla.slf4j.org/show_bug.cgi?id=68">bug 68</a>.
	 * 
	 * @author Ceki G&uuml;lc&uuml;
	 */
	public static class Log4jLoggerAdapter extends MarkerIgnoringBase implements
	    LocationAwareLogger, Serializable {

	  private static final long serialVersionUID = 6182834493563598281L;

	  final transient org.apache.log4j.Logger logger;

	  /**
	   * Following the pattern discussed in pages 162 through 168 of "The complete
	   * log4j manual".
	   */
	  final static String FQCN = Log4jLoggerAdapter.class.getName();

	  // Does the log4j version in use recognize the TRACE level?
	  // The trace level was introduced in log4j 1.2.12.
	  final boolean traceCapable;

	  // WARN: Log4jLoggerAdapter constructor should have only package access so
	  // that
	  // only Log4jLoggerFactory be able to create one.
	  Log4jLoggerAdapter(org.apache.log4j.Logger logger) {
	    this.logger = logger;
	    this.name = logger.getName();
	    traceCapable = isTraceCapable();
	  }

	  private boolean isTraceCapable() {
	    try {
	      logger.isTraceEnabled();
	      return true;
	    } catch (NoSuchMethodError e) {
	      return false;
	    }
	  }

	  /**
	   * Is this logger instance enabled for the TRACE level?
	   * 
	   * @return True if this Logger is enabled for level TRACE, false otherwise.
	   */
	  public boolean isTraceEnabled() {
	    if (traceCapable) {
	      return logger.isTraceEnabled();
	    } else {
	      return logger.isDebugEnabled();
	    }
	  }

	  /**
	   * Log a message object at level TRACE.
	   * 
	   * @param msg
	   *          - the message object to be logged
	   */
	  public void trace(String msg) {
	    logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, null);
	  }

	  /**
	   * Log a message at level TRACE according to the specified format and
	   * argument.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for level TRACE.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arg
	   *          the argument
	   */
	  public void trace(String format, Object arg) {
	    if (isTraceEnabled()) {
	      FormattingTuple ft = MessageFormatter.format(format, arg);
	      logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft
	          .getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log a message at level TRACE according to the specified format and
	   * arguments.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the TRACE level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arg1
	   *          the first argument
	   * @param arg2
	   *          the second argument
	   */
	  public void trace(String format, Object arg1, Object arg2) {
	    if (isTraceEnabled()) {
	      FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
	      logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft
	          .getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log a message at level TRACE according to the specified format and
	   * arguments.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the TRACE level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arguments
	   *          an array of arguments
	   */
	  public void trace(String format, Object... arguments) {
	    if (isTraceEnabled()) {
	      FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
	      logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft
	          .getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log an exception (throwable) at level TRACE with an accompanying message.
	   * 
	   * @param msg
	   *          the message accompanying the exception
	   * @param t
	   *          the exception (throwable) to log
	   */
	  public void trace(String msg, Throwable t) {
	    logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, t);
	  }

	  /**
	   * Is this logger instance enabled for the DEBUG level?
	   * 
	   * @return True if this Logger is enabled for level DEBUG, false otherwise.
	   */
	  public boolean isDebugEnabled() {
	    return logger.isDebugEnabled();
	  }

	  /**
	   * Log a message object at level DEBUG.
	   * 
	   * @param msg
	   *          - the message object to be logged
	   */
	  public void debug(String msg) {
	    logger.log(FQCN, Level.DEBUG, msg, null);
	  }

	  /**
	   * Log a message at level DEBUG according to the specified format and
	   * argument.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for level DEBUG.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arg
	   *          the argument
	   */
	  public void debug(String format, Object arg) {
	    if (logger.isDebugEnabled()) {
	      FormattingTuple ft = MessageFormatter.format(format, arg);
	      logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log a message at level DEBUG according to the specified format and
	   * arguments.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the DEBUG level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arg1
	   *          the first argument
	   * @param arg2
	   *          the second argument
	   */
	  public void debug(String format, Object arg1, Object arg2) {
	    if (logger.isDebugEnabled()) {
	      FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
	      logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log a message at level DEBUG according to the specified format and
	   * arguments.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the DEBUG level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arguments an array of arguments
	   */
	  public void debug(String format, Object... arguments) {
	    if (logger.isDebugEnabled()) {
	      FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
	      logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log an exception (throwable) at level DEBUG with an accompanying message.
	   * 
	   * @param msg
	   *          the message accompanying the exception
	   * @param t
	   *          the exception (throwable) to log
	   */
	  public void debug(String msg, Throwable t) {
	    logger.log(FQCN, Level.DEBUG, msg, t);
	  }

	  /**
	   * Is this logger instance enabled for the INFO level?
	   * 
	   * @return True if this Logger is enabled for the INFO level, false otherwise.
	   */
	  public boolean isInfoEnabled() {
	    return logger.isInfoEnabled();
	  }

	  /**
	   * Log a message object at the INFO level.
	   * 
	   * @param msg
	   *          - the message object to be logged
	   */
	  public void info(String msg) {
	    logger.log(FQCN, Level.INFO, msg, null);
	  }

	  /**
	   * Log a message at level INFO according to the specified format and argument.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the INFO level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arg
	   *          the argument
	   */
	  public void info(String format, Object arg) {
	    if (logger.isInfoEnabled()) {
	      FormattingTuple ft = MessageFormatter.format(format, arg);
	      logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log a message at the INFO level according to the specified format and
	   * arguments.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the INFO level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arg1
	   *          the first argument
	   * @param arg2
	   *          the second argument
	   */
	  public void info(String format, Object arg1, Object arg2) {
	    if (logger.isInfoEnabled()) {
	      FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
	      logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log a message at level INFO according to the specified format and
	   * arguments.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the INFO level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param argArray
	   *          an array of arguments
	   */
	  public void info(String format, Object... argArray) {
	    if (logger.isInfoEnabled()) {
	      FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
	      logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log an exception (throwable) at the INFO level with an accompanying
	   * message.
	   * 
	   * @param msg
	   *          the message accompanying the exception
	   * @param t
	   *          the exception (throwable) to log
	   */
	  public void info(String msg, Throwable t) {
	    logger.log(FQCN, Level.INFO, msg, t);
	  }

	  /**
	   * Is this logger instance enabled for the WARN level?
	   * 
	   * @return True if this Logger is enabled for the WARN level, false otherwise.
	   */
	  public boolean isWarnEnabled() {
	    return logger.isEnabledFor(Level.WARN);
	  }

	  /**
	   * Log a message object at the WARN level.
	   * 
	   * @param msg
	   *          - the message object to be logged
	   */
	  public void warn(String msg) {
	    logger.log(FQCN, Level.WARN, msg, null);
	  }

	  /**
	   * Log a message at the WARN level according to the specified format and
	   * argument.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the WARN level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arg
	   *          the argument
	   */
	  public void warn(String format, Object arg) {
	    if (logger.isEnabledFor(Level.WARN)) {
	      FormattingTuple ft = MessageFormatter.format(format, arg);
	      logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log a message at the WARN level according to the specified format and
	   * arguments.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the WARN level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arg1
	   *          the first argument
	   * @param arg2
	   *          the second argument
	   */
	  public void warn(String format, Object arg1, Object arg2) {
	    if (logger.isEnabledFor(Level.WARN)) {
	      FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
	      logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log a message at level WARN according to the specified format and
	   * arguments.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the WARN level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param argArray
	   *          an array of arguments
	   */
	  public void warn(String format, Object... argArray) {
	    if (logger.isEnabledFor(Level.WARN)) {
	      FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
	      logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log an exception (throwable) at the WARN level with an accompanying
	   * message.
	   * 
	   * @param msg
	   *          the message accompanying the exception
	   * @param t
	   *          the exception (throwable) to log
	   */
	  public void warn(String msg, Throwable t) {
	    logger.log(FQCN, Level.WARN, msg, t);
	  }

	  /**
	   * Is this logger instance enabled for level ERROR?
	   * 
	   * @return True if this Logger is enabled for level ERROR, false otherwise.
	   */
	  public boolean isErrorEnabled() {
	    return logger.isEnabledFor(Level.ERROR);
	  }

	  /**
	   * Log a message object at the ERROR level.
	   * 
	   * @param msg
	   *          - the message object to be logged
	   */
	  public void error(String msg) {
	    logger.log(FQCN, Level.ERROR, msg, null);
	  }

	  /**
	   * Log a message at the ERROR level according to the specified format and
	   * argument.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the ERROR level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arg
	   *          the argument
	   */
	  public void error(String format, Object arg) {
	    if (logger.isEnabledFor(Level.ERROR)) {
	      FormattingTuple ft = MessageFormatter.format(format, arg);
	      logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log a message at the ERROR level according to the specified format and
	   * arguments.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the ERROR level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param arg1
	   *          the first argument
	   * @param arg2
	   *          the second argument
	   */
	  public void error(String format, Object arg1, Object arg2) {
	    if (logger.isEnabledFor(Level.ERROR)) {
	      FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
	      logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log a message at level ERROR according to the specified format and
	   * arguments.
	   * 
	   * <p>
	   * This form avoids superfluous object creation when the logger is disabled
	   * for the ERROR level.
	   * </p>
	   * 
	   * @param format
	   *          the format string
	   * @param argArray
	   *          an array of arguments
	   */
	  public void error(String format, Object... argArray) {
	    if (logger.isEnabledFor(Level.ERROR)) {
	      FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
	      logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
	    }
	  }

	  /**
	   * Log an exception (throwable) at the ERROR level with an accompanying
	   * message.
	   * 
	   * @param msg
	   *          the message accompanying the exception
	   * @param t
	   *          the exception (throwable) to log
	   */
	  public void error(String msg, Throwable t) {
	    logger.log(FQCN, Level.ERROR, msg, t);
	  }

	  public void log(Marker marker, String callerFQCN, int level, String msg,
	      Object[] argArray, Throwable t) {
	    Level log4jLevel;
	    switch (level) {
	    case LocationAwareLogger.TRACE_INT:
	      log4jLevel = traceCapable ? Level.TRACE : Level.DEBUG;
	      break;
	    case LocationAwareLogger.DEBUG_INT:
	      log4jLevel = Level.DEBUG;
	      break;
	    case LocationAwareLogger.INFO_INT:
	      log4jLevel = Level.INFO;
	      break;
	    case LocationAwareLogger.WARN_INT:
	      log4jLevel = Level.WARN;
	      break;
	    case LocationAwareLogger.ERROR_INT:
	      log4jLevel = Level.ERROR;
	      break;
	    default:
	      throw new IllegalStateException("Level number " + level
	          + " is not recognized.");
	    }
	    logger.log(callerFQCN, log4jLevel, msg, t);
	  }

	}
	
}

测试类:

import org.apache.log4j.Level;
import org.slf4j.Logger;
import top.zqlweb.util.tool.LogUtils;

/**
 * slf4j日志工具测试类
 * @author zql
 * @createTime 2020-12-13 22:49:28
 * @version 1.0
 *
 */
public class LogUtilsTest {

    public static void main(String[] args) {
        Logger logger1 = LogUtils.getLogger();
        logger1.info("{}测试info{}", "占位符1", "占位符2");
        // 把DEBUG日志级别的打印到debug.log日志文件下
        LogUtils.resetLogFileName("error");
        Logger logger2 = LogUtils.getLogger();
        logger2.error("{}测试error{}", "占位符1", "占位符2");

        // 重置日志打印输出级别
        LogUtils.setLevel(Level.DEBUG);
        LogUtils.setPriority(Level.DEBUG);
        // 把DEBUG日志级别的打印到debug.log日志文件下
        LogUtils.resetLogFileName("debug");
        LogUtils.getLogger().debug("{}测试debug{}", "占位符1", "占位符2");
    }
}

普通项目需要引入的包
log4j-1.2.17.jar
slf4j-api-1.7.2.jar
slf4j-log4j12-1.7.2.jar

maven项目依赖

    <!-- slf4j -->
	<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
	<dependency>
	  <groupId>org.slf4j</groupId>
	  <artifactId>slf4j-api</artifactId>
	  <version>1.7.2</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
	<dependency>
	  <groupId>org.slf4j</groupId>
	  <artifactId>slf4j-log4j12</artifactId>
	  <version>1.7.2</version>
	</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值