简体   繁体   English

SLF4J:SimpleLogger 不记录跟踪和调试,也不记录异常

[英]SLF4J: SimpleLogger is not logging trace and debug and also not logging exceptions

I am trying to add a logger to one of my programs, mainly to replace the System.out.println() , and it seems to give me some problems.我正在尝试向我的一个程序添加一个记录器,主要是为了替换System.out.println() ,它似乎给我带来了一些问题。 This is my first time using a logger, so I am a noob at it.这是我第一次使用记录器,所以我是个菜鸟。

I had a look at a multitude of links over the past days but still haven't managed to make my logger catch an exception;过去几天我查看了大量链接,但仍然没有设法让我的记录器捕获异常; here are some of the links I looked at (some of them are 5 years old and might need updates):以下是我查看的一些链接(其中一些已有 5 年历史,可能需要更新):

I am using:我在用:

  • slf4j-api-1.7.22.jar slf4j-api-1.7.22.jar
  • slf4j-simple-1.7.22.jar slf4j-simple-1.7.22.jar
  • jdk1.8.0_71 jdk1.8.0_71
  • IntelliJ 2016.3.2 IntelliJ 2016.3.2

The simpleLogger.properties is placed directly in the resources package, this file is loaded before the logger is created, the file is loaded correctly as I can modify the date-time as I need it to be (and other settings work as well). simpleLogger.properties直接放在resources包中,这个文件在创建记录器之前加载,文件被正确加载,因为我可以根据需要修改日期时间(其他设置也可以)。

Part of the Main class: Main类的一部分:

...
private Logger LOG; //field
...

public static void main(String[] args) {
    launch(args);
}

...

@Override
public void start(Stage primaryStage) {
    /*Create logger*/
    createLogger();
    LOG.info("Stage start.");
    ...
}

...

private void createLogger() {
    try {
        Properties properties = new Properties();
        properties.load(LOGGER_PROPERTIES); //path to prop file
    } catch (IOException e) {
        e.printStackTrace();
    }

    LOG = LoggerFactory.getLogger(Main.class);
    LOG.info("Logger initialised.");

    LOG.trace("test trace"); //not working
    LOG.debug("test debug"); //not working
    LOG.info("test info");
    LOG.warn("test warning");
    LOG.error("test error");
}

The simpleLogger.properties file: simpleLogger.properties文件:

org.slf4j.simpleLogger.logFile=System.out
# org.slf4j.simpleLogger.defaultLogLevel=
# org.slf4j.simpleLogger.log.a.b.c=
org.slf4j.simpleLogger.showDateTime=true
org.slf4j.simpleLogger.dateTimeFormat=HH:mm:ss:SSS
org.slf4j.simpleLogger.showThreadName=false
org.slf4j.simpleLogger.showLogName=false
org.slf4j.simpleLogger.showShortLogName=true
org.slf4j.simpleLogger.levelInBrackets=true
# org.slf4j.simpleLogger.warnLevelString=

# THE FORMAT TRIED
#org.slf4j.simpleLogger.SimpleFormatter.format = [%1$tc] %4$s: %2$s - %5$s %6$s%n
#java.util.logging.SimpleFormatter.format = [%1$tc] %4$s: %2$s - %5$s %6$s%n
#java.util.logging.SimpleFormatter.format="%1$tc %2$s%n%4$s: %5$s%6$s%n"
#org.slf4j.simpleLogger.format=[%1$tc] %4$s: %2$s - %5$s %6$s%n %7$s
#org.slf4j.helpers.MessageFormatter.format = [%1$tc] %4$s: %2$s - %5$s %6$s%n %7$s
#java.util.logging.SimpleFormatter.format="%1$tc %2$s%n%4$s: %5$s%6$s%n"

Part of the class where I am attempting to create an exception:我试图创建异常的类的一部分:

LOG.info("Creating window - More info: loading.. .fxml");
try {
    BP_INFO = FXMLLoader.load(getClass().getResource("/fxml/ImageInf_.fxml")); //HERE change back to ImageInfo.fxml
    LOG.info("Creating window - More info: loaded .fxml successfully.");
} catch (IOException e) {
    //  HERE not showing anything below
    System.out.println("CATCH - From Sys out");
    LOG.error("CATCH - EXCEPTION", (Throwable) e);
    LOG.error("Creating window - More info: Exception");
    LOG.error("Creating window - More info: Exception", e);        
    LOG.error("Creating window - More info: Exception {}", e);
    LOG.error("Creating window - More info: Exception {} {} {}", Level.INFO, e.getMessage(), e);
    //  e.printStackTrace();
}

Console output:控制台输出:

12:17:08:995 [INFO] Main - Logger initialised.
12:17:08:996 [INFO] Main - test info
12:17:08:997 [WARN] Main - test warning
12:17:08:997 [ERROR] Main - test error
12:17:08:997 [INFO] Main - Stage start.
...
12:17:27:140 [INFO] View - Creating window - More info: loading.. .fxml
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
...

Problem 1:问题1:

