如何使用 SLF4J 和 SimpleLogger (Windows) 写入子目录中的日志文件

How to write to a log file in a subdirectory using SLF4J and SimpleLogger (Windows)

我在我的 Java 应用程序中使用 SLF4J SimpleLogger,我想将其配置为输出到当前工作目录中名为 log 的子目录中的文件。

E.g. <cwd>/log/log-file.log

我配置如下:

System.setProperty(org.slf4j.impl.SimpleLogger.LOG_FILE_KEY, "log/log-file.log");

// set other properties

log = LoggerFactory.getLogger(Logger.class);

在 OS X 上,这按预期工作 - 即在目录 <cwd>/log.

中创建了一个名为 log-file.log 的文件

但是,在 Windows 上调用 getLogger 时会抛出异常。

Could not open [log/log-file.log]. Defaulting to System.err
Reported exception:
java.io.FileNotFoundException: log\log-file.log (The system cannot find the path specified)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
    at org.slf4j.impl.SimpleLogger.computeTargetStream(SimpleLogger.java:219)
    at org.slf4j.impl.SimpleLogger.init(SimpleLogger.java:201)
    at org.slf4j.impl.SimpleLogger.<init>(SimpleLogger.java:262)
    at org.slf4j.impl.SimpleLoggerFactory.getLogger(SimpleLoggerFactory.java:55)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:281)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:301)

如果我在没有指定子目录的情况下设置 属性,它就可以正常工作。

System.setProperty(org.slf4j.impl.SimpleLogger.LOG_FILE_KEY, "log-file.log");

Java文档说 logfile 属性 是 "The output target which can be the path to a file"。

如何在 Windows 上实现与在 OS X 上相同的行为 - 即,将日志文件写入当前工作目录的子目录?

我明白了。该问题与 SimpleLogger 无关,但与 FileOutputStream 相关。在 Windows 如果目录不存在则需要先创建它。这在 OS X 上没有必要。