java使用slf4j+log4j进行日志记录并将ERROR级别信息入库
1.maven 坐标
<!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency>
2.log4j.properties文件(这个文件放到资源目录)
log4j.rootLogger = INFO, info, warn, error, console, db #console level log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n # 每日产生文件 log4j.appender.dailyFile=org.apache.log4j.DailyRollingFileAppender #info level log4j.logger.info = info log4j.appender.info = org.apache.log4j.DailyRollingFileAppender log4j.appender.info.File = D:\\logs\\info.log #log4j.appender.warn.File = /opt/logs/info.log log4j.appender.info.Append = true log4j.appender.info.Threshold = INFO log4j.appender.info.layout = org.apache.log4j.PatternLayout log4j.appender.info.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n log4j.appender.info.filter.infoFilter = org.apache.log4j.varia.LevelRangeFilter log4j.appender.info.filter.infoFilter.LevelMin=INFO log4j.appender.info.filter.infoFilter.LevelMax=INFO #warn Level log4j.logger.warn = warn log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender log4j.appender.warn.File = D:\\logs\\warn.log #log4j.appender.warn.File = /opt/logs/warn.log log4j.appender.warn.Append=true log4j.appender.warn.Threshold=WARN log4j.appender.warn.layout=org.apache.log4j.PatternLayout log4j.appender.warn.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n log4j.appender.warn.datePattern='.'yyyy-MM-dd log4j.appender.warn.filter.warnFilter=org.apache.log4j.varia.LevelRangeFilter log4j.appender.warn.filter.warnFilter.LevelMin=WARN log4j.appender.warn.filter.warnFilter.LevelMax=WARN #error level log4j.logger.error = error log4j.appender.error = org.apache.log4j.DailyRollingFileAppender log4j.appender.error.File = D:\\logs\\error.log #log4j.appender.warn.File = /opt/logs/error.log log4j.appender.error.Append = true log4j.appender.error.Threshold = ERROR log4j.appender.error.layout = org.apache.log4j.PatternLayout log4j.appender.error.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n log4j.appender.error.datePattern='.'yyyy-MM-dd log4j.appender.error.filter.errorFilter=org.apache.log4j.varia.LevelRangeFilter log4j.appender.error.filter.errorFilter.LevelMin=ERROR log4j.appender.error.filter.errorFilter.LevelMax=ERROR # 数据库操作 log4j.appender.db=org.apache.log4j.jdbc.JDBCAppender # error级别错误入库 log4j.appender.db.Threshold=ERROR # 设置缓冲区,每10条错误入库 #log4j.appender.db.BufferSize=10 log4j.appender.db.URL= log4j.appender.db.Driver= log4j.appender.db.user= log4j.appender.db.password= log4j.appender.db.sql= log4j.appender.db.layout=org.apache.log4j.PatternLayout
设置要插入日志信息的格式和内容的SQL解释:
%X{userId}是置取MDC中的key值,
(过滤器中是将用户id和用户姓名放入MDC中,在这里可以用%X{userId}和%X{userName}取出用户的ID和用户姓名;)
'%C'表示日志信息是来自于那个类;
%M表示日志信息来自于那个方法中;
%d{yyyy-MM-dd HH:mm:ss}表示日志信息产生的时间,{yyyy-MM-dd HH:mm:ss}表示一种时间格式,你也可以直接写成%d;
%p表示日志信息的级别(debug info warn error);
%m表示你写入的日志信息
3.测试
import org.apache.log4j.Logger; public class log4jTest { public static Logger logger1 = Logger.getLogger(log4jTest.class); public static void main(String[] args) { logger1.info("我是logger1"); } }
4.封装LogUtils(个人喜欢,也可以不封装,在每个类中定义)
package com.xxx; import java.util.HashMap; import java.util.Map; import org.apache.log4j.*; /** * @author phubing * * 用于记录日志入库等方法 */ public class LogUtils { private static Map<String,Logger> loggerMap = new HashMap<String,Logger>(); public static void debug(Object message){ String className = getClassName(); Logger log = getLogger(className); if(log.isDebugEnabled()){ log.debug(message); } } public static void debug(String tag, Object message){ String className = getClassName(); Logger log = getLogger(className); if(log.isDebugEnabled()){ log.debug(new StringBuffer().append("【").append(tag).append("】").append(message).toString()); } } public static void info(Object message){ String className = getClassName(); Logger log = getLogger(className); if(log.isInfoEnabled()){ log.info(message); } } public static void info(String tag, Object message){ String className = getClassName(); Logger log = getLogger(className); if(log.isInfoEnabled()){ log.info(new StringBuffer().append("【").append(tag).append("】").append(message).toString()); } } public static void warn(Object message){ String className = getClassName(); Logger log = getLogger(className); log.warn(message); } public static void warn(String tag, Object message){ String className = getClassName(); Logger log = getLogger(className); log.warn(new StringBuffer().append("【").append(tag).append("】").append(message).toString()); } public static void error(Object message){ String className = getClassName(); Logger log = getLogger(className); log.error(message); } public static void error(String tag, Object message){ String className = getClassName(); Logger log = getLogger(className); log.error(new StringBuffer().append("【").append(tag).append("】").append(message).toString()); } /** * @author phubing * * 获取最开始的调用者所在类 */ private static String getClassName(){ Throwable th = new Throwable(); StackTraceElement[] stes = th.getStackTrace(); StackTraceElement ste = stes[2]; return ste.getClassName(); } /** * @author phubing * * 根据类名获得logger对象 */ private static Logger getLogger(String className){ Logger log = null; if(loggerMap.containsKey(className)){ log = loggerMap.get(className); }else{ try { log = Logger.getLogger(Class.forName(className)); loggerMap.put(className, log); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return log; } public void insertLog() { } }
5.具体类中使用
LogUtils.error("This is error message");
6.在Logj.properties中配置了数据库连接信息,就会自动入库