I am working on Serilog asp.net MVC 5. everything works fine but I want to move the setting to web.config instead of code. I need to move the database connection, file path. and also I have to specify two different levels one for database and one for the file.
this is the code
var logFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"xxx.Web-{Environment.MachineName}.log");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Trace(LogEventLevel.Debug, "{Timestamp:u} [{Level}] {SourceContext}:: {CorrelationId} {Message}{NewLine}{Exception}")
.WriteTo.LiterateConsole(LogEventLevel.Debug, "{Timestamp:u} [{Level}] {SourceContext}:: {CorrelationId} {Message}{NewLine}{Exception}")
.WriteTo.RollingFile(logFileName, LogEventLevel.Debug,
"{Timestamp:u} [{Level}] {MachineName} {SourceContext}:: {CorrelationId} {Message}{NewLine}{Exception}",
retainedFileCountLimit: 31, fileSizeLimitBytes: null)
.WriteTo.MSSqlServer(connectionString, "LogUsers", LogEventLevel.Information)
.Enrich.WithExceptionDetails()
.Enrich.With<HttpRequestIdEnricher>()
.Enrich.FromLogContext()
.CreateLogger();
P.S. connectionString variable came from web.config.
I am very new to serilog, so I am really confussed. please if you can replay as soon as possible.
thank you
What you need to do is add Serilog information in the appSettings
tag within Web.Config.
<add key="serilog:using:MSSqlSever" value="Serilog.Sinks.MSSqlServer" />
<add key="serilog:write-to:MSSqlServer.connectionString" value="nameOfConnectionString" />
<add key="serilog:write-to:MSSqlServer.tableName" value="Serilogs" />
<add key="serilog:write-to:MSSqlServer.autoCreateSqlTable" value="true" />
The above code helps you log to SQL database.
<add key="serilog:using:File" value="Serilog.Sinks.File" />
<add key="serilog:write-to:File.path" value="log.txt" />
<add key="serilog:write-to:File.fileSizeLimitBytes" value="" />
And the above helps you write to a text file.
All what you will have to do in your code is just call the log function and it will automatically log to what you have specified in the config.
You may want to look at these two pages for more help:
https://github.com/serilog/serilog-sinks-mssqlserver
https://github.com/serilog/serilog-sinks-file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With