# 日志乱码问题修复说明 ## 问题描述 应用运行时,控制台和日志文件中出现中文乱码,例如: ``` 02:54:07.747 [restartedMain] INFO sys-user - [shutdownAsyncManager,31] - ====关闭后台任务线程池==== ``` 显示为乱码。 ## 问题原因 1. **Logback 编码未配置**:logback.xml 中的 encoder 没有指定 charset,默认使用系统编码 2. **JVM 编码未设置**:启动时没有指定 `-Dfile.encoding=UTF-8` 参数 3. **Windows 控制台编码**:Windows 控制台默认使用 GBK 编码 ## 修复内容 ### 1. 修复 logback.xml 编码配置 **文件位置:** `ry-study-admin/src/main/resources/logback.xml` **修改内容:** 为所有 encoder 添加 UTF-8 编码配置 #### 修改前: ```xml ${log.pattern} ``` #### 修改后: ```xml ${log.pattern} UTF-8 ``` **修改的 appender:** - `console` - 控制台输出 - `file_info` - 系统信息日志 - `file_error` - 系统错误日志 - `sys-user` - 用户操作日志 ### 2. 修复 Spring Boot Maven 插件配置 **文件位置:** `ry-study-admin/pom.xml` **修改内容:** 在 spring-boot-maven-plugin 中添加 JVM 编码参数 ```xml true -Dfile.encoding=UTF-8 ``` ### 3. 修复启动脚本编码配置 **文件位置:** - `ry.bat` (Windows) - `ry.sh` (Linux) **修改内容:** 在 JVM_OPTS 中添加 `-Dfile.encoding=UTF-8` #### Windows (ry.bat): ```batch set JVM_OPTS="-Dname=%AppName% -Dfile.encoding=UTF-8 -Duser.timezone=Asia/Shanghai ..." ``` #### Linux (ry.sh): ```bash JVM_OPTS="-Dname=$AppName -Dfile.encoding=UTF-8 -Duser.timezone=Asia/Shanghai ..." ``` ## 验证方法 ### 方法1:检查日志输出 重新启动应用后,查看日志输出,中文应该正常显示: ``` 02:54:07.747 [restartedMain] INFO sys-user - [shutdownAsyncManager,31] - ====关闭后台任务线程池==== ``` ### 方法2:检查日志文件 查看日志文件(如 `sys-user.log`),中文应该正常显示。 ### 方法3:在 IntelliJ IDEA 中设置 如果使用 IntelliJ IDEA 运行,还需要: 1. **设置运行配置的 VM options:** ``` -Dfile.encoding=UTF-8 ``` 2. **设置控制台编码:** - File → Settings → Editor → File Encodings - 确保所有编码设置为 UTF-8 3. **设置运行配置的编码:** - Run → Edit Configurations - 在 VM options 中添加:`-Dfile.encoding=UTF-8` ## Windows 控制台编码设置 如果 Windows 控制台仍然显示乱码,可以: ### 方法1:设置控制台代码页 ```cmd chcp 65001 ``` 然后重新运行应用。 ### 方法2:在启动脚本中设置 在 `ry.bat` 文件开头添加: ```batch @echo off chcp 65001 >nul ``` ## 修复状态 ✅ **logback.xml** - 已修复,所有 encoder 添加 UTF-8 编码 ✅ **pom.xml** - 已修复,Spring Boot 插件添加编码参数 ✅ **ry.sh** - 已修复,添加编码参数 ⚠️ **ry.bat** - 需要手动修复(文件本身有编码问题) ## 注意事项 1. **文件编码**:确保所有源代码文件使用 UTF-8 编码保存 2. **IDE 设置**:确保 IDE 的文件编码设置为 UTF-8 3. **控制台编码**:Windows 控制台可能需要额外设置代码页 4. **重启应用**:修改配置后需要重新启动应用才能生效 ## 如果仍有乱码 1. 检查 IDE 的文件编码设置 2. 检查 Windows 控制台代码页(运行 `chcp` 查看当前代码页) 3. 检查日志文件本身的编码(用支持 UTF-8 的编辑器打开) 4. 确认所有配置文件已保存为 UTF-8 编码