ASP.Net Core Logging
See docs.asp.net
Nuget packages
- "Microsoft.Extensions.Logging"
- One or more loggers:
- "Microsoft.Extensions.Logging.Console" - console logging.
- "Microsoft.Extensions.Logging.EventLog" - windows events.
- Another CoreFx-compatible logger (Serilog is one: Serilog.Framework.Logging)
Startup
- Startup.Configure: loggerFactory.AddConsole(); or loggerFactory.AddSerilog()
Or configure log filtering eg loggerFactory.AddConsole(LogLevel.Debug) (default is Verbose)
For file logging, take IHostingEnvironment and use the hostEnv.ContentRootPath - You can log in Configure - take argument ILoggerFactory. Use it after AddConsole.
Use
- Either- take argument ILoggerFactory and created a named logger
var logger = loggerFactory.CreateLogger("Catchall Endpoint");
//Debug-Verbose (default)-Information-Warning-Error-Critical
logger.LogWarning("Something happened {path}", context.Request.Path); - Or = take argument ILogger<T> where T is probably your classname.
Unit Tests
In a test you will need to provide an ILogger<X>. Provide it with NullLogger<X>.Instance
var validator = new X(NullLogger<X>.Instance);
NLog
Sample NLog setup in .net 6 Program.cs
public class Program
{
public static void Main(string[] args)
{
Trace.Listeners.Add(new NLogTraceListener());
var builder = WebApplication.CreateBuilder(args);
// NLog: Setup NLog for Dependency injection
builder.Logging.ClearProviders();
builder.Host.UseNLog();
builder.Services.AddControllers();
{
public static void Main(string[] args)
{
Trace.Listeners.Add(new NLogTraceListener());
var builder = WebApplication.CreateBuilder(args);
// NLog: Setup NLog for Dependency injection
builder.Logging.ClearProviders();
builder.Host.UseNLog();
builder.Services.AddControllers();