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
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.
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;
}
}
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 );
...
}
public class MyTestController : Controller
{
private readonly ICustomLogger _customLogger;
public MyTestController( ICustomLogger customLogger )
{
_customLogger = customLogger;
}
public IActionResult Index()
{
...
_customLogger.Log.Debug( "Serving Index" );
...
}
}