Serilog only writes to database if table didn't previously exist

53 views Asked by At

I'm using .net 8 minimal API and I've added Serilog to my project:

<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Sinks.MySQL" Version="5.0.0" />

I'm writing to a MySQL database and if the table doen't exist, I have Serilog create it. Heres appsettings.json:

 "WriteTo": [
 {
   "Name": "MySQL",
   "Args": {
     "connectionString": "server=myserver;port=3306;Database=mydatabase;uid=username;pwd=password;",
     "tableName": "Logs",
     "autoCreateSqlTable": true,
     "batchPostingLimit": 100,
     "period": "0.00:00:10",

When testing, the table didn't exist. I ran my application and the table was created and I saw my logs (21 records).

I ran the application again and tried to write some new logs I added, and nothing was written. The same number of records (21) that were in the table previously are the only ones that are still there. No errors or anything.

I delete the table, run my application again and all logs are written (including the old and new ones). Here is how I initialize Serilog in Program.cs:

var builder = WebApplication.CreateBuilder(args);
  IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

 builder.Host.UseSerilog((context, config) =>
{
   config
    .ReadFrom.Configuration(configuration)
    .Enrich.FromLogContext();
});

 builder.Services.AddEndpointsApiExplorer();

Why do my logs only get written if the table doesn't exist and how it I configure Serilog to write to my database everytime regardless if the table existed or not?

Thanks

EDIT: I added the following to appsettings.json:

 "autoCreateSqlDatabase": false,
 "autoCreateSqlTable": false,

This is how I log (simple):

 logger.Information("This should be in the database");

Still, no new records are written to the database.

1

There are 1 answers

4
Power Mouse On BEST ANSWER

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/applog-.txt",
          "rollingInterval": "Day"
        }
      },
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server=(local);Database=MishkaDB;TrustServerCertificate=true;Trusted_Connection=True;MultipleActiveResultSets=true",
          "tableName": "Log",
          "schemaName": "dbo",
          "autoCreateSqlTable": true
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName" ],
    "Properties": {
      "ApplicationName": "Your ASP.NET Core App"
    }
  },
  "ConnectionStrings": {
    "MyConnectionString": "Data Source=(local);Integrated Security=True;Database=MishkaDB;TrustServerCertificate=true;Trusted_Connection=True;MultipleActiveResultSets=True;Connection Timeout=0;"
  }
}

Program.cs

using Serilog;
using Serilog.Context;
using Serilog.Sinks.MSSqlServer;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddLogging();
builder.Host.UseSerilog((ctx, lc) => lc
                                    //.WriteTo.Console()
                                    //.WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day)
                                    .WriteTo.MSSqlServer(ctx.Configuration["ConnectionStrings:MyConnectionString"], sinkOptions: new MSSqlServerSinkOptions { TableName = "Logs" } )
                                    //.Enrich.FromLogContext()
                                    .ReadFrom.Configuration(ctx.Configuration)
                                    );

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        c.RoutePrefix = string.Empty;
    });
}

app.UseSerilogRequestLogging();
app.UseAuthorization();
app.MapControllers();

app.Use(async (context, next) =>
{
    var correlationId = context.Request.Headers["X-Correlation-ID"].FirstOrDefault() ?? Guid.NewGuid().ToString();
    context.Response.Headers["X-Correlation-ID"] = correlationId;
    using (LogContext.PushProperty("CorrelationID", correlationId))
    {
        await next();
    }
});

app.Run();

WeatherForecastController controller

using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{


    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            _logger.LogInformation("*** TEST ***");


            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

enter image description here