1

I am working on an asp.net core 6.0 project, I have implemented logging using Serilog. I have configured it to insert records in SQL Server table, but it logs only errors and fatal errors. I need to log information as well, please suggest if I need to change my code to log all types of logs supported by Serilog.

C# Code: -

public static void Main(string[] args)
    {
        try
        {                
            ConfigureLogging();
            var host = CreateHostBuilder(args).Build();
            Log.Information("App starting");
            host.Run();
        }
        catch (Exception exception)
        {
            Log.Fatal(exception, "Error starting - Main method");
        }
    }
   
   private static void ConfigureLogging()private static void ConfigureLogging()
    {
        try
        {               
            var configuration = new ConfigurationBuilder()
               .AddJsonFile("appsettings.json")
               .Build();

            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .Enrich.FromLogContext()
                //.MinimumLevel.Warning()
                //.Filter.ByExcluding((le) => le.Level == LogEventLevel.Information)
                .CreateLogger();
        }
        catch (Exception exception)
        {
            Log.Fatal(exception, "Error starting - ConfigureLogging method");
        }
        finally
        {
            //Log.CloseAndFlush(); //no need to close bcz we are using it as a singleton instance.
        }
    }
    
  public void ConfigureServices(IServiceCollection services)
   {
      services.AddSingleton<Serilog.ILogger>(Log.Logger);
   }
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHangfireJobs hangfireJobs, IHttpContextAccessor httpContextAccessor, DBContext dbContext, Serilog.ILogger logger, IServiceProvider serviceProvider, IAntiforgery antiforgery)
   {
   }

appSettings.json

 "Serilog": {
    "Using": [],
    "MinimumLevel": {
      "Default": "Warning",
      "Override": {
        //"Microsoft": "Warning",  // auto write MS warnings
        //"System": "Warning"      // auto write System warnings
      }
    },
    "WriteTo": [
       {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server=tcp:xyz.database.windows.net,1433;Initial Catalog=abc;Persist Security Info=False;User ID=sql;Password=123456;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
          "tableName": "APILogs",
          "schemaName": "dbo",
          "autoCreateSqlTable": true,
          "columnOptionsSection": {
            "addStandardColumns": [ "LogEvent" ],
            "removeStandardColumns": [ "MessageTemplate", "Properties" ],
            "customColumns": [
              {
                "ColumnName": "APIPath",
                "DataType": "varchar",
                "DataLength": 150
              },
              {
                "ColumnName": "ControllerName",
                "DataType": "varchar",
                "DataLength": 50
              },
              {
                "ColumnName": "MethodName",
                "DataType": "varchar",
                "DataLength": 80
              },
              {
                "ColumnName": "LineNumber",
                "DataType": "int"
              }
            ]
          },
          "timeStamp": {
            "columnName": "TimeStamp",
            "convertToUtc": true
          },
          "restrictedToMinimumLevel": "Warning"
        }
      }
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithProcessId",
      "WithThreadId"
    ]
  },
6
  • 1
    Does this answer your question? Different Minimum Level Logs Serilog Commented Jun 9, 2022 at 14:56
  • I have already tried setting MinimumLevel, but didn't work for me. Commented Jun 9, 2022 at 15:10
  • What did you set it to? Seems you want at least Information Commented Jun 9, 2022 at 15:11
  • For SQL Sink you set "restrictedToMinimumLevel": "Warning", though. Commented Jun 9, 2022 at 15:25
  • 3
    ^^ and "Default": "Warning" ... how can you expect to get information-level messages? Set both to "Information". Commented Jun 9, 2022 at 15:31

1 Answer 1

2

In AppSettings.json, please change

"MinimumLevel": {
      "Default": "Warning",

TO

"MinimumLevel": {
      "Default": "Information",

Then it will start logging Information and below (Information, Warning,Error, Critical)

Sign up to request clarification or add additional context in comments.

1 Comment

thanks @Anshul, I was setting only Default property but the restrictedToMinimumLevel property is also needs to be changed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.