1. 程式人生 > >logback系列之二:輸出日誌到檔案

logback系列之二:輸出日誌到檔案

logback系列之一:輸出日誌到控制檯類似,改動的地方: 

1. logback[-test].xml檔案:
Java程式碼  收藏程式碼
  1. <appender name="fileAppender" class="ch.qos.logback.core.FileAppender">  
  2.     <file>/logs/granularity.log</file>  
  3.     <encoder><!-- 必須指定,否則不會往檔案輸出內容 -->  
  4.         <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5
    } - %msg%n</pattern>  
  5.     </encoder>  
  6.     <append>true</append>  
  7.     <prudent>false</prudent>  
  8. </appender>  
  9. <root level="DEBUG">  
  10.     <appender-ref ref="fileAppender" />  
  11. </root>  


呼叫測試類的方法,生成granularity.log檔案。 

附: 
①. prudent:小心的,慎重的。如果設定為true,不同JVM的file appenders能夠安全地將日誌輸出到同一個檔案中。 

    這是通過鎖定檔案通道實現的: 

Java程式碼  收藏程式碼
  1. protected void writeOut(E event) throws IOException {  
  2.   if (prudent) {  
  3.     safeWrite(event);  
  4.   } else {  
  5.     super.writeOut(event);  
  6.   }  
  7. }  
  8. private void safeWrite(E event) throws IOException {  
  9.   ResilientFileOutputStream resilientFOS = (ResilientFileOutputStream) getOutputStream();  
  10.   FileChannel fileChannel = resilientFOS.getChannel();  
  11.   if (fileChannel == null) {  
  12.     return;  
  13.   }  
  14.   FileLock fileLock = null;  
  15.   try {  
  16.     fileLock = fileChannel.lock(); // 加鎖  
  17.     long position = fileChannel.position();  
  18.     long size = fileChannel.size();  
  19.     if (size != position) {  
  20.       fileChannel.position(size);  
  21.     }  
  22.     super.writeOut(event);  
  23.   } finally {  
  24.     if (fileLock != null) {  
  25.       fileLock.release(); // 釋放鎖  
  26.     }  
  27.   }  
  28. }  


②. 當prudent為true時,如果append設定為false,會被強行轉成true。 
    這是在start方法中處理的: 

Java程式碼  收藏程式碼
  1. if (prudent) {  
  2.   if (!isAppend()) {  
  3.     setAppend(true);  
  4.     addWarn("Setting \"Append\" property to true on account of \"Prudent\" mode");  
  5.   }  
  6. }