![](/img/trans.png)
[英]How to log error and info messages separately into syslog with log4j?
[英]How to configure log4j to log only info messages and higher?
我沒有使用config或xml文件來配置log4j,因為不需要深入配置它。 我只需要將消息打印到控制台。 所以我這樣做:
BasicConfigurator.configure();
並且只打印信息和更高的消息我這樣做:
Logger LOG = Logger.getLogger(MyClass.class)
LOG.setLevel(Level.INFO);
但是我在控制台中也看到了調試消息。 但我只需要打印信息和實際錯誤消息。
這該怎么做?
UPD:我創建了一個包含的配置文件,如本教程中所述: 手動以下內容:
log4j.rootLogger=INFO, stdout
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L %m%n
log4j.logger.com.messagedna.facade=INFO
log4j.logger.com.messagedna.receiver=INFO
log4j.logger.com.messagedna.util=INFO
log4j.logger.com.messagedna.parser=INFO
我把它放到了com.messagedna
在我需要記錄器的每個班級中,我寫了以下內容:
Properties props = new Properties();
try {
props.load(new FileInputStream("/log4j.properties"));
} catch (Exception e){
LOG.error(e);
}
PropertyConfigurator.configure(props);
但是當我運行我的應用程序時,我得到以下內容:
log4j:WARN No appenders could be found for logger (com.messagedna.server.util.Config).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
您只是為使用MyClass.class
的記錄器記錄的消息設置了級別,但是其他記錄器上的調試級別的任何消息仍將被打印。
您真正需要做的是在控制台日志處理程序(負責將所有日志消息打印到控制台)上設置日志級別。 但是,在使用BasicConfigurator
時執行此操作將非常棘手,最好轉到在屬性文件中指定日志配置(這樣更靈活)。
我建議通過log4j日志記錄配置教程 - 這將幫助您准確地組合您想要的配置,並且應該證明您的時間是值得的投資。 但是,如果您希望快速完成此操作,請嘗試將以下內容添加到文件log4j.properties
( 從此處獲取示例 ):
# Root logger option
log4j.rootLogger=INFO, stdout
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
然后更改代碼以執行以下操作:
Properties props = new Properties();
props.load(new FileInputStream("/my/path/to/log4j.properties"));
PropertyConfigurator.configure(props);
配置log4j.properties:
log4j.rootLogger=DEBUG, A1
log4j.logger.com.MYPACKAGE=INFO, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
因為你只想用代碼來做它
繼承人另類。
在開始時執行此操作,靜態代碼初始化將起作用
logger = Logger.getLogger(Class.getName(), factory);
logger.setLevel(Level.INFO);
話雖如此,沒有理由不使用log4j.xml。 它非常容易使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.