log4j.properties
log4j.rootLogger=DEBUG,console,f,n
log.rootdir =/data/online/logs/shortlink/
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.encoding=UTF-8
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss:SSS}][%t][%l][%p] %m%n
log4j.appender.console.Threshold = INFO
log4j.appender.f = org.apache.log4j.DailyRollingFileAppender
log4j.appender.f.encoding=UTF-8
log4j.appender.f.File = ${log.rootdir}/error.log
log4j.appender.f.Append = true
log4j.appender.f.Threshold = ERROR
log4j.appender.f.layout = org.apache.log4j.PatternLayout
log4j.appender.f.layout.ConversionPattern = [%d{yyyy-MM-dd HH:mm:ss:SSS}][%t][%l][%p] %m%n
#log4j.appender.n = org.apache.log4j.DailyRollingFileAppender
log4j.appender.n.encoding=UTF-8
log4j.appender.n.File = ${log.rootdir}/debug.log
log4j.appender.n.Append = true
log4j.appender.n.Threshold = INFO
log4j.appender.n.layout = org.apache.log4j.PatternLayout
log4j.appender.n.layout.ConversionPattern = [%d{yyyy-MM-dd HH:mm:ss:SSS}][%t][%l][%p] %m%n
log4j.logger.org.apache.http=OFF
log4j.logger.io.netty=OFF
log4j.logger.org.springframework=INFO,n
log4j.logger.org.apache=WARN,n
log4j.logger.com.tencent.tdbank.busapi=ERROR,f
#以下配置为将日志写入数据库,特别注意自定义的db不能只写在log4j.rootLogger中,
#也就是这里必须要有log4j.logger.db=INFO,db
log4j.appender.db.Threshold = INFO
#达到数量插入记录
log4j.appender.db.bufferSize=1
log4j.appender.db=org.apache.log4j.jdbc.JDBCAppender
#连接数据库的驱动-这里根据自己使用的数取库去填写
log4j.appender.dbDriver=com.mysql.jdbc.Driver
#连接数据库的地址我这里使用的oracle的地址
log4j.appender.db.URL=jdbc:mysql://localhost:3306/urlwork?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
#连接数据库的用户名
log4j.appender.db.user=root
#密码
log4j.appender.db.password=root
#创建记录的sql--这里需要自己手动去创建一个记录表,注意表列名一一对应,本人测试日期类型必须为varchar2,不知道是不是oracle的问题
#log4j.appender.db.sql=insert into WDZLOG (Class,Mothod,CreateTime,LogLevel,LogLine,MSG) values ("%C","%M","%d{yyyy-MM-dd HH:mm:ss}","%p","%l","%m")
log4j.appender.db.sql=insert into WDZLOG (create_time,short_url,long_url,ip,cookie_value,user_id) values ("%d{yyyy-MM-dd HH:mm:ss}","%X{shortUrl}","%X{longUrl}","%X{ip}","%X{cookieValue}","%X{userId}")
log4j.appender.db.layout=org.apache.log4j.PatternLayout
log4j.additivity.db = false
代码中的“x{}”为占位符,需要在代码中手动设置值,设置的代码如下:使用log4j的MDC设置参数的值,类似Map的使用
package com.tencent.aics.shortlink.utils;
import org.apache.log4j.MDC;
/**
* 封装操作日志工具类
*/
public class LogUtil {
public static void putValue(String shortUrl, String longUrl, String ip, int userId, String cookieValue) {
MDC.put("shortUrl",shortUrl);
MDC.put("longUrl",longUrl);
MDC.put("ip",ip);
MDC.put("cookieValue",cookieValue);
MDC.put("userId",userId);
}
}
在类中使用输出日志:
static final Logger LOG = LoggerFactory.getLogger("db");
LOG.info("visit<|>"+shortUrl);
注意只能使用这个构造函数获取日志器