custom logging in serilog

Viewed 52

I am logging using serilog. While logging, if I pull the log level to information, I get a lot of logs and my db is bloated. I only want the logs that I have written as the information that I have defined in my controllers to work, but that the high-level logs (warning,error) are automatically thrown. How can I do that?

builder.Services.AddHttpLogging(logging =>
            {
                logging.LoggingFields = HttpLoggingFields.All;
                logging.RequestHeaders.Add("sec-ch-ua");
                logging.ResponseHeaders.Add("MyResponseHeader");
                logging.MediaTypeOptions.AddText("application/javascript");
                logging.RequestBodyLogLimit = 4096;
                logging.ResponseBodyLogLimit = 4096;
            });
            SqlColumn sqlColumn = new SqlColumn();
            sqlColumn.ColumnName = "UserName";
            sqlColumn.DataType = System.Data.SqlDbType.NVarChar;
            sqlColumn.PropertyName = "UserName";
            sqlColumn.DataLength = 50;
            sqlColumn.AllowNull = true;
            ColumnOptions columnOpt = new ColumnOptions();
            columnOpt.Store.Remove(StandardColumn.Properties);
            columnOpt.Store.Add(StandardColumn.LogEvent);
            columnOpt.AdditionalColumns = new Collection<SqlColumn> { sqlColumn };
     Logger log = new LoggerConfiguration()
                    .WriteTo.Console()
                    .WriteTo.File("logs/log.txt")
                    .WriteTo.MSSqlServer(
                    connectionString: builder.Configuration.GetConnectionString("SqlCon"),
                     sinkOptions: new MSSqlServerSinkOptions
                     {
                         AutoCreateSqlTable = true,
                         TableName = "logs",                             
                     },
                     appConfiguration: null,
                     columnOptions: columnOpt        
                    )                        
                    .Enrich.FromLogContext()
                    .Enrich.With<CustomUserNameColumn>()
                    .MinimumLevel.Warning()
                    .WriteTo.Seq(builder.Configuration["Seq:Url"])
                    .CreateLogger();
                builder.Host.UseSerilog(log);

Action Method

         [HttpPost]
        public IActionResult AddConnection(UserViewModel model)
        {
            _log.LogInformation($"{User.Identity.Name},{model.Name} is connected");
           return Redirect($"FindConnection/{model.Search}");
        }
1 Answers

Try this. It will only include the log matching with filter.

 .UseSerilog((context, loggerConfig) =>
 {
   loggerConfig.Filter.ByIncludingOnly(logevent => logevent.Level == Serilog.Events.LogEventLevel.Information);
 })
Related