0

I am trying Serilog for my logging requirements with asp.net core web application. I am new to both of these frameworks. I really want to understand how to configure the logger so that I can log *separate data to both file and database sinks simultaneously (say from within the same controller class). I tried researching on the internet, since I read Serilog has a good documentation, but I failed to find the exact configuration I need for my requirement.

With someone's suggestion on another stackoverflow question related to multiple sinks here.

I tried to do the following:

 public static void Main(string[] args)
 {
        var logger1 = new LoggerConfiguration()
            .WriteTo.File("Logs\\system_.log", rollingInterval: RollingInterval.Day)
                .CreateLogger();

        var logger2 = new LoggerConfiguration()
           .WriteTo.MSSqlServer(connectionString,
            sinkOptions: new MSSqlServerSinkOptions { TableName = "logs" })
               .CreateLogger();

        logger1.Information("hello to file");
        logger2.Information("hello to database"); 

        CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .UseSerilog();

This partially works, I was able to see distinct logs in log file and database(Sql server) respectively, but now I do not know how to use these two configurations from inside a controller class.

As the following code from my controller class does not log anything in any of the sinks

 public class UserController : ControllerBase
{        
    private ILogger<UserController> _logger;

    public UserController(ILogger<UserController> logger)
    {           
        _logger = logger;
        _logger.LogInformation("Writing to log file with INFORMATION severity level.");            
        _logger.LogWarning("Writing to log file with WARNING severity level.");
        _logger.LogError("Writing to log file with ERROR severity level.");
        
    }

Any suggestions would be really helpful, thanks in advance.

  • Dependency injection, Ilogger and Serilog, in startup ConfigureServices: services.AddLogging(loggingBuilder => { loggingBuilder.AddSerilog(); }); – SilentTremor Jul 07 '21 at 12:57
  • Okay I forgot to add that piece of code, but I have already added .UseSerilog() to CreateHostBuilder(), I do not know if this is what you mean. – user2218529 Jul 07 '21 at 13:12
  • it's the same thing, I don't get you what are the needs then, what is not working – SilentTremor Jul 07 '21 at 15:29

0 Answers0