As you can see trace and debug are not working.如您所见, tracedebug不起作用。 I have tried all the properties in the prop.我已经尝试了道具中的所有属性。 file and some more as well but so far did not manage to catch any exception or apply a specific format.文件以及其他一些文件,但到目前为止还没有设法捕获任何异常或应用特定格式。

Problem 2:问题2:

As you can see, the exception is also not logged at all.如您所见,该异常也根本没有被记录。

Additional info: I have reset IntelliJ settings, I have been cleaning the win %temp% folder various times, I have been cleaning caches and restarted Intellij various times;附加信息:我重置了 IntelliJ 设置,我多次清理 win %temp% 文件夹,我多次清理缓存并重新启动 Intellij; all this in an attempt if the prop.所有这一切都在尝试如果道具。 file was not read correctly or kept somewhere in a cache.文件未正确读取或保存在缓存中的某处。

Any help is much appreciated.任何帮助深表感谢。 Please respond in a simplistic way.请用简单的方式回答。

We may use Slf4j within a JavaFX project by using only these dependencies:我们可以通过仅使用以下依赖项在 JavaFX 项目中使用 Slf4j:

  • slf4j-api-1.7.22.jar slf4j-api-1.7.22.jar
  • slf4j-simple-1.7.22.jar slf4j-simple-1.7.22.jar

Here's an example Application class:这是一个示例Application类:

...

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

public class Todo extends Application {

    private static final Logger log = LoggerFactory.getLogger(Todo.class);

    ...

    public static void main(String[] args) {

        log.info("launching...");
        log.warn("launching...");
        log.error("launching...");
        log.debug("launching...");
        log.trace("launching...");

        launch(args);
    }
}

Slf4j simple already has default settings that may be fine for various scenarios. Slf4j simple 已经有了适用于各种场景的默认设置。 That not being the case, the logger may be configured by adding simplelogger.properties to the classpath, which will be automatically picked up by Slf4j on application startup.事实并非如此,可以通过将simplelogger.properties添加到类路径来配置记录器,Slf4j 将在应用程序启动时自动获取它。 The javadoc for the SimpleLogger class nicely enlists all the properties that may be configured. SimpleLogger类的javadoc很好地列出了所有可以配置的属性。

The contents of a simplelogger.properties file that modifies the log level only:仅修改日志级别的simplelogger.properties文件的内容:

org.slf4j.simpleLogger.defaultLogLevel=trace

And here is the output when running with the log level set to trace :这是在日志级别设置为trace情况下运行时的输出:

[main] INFO todo.Todo - launching... 
[main] WARN todo.Todo - launching... 
[main] ERROR todo.Todo - launching... 
[main] DEBUG todo.Todo - launching... 
[main] TRACE todo.Todo - launching...

Problem #1 (trace and debug level is not logged)问题 #1 (未记录跟踪和调试级别)

From the doc ofSimpleLogger :来自SimpleLogger的文档:

org.slf4j.simpleLogger.defaultLogLevel - Default log level for all instances of SimpleLogger. org.slf4j.simpleLogger.defaultLogLevel - SimpleLogger 的所有实例的默认日志级别。 Must be one of ("trace", "debug", "info", "warn", "error" or "off").必须是(“跟踪”、“调试”、“信息”、“警告”、“错误”或“关闭”)之一。 If not specified, defaults to "info".如果未指定,则默认为“信息”。

Because the defult level is info, and trace and debug levels are "under" info, they will be filtered out by the logger and will not reach the appender.因为默认级别是信息,而跟踪和调试级别是“低于”信息,它们将被记录器过滤掉并且不会到达附加程序。

So if you add the following line in the properties file:因此,如果您在属性文件中添加以下行:

org.slf4j.simpleLogger.defaultLogLevel = trace

you should see also messages with trace and debug level.您还应该看到带有跟踪和调试级别的消息。

Problem #2 (the error trace is not logged properly)问题 #2 (错误跟踪未正确记录)

You are catching IOException s, but an InvocationTargetException is actually thrown (which one is not catched), therefore the execution will never enter your catch block.您正在捕获IOException s,但实际上抛出了InvocationTargetException (未捕获到哪个),因此执行将永远不会进入您的 catch 块。 What you see on the console is an unhandled runtime exception printed.您在控制台上看到的是打印的未处理的运行时异常。

As described here , there could be per user configuration of Maven logging for one installation.如所描述的 在这里,可以存在每Maven的日志记录的用户配置一个安装。 I copied default simplelogger.properties to $M2_HOME/conf/logging and added:我将默认的 simplelogger.properties 复制到 $M2_HOME/conf/logging 并添加:

org.slf4j.simpleLogger.log.com.example=trace

and it logs fine.它记录良好。 This is not maybe the best solution, but the one I've found fitting my needs.这可能不是最好的解决方案,但我发现它适合我的需求。 You can log DEBUG but not TRACE as I remember I've read somewhere.您可以记录 DEBUG 但不能记录 TRACE,因为我记得我在某处读过。

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

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