网上有关java的Log4j写日志大多是web开发,但是我要在一个纯java工程(非web)中写日志。我在网上看到一个例子:
http://blog.csdn.net/tower888/article/details/6452699
我试着用了一下,发现只能在Console写日志,在log4j.properties中配置了很久也没成功在指定的文件中写日志。
我希望在指定位置创建一个log文件,把日志写进去,但就是实现不了。请各位帮我找找原因,谢谢!
这是我的代码,我写了三个java文件,一个log4j.properties,引入了两个jar包:log4j和apache.org.common.logging
1、Log4jConfig类:是用于配置log4j.properties的位置的。
- Java code
package testLog;import org.apache.log4j.PropertyConfigurator;public class Log4jConfig { private static boolean isReload = true; public static void load() { String path = Log4jConfig.class.getClass().getResource("/") .getPath() + "testLog/log4j.properties"; //String path="config/log4j.properties"; System.out.println("log4j configfile path=" + path); PropertyConfigurator.configureAndWatch(path,1000); } private static void reload() { if (isReload) { load(); } isReload = false; } public void setReload(boolean flag) { isReload = flag; } }
2、Logger类,用于写日志的。
- Java code
package testLog;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class Logger { private Log log = null; static{ Log4jConfig.load();//装载log4j配置文件 } private Logger() { log = LogFactory.getLog(this.getClass()); } private Logger(Class c) { log = LogFactory.getLog(c); } private Logger(String className) { log = LogFactory.getLog(className); } public static Logger getLogger() { return new Logger(); } public static Logger getLogger(Class c) { return new Logger(c); } public static Logger getLogger(String className) { return new Logger(className); } public void trace(String info) { if (log.isTraceEnabled()) log.trace(info); } public void debug(String info) { if (log.isDebugEnabled()) log.debug(info); } public void info(String info) { if (log.isInfoEnabled()) log.info(info); } public void warn(String info) { if (log.isWarnEnabled()) log.warn(info); } public void error(String info) { if (log.isErrorEnabled()) log.error(info); } public void fatal(String info) { if (log.isFatalEnabled()) log.fatal(info); } public boolean isTraceEnabled() { return log.isTraceEnabled(); } public boolean isDebugEnabled() { return log.isDebugEnabled(); } public boolean isInfoEnabled() { return log.isInfoEnabled(); } public boolean isWarnEnabled() { return log.isWarnEnabled(); } public boolean isErrorEnabled() { return log.isErrorEnabled(); } public boolean isFatalEnabled() { return log.isFatalEnabled(); } }
3、log4j.properties,用于配置的,是我用添加普通文件的方式创建的。
其实不用写这么多,但是用了这么多配置语句都不起作用啊!
- Java code
log_home=../log
log4j.rootLogger=file,Console
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=C:\gwlog.log
log4j.appender.logfile.DatePattern=.yyyy-MM-dd
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - <%m>%n