2015-01-14 72 views
1

我在ASP.NET MVC 4應用程序中使用log4net,並試圖從log4Net下載生成的日誌文件。如何從log4Net下載生成的日誌文件

我心目中下載日誌文件以FileResult,如:

[Authorize(Roles = "Admin")] 
public FileResult DownloadUserInterfaceLog() 
{ 
    // Get the path of the log file 
    string path = (LogManager.GetCurrentLoggers()[0].Logger.Repository.GetAppenders()[0] as FileAppender).File; 
    // Get the file 
    byte[] fileBytes = System.IO.File.ReadAllBytes(path); 
    string fileName = "Log.txt"; 
    // Return the expected file 
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); 
} 

我的問題是,當我打電話System.IO.File.ReadAllBytes(path);我得到一個異常,導致日誌文件已經由另一個進程使用。

我已經把<lockingModel value="log4net.Appender.FileAppender+MinimalLock" /> (which should release the file after any modification) in my Web.Config沒有成功。

Web.Config中開始log4net的配置:

<log4net> 
    <appender name="Appender-root" type="log4net.Appender.RollingFileAppender"> 
     <lockingModel value="log4net.Appender.FileAppender+MinimalLock" /> 
     <file value="Path..." /> 
     <appendToFile value="true" /> 

回答

2

Here是關於類似問題的文章。

File.ReadAllBytes()函數被寫入,使得它使用像 呼叫以下實例化一個FileStream:

FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read) 

注意,文件共享被指定爲已讀。這意味着如果您有另一段代碼同時寫入同一文件,即使其他代碼通過將共享模式指定爲「ReadWrite」創建了 FileStream,您的 也會收到錯誤:

FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite) 

解決辦法是寫自己的自定義ReadAllBytes:

public static byte[] ReadAllBytes(String path) 
{ 
    byte[] bytes; 
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
    { 
     int index = 0; 
     long fileLength = fs.Length; 
     if (fileLength > Int32.MaxValue) 
      throw new IOException(「File too long」); 
     int count = (int)fileLength; 
     bytes = new byte[count]; 
     while (count > 0) 
     { 
      int n = fs.Read(bytes, index, count); 
      if (n == 0) 
       throw new InvalidOperationException(「End of file reached before expected」); 
      index += n; 
      count -= n; 
     } 
    } 
return bytes; 
} 
2

您需要訪問該文件前,關閉追加程序:

((FileAppender)LogManager.GetCurrentLoggers()[0].Logger.Repository.GetAppenders()[0]).Close() 
+0

似乎工作!非常感謝 !! 你知道嗎,我該如何重建log4net tracer? (在我關閉Appender之後) –