如何在 logback 中以可移植的方式将日志文件放在用户主目录中?

How to put log file in user home directory in portable way in logback?

我想将日志文件放入用户主目录。

如何以可移植的方式做到这一点,即在 Windows、Linux 和 Mac 上工作?

根据 Logback documentation,您应该使用 ${user.home},这是 JVM 中直接来自 OS 的环境变量(因此它是可移植的):

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>${user.home}/logback.log</file>
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
    </encoder>
</appender>

日志设置实际上是系统的配置组件。最好的办法是分离(并加载)每个系统的配置。一个好的方法是使用 Apache Commons Configuration 之类的东西,这允许遍历一组属性,这些属性将指示在哪里可以找到一次性的 logback 配置。

我们使用类似"priority"的方案来标识logback配置文件名。使用 Apache Commons 配置,我们指定如下方案:

<configuration config-name="master-config">
<!--  start here, properties encountered in the first file would be ignored in the last file -->
<properties fileName="/opt/config/log.properties" optional="true"/> 
<properties fileName="${sys:user.home}/config/product/log.properties" optional="true"/>
<properties fileName="com/company/product/config/log.properties"/>    

在我的本地 windows 开发箱中(${sys:user.home}/config/product/log.properties)文件看起来像

logbackConfigLocation=C:/Users/dan/config/product/logback.xml 

然后每个 system/user 可以 configure/setup 根据需要进行记录。从 servlet 上下文中,您可以加载和初始化 logback。

补充一下,路径也可以是您定义为系统的任何内容属性。例如,

java -Dmylog.root=somelocation ...

并且 logback 配置可以支持 属性。

<appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${mylog.root}/logback.log</file>