【1】从零开始
a). 新建Java Project>>新建package>>新建java类;
b). import jar包(一个就够),这里我用的是log4j-1.2.14.jar,
c). 新建log4j.properties,置于project根目录下;
log4j.rootLogger=info, ServerDailyRollingFile, stdout
log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd
log4j.appender.ServerDailyRollingFile.File=C://logs/notify-subscription.log
log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.ServerDailyRollingFile.layout.ConversionPattern=%d - %m%n
log4j.appender.ServerDailyRollingFile.Append=truelog4j.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
d). 在main()中,加载log4j:
PropertyConfigurator.configure("log4j.properties");
e). 写个小程序测试下,好了,我们看下效果:
【神马】找不到文件exception?
1). 用绝对路径,真心不推荐啊,太不优雅了;
2). 将log4j文件置于bin/目录下:
a). 代码中,PropertyConfigurator.configure("bin/log4j.properties");
b). 代码中,PropertyConfigurator.configure(ClassLoader.getSystemResource("log4j.properties"));
c). 注意,必须位于bin直接目录下,不可位于bin更深层的目录当中。可是这究竟是为神马捏?
可参考: http://blog.sina.com.cn/s/blog_3f4755c70100jco1.html
3) 必杀技:
private static void initLog4j() {
Properties prop = new Properties();
prop.setProperty("log4j.rootLogger", "DEBUG, CONSOLE");
prop.setProperty("log4j.appender.CONSOLE", "org.apache.log4j.ConsoleAppender");
prop.setProperty("log4j.appender.CONSOLE.layout", "org.apache.log4j.PatternLayout");
prop.setProperty("log4j.appender.CONSOLE.layout.ConversionPattern", "%d{HH:mm:ss,SSS} [%t] %-5p %C{1} : %m%n");
PropertyConfigurator.configure(prop);
}
【2】log4j 格式详解
log4j.rootLogger=日志级别,appender1, appender2, ….
log4j.appender.appender1=org.apache.log4j.日志输出到哪儿
log4j.appender.appender1.File=文件目录及文件
${user.home}/logs/...
log4j.appender.appender1.MaxFileSize=最大文件大小
log4j.appender.appender1.MaxBackupIndex=备份文件个数
log4j.appender.ServerDailyRollingFile.DatePattern=日志后缀格式
log4j.appender.appender1.layout=org.apache.log4j.日志布局格式
log4j.appender.appender1.layout.ConversionPattern=日志输出格式
log4j.appender.ServerDailyRollingFile.Append=true
总结一下: