C#C
C#3y ago
M B V R K

❔ Why Serilog doesn't loggin into a MSSQL Database

Hi dear friends,
I'm working on a solution that contains 5 projects, ( Core, IdentityCore, EFCore, CQRSCore and WEB), the WEB project is an ASP.NET Core 7 API project.

Recently I tried to integrate the Serilog logger in the project.
I created the following entity that represents a Log :

public class Log
{
    public int Id { get; set; }
    public DateTime Timestamp { get; set; }
    public string Level { get; set; }
    public string Message { get; set; }
    public string Exception { get; set; }
    public string Properties { get; set; }
    public string? UserId { get; set; }

    public AppUser User { get; set; }
}


AppUser is a class that Inherits from IdentityUser.
in the AppDbContext I add the Log as a DbSet<Log> Logs.
And I configured in the Serilog in the Program.cs of the web project like this :
Serilog.Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Override("Microsoft.AspNetCore", Serilog.Events.LogEventLevel.Warning)
        .Enrich.FromLogContext()
        .WriteTo.MSSqlServer(configuration.GetConnectionString("DefaultConnection"), sinkOptions: new MSSqlServerSinkOptions()
        {
            TableName = "Logs"
        }).CreateLogger();

And to log from Controllers I use like the following example :
    [Authorize]
    [HttpGet]
    public async Task<ActionResult<IEnumerable<BranchGetModel>>> GetBranches()
    {
        var result = await _mediator.Send(new GetBranchesQuery());
        var mappedResult = _mapper.Map<IEnumerable<BranchGetModel>>(result);

        Log.ForContext("UserId", User.Identity.Name).Information($"User has requested all branches");

        return Ok(mappedResult);
    }


With all these and no logs stored in the DB, please from your experience how do I can solve this issue ?
Was this page helpful?