Maven 中指定编码是编译时使用编码
Java 运行时编码应该通过 java -Dfile.encoding=UTF-8 -jar xxx.jar 指定,如果 Java 启动时没设置运行。截至目前 1.2.3 logback 可能会直接取系统默认编码作为 encoder 编码,因此 logback 配置非常有必要给 encoder 设置 UTF-8 编码。
对于 log4j2,不会有这个问题,因为 layout 默认编码就是 utf-8, 见 https://logging.apache.org/log4j/2.x/manual/layouts.html
The root class for layouts that use a Charset is org.apache.logging.log4j.core.layout.AbstractStringLayout where the default is UTF-8. Each layout that extends AbstractStringLayout can provide its own default. See each layout below.
So if you configure via code you can call the setCharset
method with UTF-8. Or if you are configuring via xml this is:
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<charset class="java.nio.charset.Charset">UTF-8</charset>
<outputPatternAsHeader>true</outputPatternAsHeader>
<pattern>${PROJECT_PATTERN}</pattern>
</encoder>
https://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding
Charset.defaultCharset() will reflect changes to the file.encoding property, but most of the code in the core Java libraries that need to determine the default character encoding do not use this mechanism. When you are encoding or decoding, you can query the file.encoding property or Charset.defaultCharset() to find the current default encoding, and use the appropriate method or constructor overload to specify it.