Can I log to separate files using Serilog?

后端 未结 3 902
我寻月下人不归
我寻月下人不归 2021-01-05 07:25

My ASP.NET Core 2.1 app logs to a Serilog file sink, all the \"usual stuff\" - i.e. app related stuff such as debug, monitoring, performance, etc.

However we also ne

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-05 08:18

    The simplest way I've managed to do this was to implement a new unique interface that I could pass to the DI system to be consumed by the controllers.
    Note: In the example I used the Serilog.Sinks.RollingFile NuGet package. Use any other sinks as you see fit. I use asp.net Core 2.1.

    New Interface

    using Serilog;
    using Serilog.Core;
    
    public interface ICustomLogger
    {
        ILogger Log { get; }
    }
    
    public class CustomLogger : ICustomLogger
    {
        private readonly Logger _logger;
    
        public ILogger Log { get { return _logger; } }
    
        public CustomLogger( Logger logger )
        {
            _logger = logger;
        }
    }
    

    Implementation in Startup.cs

    using Serilog;
    ...
    public void ConfigureServices( IServiceCollection services )
    {
        ...
    
        ICustomLogger customLogger = new CustomLogger( new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.RollingFile( @"Logs\CustomLog.{Date}.log", retainedFileCountLimit: 7 )
            .CreateLogger() );
        services.AddSingleton( customLogger );
    
        ...
    }
    

    Usage in Controller

    public class MyTestController : Controller
    {
        private readonly ICustomLogger _customLogger;
    
        public MyTestController( ICustomLogger customLogger )
        {
            _customLogger = customLogger;
        }
    
        public IActionResult Index()
        {
            ...
            _customLogger.Log.Debug( "Serving Index" );
            ...
        }
    }
    

提交回复
热议问题