简体   繁体   English

Serilog.Exceptions滚动文件

[英]Serilog.Exceptions Rolling Files

When a new exception is logged, a new file is created. 记录新异常时,将创建一个新文件。

Scenario: First file created: 场景:创建的第一个文件:
log-20170602 日志-20170602

Files created per exceptions: 根据例外创建的文件:
log-20170602_001 日志-20170602_001
log-20170602_002 日志-20170602_002
log-20170602_003 日志-20170602_003

My code (C# - Visual Studio 2015 Project): 我的代码(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);
        }
    }

Refer that class to avoid writing the following code in every class: 引用该类以避免在每个类中编写以下代码:

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

Is there a way to prevent the files being created per exception but per new date? 有没有一种方法可以防止按例外但按新日期创建文件?

Are you creating a new logger everytime you log something? 您是否在每次记录内容时都创建一个新的记录器? Generally with Serilog I initialize the singleton Log instance once and use it everywhere: 通常,我使用Serilog初始化一次Singleton Log实例,并在各处使用它:

At Startup: 在启动时:

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

later: 后来:

Serilog.Log.Error(exception, message);

In your case, I think if you just keep a static instance of your _logger instead of recreating a new one over and over, it'll solve your problem. 就您而言,我认为如果只保留_logger的静态实例,而不是_logger创建一个新实例,它将解决您的问题。 Or possibly if you just keep the same RollingFileSink and reuse it, you can get away with different loggers. 或者,如果仅保留相同的RollingFileSink用它,则可以使用其他记录器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM