log4j自动生成日志文件配置
生成文件到默认位置:
#生成日志文件 #log4j.appender.systemFile=org.apache.log4j.RollingFileAppender #按天生成 log4j.appender.systemFile=org.apache.log4j.DailyRollingFileAppender log4j.appender.systemFile.layout=org.apache.log4j.PatternLayout #将旧的文件重新命名为年月日结尾 log4j.appender.systemFile.DatePattern = '.'yyyy-MM-dd #log4j.appender.systemFile.layout.ConversionPattern=%l : %m %n log4j.appender.systemFile.layout.ConversionPattern=[%5p] %d{dd-MM-yy HH:mm:ss} : %F %L : %m %n log4j.appender.systemFile.File=D\:/gaeaback/logs/gaeaback.log
生成日志到数据库:首先你需要穿件对应的数据库表,这样你配置中的sql语句才可能会有效执行。
log4j.rootLogger=INFO,stdout log4j.logger.org.springframework.web.servlet=INFO,logfile log4j.logger.org.springframework.beans.factory.xml=INFO,logfile log4j.logger.com.bing.controler=INFO,db log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p [%c] - - <%m>%n #log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender #log4j.appender.logfile.File=${webapp.root}/WEB-INF/logs/exppower.log #log4j.appender.logfile.DatePattern=.yyyy-MM-dd #log4j.appender.logfile.layout=org.apache.log4j.PatternLayout #log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] wang- <%m>%n ######################## # JDBC Appender ####################### #log4j.logger.business=INFO,db #log4j.appender.db=com.neam.commons.MyJDBCAppender log4j.appender.db=org.apache.log4j.jdbc.JDBCAppender log4j.appender.db.BufferSize=1 log4j.appender.db.sqlname=log #log4j.appender.db.driver=net.sourceforge.jtds.jdbc.Driver log4j.appender.db.driver=oracle.jdbc.driver.OracleDriver #log4j.appender.db.URL=jdbc:jtds:SqlServer://localhost:1433;DatabaseName=pubs log4j.appender.db.URL=jdbc:oracle:thin:@127.0.0.1:1521:orcl log4j.appender.db.user=uername log4j.appender.db.password=password log4j.appender.db.sql=insert into T_LOG (FID,LogName,UserName,Class,Mothod,createTime,LogLevel,MSG,DATESTAMP) values(sys_guid(),'%X{userId}','%X{userName}','%C','%M','%d{yyyy/MM/dd HH:mm:ss}','%p','%m',sysdate) log4j.appender.db.layout=org.apache.log4j.PatternLayout
上面的配置中'%X{userId}','%X{userName}'这两个变量是用户加进去的。在org.apache.log4j.MDC这个类中有个静态的普通方法,用法如下
MDC.put("userId",customer.getUserName());
MDC.put("userName",customer.getUserId());
当调用put方法是后,MDC中存在一个静态变量以键值对的形式来存储加入的值。执行过这个方法后,就能在配置文件中读取到