2017-06-02 86 views
0

當記錄一個新的異常時,將創建一個新文件。Serilog.Exceptions滾動文件

場景: 首先創建的文件:
數20170602

每例外創建的文件:
日誌20170602_001
日誌20170602_002
日誌20170602_003

我的代碼(C# - Visual Studio 2015項目):

public class EventLogging 
    { 
     private readonly Logger _logger; 


     public EventLogging(IOptions<LoggingOptions> logOption) 
     { 
      var logAccessor = logOption.Value; 

      _logger = new LoggerConfiguration() 
       .Enrich.WithExceptionDetails() 
       .WriteTo.Sink(new RollingFileSink(logAccessor.Path, 
        new JsonFormatter(renderMessage: true), null, null)).CreateLogger(); 
     } 

     public void LogError(string message, Exception exception) 
     { 
      _logger.Error(exception, message); 
     } 

     public void LogWarning(string message, Exception exception) 
     { 
      _logger.Warning(exception, message); 
     } 
    } 

請參閱該類別,以避免在每一個類編寫如下代碼:

_logger = new LoggerConfiguration() 
       .Enrich.WithExceptionDetails() 
       .WriteTo.Sink(new RollingFileSink(logAccessor.Path, 
        new JsonFormatter(renderMessage: true), null, null)).CreateLogger(); 

有沒有一種方法,以防止每異常,但每個新的日期正在創建的文件嗎?

回答

1

您是否在每次登錄時創建一個新的記錄器?一般用Serilog我的初始化一次單身日誌實例,並在任何地方使用它:

在啓動:

Serilog.Log.Logger = new LoggerConfiguration() 
    .Enrich.WithExceptionDetails() 
    .WriteTo.Sink(new RollingFileSink(logAccessor.Path, 
    new JsonFormatter(renderMessage: true), null, null)).CreateLogger(); 

後:

Serilog.Log.Error(exception, message); 

在你的情況,我覺得如果你只是保持靜態你的_logger的實例,而不是一遍又一遍地重新創建一個新實例,它會解決你的問題。或者如果你只保留相同的RollingFileSink並重新使用它,你可以使用不同的記錄器。

+0

我意識到我每次創建一個新實例後,才意識到這種方法。謝謝 –