LayoutWrappingEncoder 的 LogBack 默认字符集?

LogBack default charset for LayoutWrappingEncoder?

Logback 1.1.3 LayoutWrappingEncoder documentation 没有说明如果用户不设置默认字符集是什么,但源代码说:

By default this property has the value null which corresponds to the system's default charset.

但是我使用的是 PatternLayoutEncoder(带有 RollingFileAppender),它似乎以 UTF-8 格式输出文件(以及我的 Windows 7 的默认字符集专业系统可能不是UTF-8)。

UTF-8 输出实际上是我想要的,但我想确保这不是偶然得到的,因为文档似乎表明了其他内容。那么为什么当我没有明确指定字符集时 Logback 给我 UTF-8 输出?

Logback 字符编码

您可以在 PatternLayoutEncoder 的定义中使用 <charset>,因为这是 LayoutWrappingEncoder 的子 class,它提供了 setCharset 方法。 class 的摘录在文档中表明了这一点,但没有给出示例 xml 配置。对于 LayoutWrappingEncoder,这里已经给出了答案:[Logback-user]: How to use UTF-8.

因此,如果您通过代码进行配置,则可以使用 UTF-8 调用 setCharset 方法。或者,如果您通过 xml 配置,则为:

<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
        <charset>UTF-8</charset>            
        <outputPatternAsHeader>true</outputPatternAsHeader>
        <pattern>[%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>

默认文件编码

Logback 的文档在说明使用默认字符编码方面是正确的。默认字符集通常不是 windows 上的 UTF-8(例如,我的是 windows-1252)。正确的做法是如上所述将 logback 配置为 UTF-8。即使 logback 从某个地方选择 UTF-8,或者 file.encoding 是由您设置的,也不能保证将来会发生这种情况。

顺便提一句,Sun 之前曾说过 file.encoding,如果您在 Oracle VM 上设置它:

The "file.encoding" property is not required by the J2SE platform specification; it's an internal detail of Sun's implementations and should not be examined or modified by user code. It's also intended to be read-only; it's technically impossible to support the setting of this property to arbitrary values on the command line or at any other time during program execution.

Eclipse 和 Maven

如果您是来自 eclipse 的 运行 maven,并且您已经将环境设置为 UTF-8 用于 environment/project 或 运行 配置(对我来说公共选项卡)然后 eclipse 将通过设置 file.encoding 来安排新的 JVM 具有 UTF-8 编码。参见:Eclipse's encoding documentation

系统默认的charset由Java决定,在系统中设置属性file.encoding,但是这个属性也可以在JVM启动时指定( this answer 中有更多内容)。 Eclipse、Netbeans、Maven 等可以使用此系统 属性 将默认字符集设置为 UTF-8,这可能就是为什么即使您没有指定它,输出也是 UTF-8 的原因。

this answer. Logback's source code shows how the character set is used to convert the Strings to bytes to write to file in the convertToBytes method (more on Strings to bytes is explained in this answer).

所示,要删除随机元素,请指定用于记录的字符集

在 Unix 上,file.encoding 的值是使用环境变量确定的(例如,通过 LANG=en_US.UTF-8,如 here, but other environment variables can be involved as well 所述)。
在 Windows 上,默认代码页与命令 chcp 一起显示。代码页编号对应于 this list 中显示的字符集。例如,代码页 65001 对应于 UTF-8。默认语言环境使用命令 systeminfo | findstr Locale.

显示

简而言之:一旦您的软件离开您的开发环境,您就不能采用任何特定的默认字符集。因此,始终指定一个字符集。