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?
Asked
Active
Viewed 1,477 times
0
-
@PeterBons Sorry for the confusion, but I'm not using .net core. – dmoore1181 Mar 25 '19 at 18:45
-
Hi, I have added a rather detailed version of the config we have been using for our Web APIs in my previous job from 2015-ish to 2018 . It might be useful to you : https://stackoverflow.com/a/55365917/474763 – tsimbalar Mar 26 '19 at 20:47
2 Answers
0
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"/>

ElasticCode
- 7,311
- 2
- 34
- 45