Samy Sammour Samy Sammour - 1 year ago 337
ASP.NET (C#) Question

serilog AppSetting in web.config mvc 5

I am working on Serilog 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()
.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)

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

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download