log4j1 插入mysql
做任务需要用到这样的需求:
- 使用log4j 1.2进行日志管理。
- 将日志输出到mysql中
- 系统数据库表利用脚本每日生成一张,插入系统运行时特定的表中。
实现方法
- properties(放在项目根目录中)
log4j.rootLogger=info, ServerDailyRollingFile, stdout ,logDB
#这一个为文件输出,并且Daily
log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd
log4j.appender.ServerDailyRollingFile.File=D://logs/notify-subscription.log
log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.ServerDailyRollingFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p [%c] %m%n
log4j.appender.ServerDailyRollingFile.Append=true
#这一个是配置console输出
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
#这一个为配置mysql
log4j.appender.logDB = org.apache.log4j.jdbc.JDBCAppender
log4j.appender.logDB.layout = org.apache.log4j.PatternLayout
log4j.appender.logDB.Driver = com.mysql.jdbc.Driver
log4j.appender.logDB.URL = jdbc:mysql://127.0.0.1:3306/imooc
log4j.appender.logDB.User = root
log4j.appender.logDB.Password = root
log4j.appender.logDB.Sql = INSERT INTO T_log4j(project_name,create_date,level,category,file_name,thread_name,line,all_category,message)values('Struts2','%d{yyyy-MM- ddHH:mm:ss}','%p','%c','%F','%t','%L','%l','%m')
- 代码(其中要进行修改log4j.appender.logDB.Sql的配置值)
static Logger log = Logger.getLogger(Main.class);
public static void main(String[] args) throws FileNotFoundException,
IOException {
String dailySqlString = "INSERT INTO T_log4j_"
+ GetNowDate()
+ "(project_name,create_date,level,category,file_name,thread_name,line,all_category,message)"
+ "values('Struts2','%d{yyyy-MM-ddHH:mm:ss}','%p','%c','%F','%t','%L','%l','%m')";
Properties properties = new Properties();
properties.load(new FileInputStream("log4j.properties"));
properties.setProperty("log4j.appender.logDB.Sql", dailySqlString);
PropertyConfigurator.configure(properties);
//以下为测试
try {
double a = 1 / 0;
} catch (Exception e) {
log.error(e);
}
}
//其中GetNowDate用来获取当前时间:
public static String GetNowDate() {
String temp_str = "";
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
temp_str = sdf.format(dt);
return temp_str;
}
3.结果