I want to setup logging on my asp.net web api (Not Asp.Net Core), and want to make sure that I follow best practices (as close as possible). I am using SeriLog in my services, and would like to use this product for my Web Api as well. I am not sure of the best way to setup logging in Web API, and I would like to set it up such that depending on the context (my api serves multiple apps) I would like to be able to log to a separate Microsoft Sql Server. Can somebody please provide some direction on how to get started at this task, potential pitfalls, or a link to an article that I have yet to find on how to set this up in Asp.Net?
You can create a centralized logger project and add serilog packages to this project only, and reference this project where you need to use serilog (your services).
And configure serilog using Serilog.Settings.AppSettings package so each service project will read its own configuration (Ex: separate Microsoft SQL Server) from <appSettings>
section in service web.config
useing the ReadFrom.AppSettings()
extension method on your LoggerConfiguration
Sample Logger Class
public static class Logger
{
private static readonly ILogger _dbLogger;
static Logger()
{
_dbLogger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.CreateLogger();
}
public static void Log(string error)
{
_dbLogger.Error(error);
}
}
Sample appSettings
configuration
<add key="serilog:using:MSSqlServer" value="Serilog.Sinks.MSSqlServer" />
<add key="serilog:write-to:MSSqlServer.connectionString" value="Server=..."/>
<add key="serilog:write-to:MSSqlServer.tableName" value="Logs"/>
<add key="serilog:write-to:MSSqlServer.autoCreateSqlTable" value="true"/>