我尝试使用log4j创建一个静态记录器。使用PropertyConfigurator.configureAndWatch(LOG4J_CONFIG_FILE);
读取属性文件时没有出错,但是如果我想用例如debug登录
case DEBUG:
System.out.println("debug");
log.debug(message);
break;
没有任何事情发生。我创建了一个system.out.println来查明是否到达了代码,println被打印出来了。有人可以给我一个提示,为什么记录器不起作用?
这是完整的代码。
import org.apache.log4j.Appender;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;
public class Logging {
private static final String LOG4J_CONFIG_FILE = "/config/log4j.properties";
private static Logging instance;
private Logger log;
public enum level {
DEBUG, INFO, WARN, ERROR, FATAL
};
/**
* Private Constructor for Logging.
*/
private Logging() {
PropertyConfigurator.configureAndWatch(LOG4J_CONFIG_FILE);
}
/**
* Returns an instance of the Logger.
*/
public static synchronized Logging getInstance() {
if (instance == null)
instance = new Logging(Logger.getLogger(Logging.class));
return instance;
}
/**
* Method for doing the logging of actions in the system.
*
* @param l The preciseness level of the logging.
* @param message The message to print.
*/
public void log(Logging.level l, String message) {
switch (l) {
case WARN:
log.warn(message);
break;
case ERROR:
log.error(message);
break;
case DEBUG:
System.out.println("debug");
log.debug(message);
break;
case FATAL:
log.fatal(message);
break;
default:// INFO
log.info(message);
break;
}
}
public Logging(Logger logger) {
this();
setLogger(logger);
}
private void setLogger(Logger log) {
this.log = log;
}
}
Hier是log4j.properties
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C://loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
答案 0 :(得分:0)
根据我的评论,您的DEBUG
消息未显示的原因是配置错误。
要使其正常工作,请将第一行更改为以下内容:
log4j.rootLogger=DEBUG, file
这将使所有级别大于或等于DEBUG
的邮件能够输出到您的文件中。
您可以在以下手册中阅读所有相关信息:http://logging.apache.org/log4j/1.2/manual.html