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"
]
},
CodePudding user response:
In AppSettings.json, please change
"MinimumLevel": {
"Default": "Warning",
TO
"MinimumLevel": {
"Default": "Information",
Then it will start logging Information and below (Information, Warning,Error, Critical)