log4j配置生成日志保存在数据库

时间:2023-03-08 17:51:46

利用MDC可以存储参数,MDC原理:相当于一个map将值存储起来,调用时可以根据key将自定义的在值存入对应位置(数据库或文件等).使用:

配置文件:log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=info, stdout,Am #log4j.logger.com.dc.erp.dao=info
log4j.appender.Am=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.Am.bufferSize=1
log4j.appender.Am.URL=jdbc:oracle:thin:
log4j.appender.Am.driver=oracle.jdbc.driver.OracleDriver
log4j.appender.Am.Threshold=ERROR
log4j.appender.Am.user=
log4j.appender.Am.password=
log4j.appender.Am.sql=INSERT INTO LOG4J (USERID,USERIP,LOGINTIME,CLASSNAME,SQL,PARAMS,CONTENT,USERNAME) VALUES ('%X{userId}','%X{userIp}','%X{loginTime}','%c','%X{sql}','%X{params}','%m','%X{username}') log4j.appender.Am.layout=org.apache.log4j.PatternLayout

强需要的字段用MDC存储方式:

MDC.put("username","张三");