简体   繁体   English

如何使用slf4j读取.properties文件?

[英]How do I read .properties file using slf4j?

I am trying to make a simple program which reads the properties file and logs the output to console but I am not able to do that. 我正在尝试制作一个简单的程序,该程序读取属性文件并将输出记录到控制台,但是我无法做到这一点。

This is my class: 这是我的课:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class Slf4jSample {

    public static void main(final String[] args) {
        final Logger logger = LoggerFactory.getLogger(Slf4jSample.class);

        logger.info("Hello World!");
    }

    private Slf4jSample() {
    }
}

And this is my properties file: 这是我的属性文件:

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.logger.Slf4jSample=INFO, A1

When I run this it gives this exception: 当我运行它时,会出现以下异常:

log4j:WARN No appenders could be found for logger (com.slf4j.Slf4jSample).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

The "log4j:WARN No appenders could be found..." message indicates that SLF4J was correctly bound with log4j but log4j could not load your log4j.properties file. “ log4j:WARN找不到附加程序...”消息表明SLF4J已与log4j正确绑定,但log4j无法加载log4j.properties文件。 SLF4J is not the issue here. SLF4J不是这里的问题。 Just place log4j.properties on your classpath. 只需将log4j.properties放在类路径上即可。

Considering that you are using slf4j with log4j as the underlying logging library, and you have both slf4j-log4j.jar and log4j.jar on your classpath, you then need to specify the location of the log4j.properites file. 考虑到您正在将slf4j与log4j作为基础日志记录库一起使用,并且在类路径上同时具有slf4j-log4j.jar和log4j.jar,则需要指定log4j.properites文件的位置。

Ceki mentioned to put log4j.properties on your classpath and it should pick it up automatically. Ceki提到将log4j.properties放在类路径上,它应该自动将其拾取。 If this is not working for you (it should), or you need the log4j.properties to exist outside the classpath, then you can add -Dlog4j.configuration=log4j.properties to your JVM arguments when executing your code. 如果这不适合您(应该这样做),或者您需要log4j.properties存在于类路径之外,则可以在执行代码时将-Dlog4j.configuration=log4j.properties添加到JVM参数中。 The value of this variable can be a full path, or is relative to the current directory where you are executing from. 该变量的值可以是完整路径,也可以是相对于您从中执行当前目录的路径。

For example, when exectuing JUnit tests in my IDE I commonly add this as a JVM argument in my Run Profile to ensure it picks up my properties file that is not inside my Java Project (ie not on classpath) 例如,当在我的IDE中执行JUnit测试时,我通常将此添加为我的运行配置文件中的JVM参数,以确保它获取不在Java项目中(即不在类路径中)的属性文件。

-Dlog4j.configuration=file:/C:/java/workspace/logs/log4j.properties

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM