logback系列之二:輸出日誌到檔案
阿新 • • 發佈:2019-01-08
和logback系列之一:輸出日誌到控制檯類似,改動的地方:
1. logback[-test].xml檔案:
Java程式碼
呼叫測試類的方法,生成granularity.log檔案。
附:
①. prudent:小心的,慎重的。如果設定為true,不同JVM的file appenders能夠安全地將日誌輸出到同一個檔案中。
這是通過鎖定檔案通道實現的:
Java程式碼
②. 當prudent為true時,如果append設定為false,會被強行轉成true。
這是在start方法中處理的:
Java程式碼
1. logback[-test].xml檔案:
Java程式碼
- <appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
- <file>/logs/granularity.log</file>
- <encoder><!-- 必須指定,否則不會往檔案輸出內容 -->
-
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5
- </encoder>
- <append>true</append>
- <prudent>false</prudent>
- </appender>
- <root level="DEBUG">
- <appender-ref ref="fileAppender" />
- </root>
呼叫測試類的方法,生成granularity.log檔案。
附:
①. prudent:小心的,慎重的。如果設定為true,不同JVM的file appenders能夠安全地將日誌輸出到同一個檔案中。
這是通過鎖定檔案通道實現的:
Java程式碼
- protected void writeOut(E event) throws IOException {
- if (prudent) {
- safeWrite(event);
- } else {
- super.writeOut(event);
- }
- }
- private void safeWrite(E event) throws IOException {
-
ResilientFileOutputStream resilientFOS = (ResilientFileOutputStream) getOutputStream();
- FileChannel fileChannel = resilientFOS.getChannel();
- if (fileChannel == null) {
- return;
- }
- FileLock fileLock = null;
- try {
- fileLock = fileChannel.lock(); // 加鎖
- long position = fileChannel.position();
- long size = fileChannel.size();
- if (size != position) {
- fileChannel.position(size);
- }
- super.writeOut(event);
- } finally {
- if (fileLock != null) {
- fileLock.release(); // 釋放鎖
- }
- }
- }
②. 當prudent為true時,如果append設定為false,會被強行轉成true。
這是在start方法中處理的:
Java程式碼
- if (prudent) {
- if (!isAppend()) {
- setAppend(true);
- addWarn("Setting \"Append\" property to true on account of \"Prudent\" mode");
- }
- }