DotNet API Custom Logging

Date: 2021-11-05
//using System;
//using Domain;
//using Microsoft.AspNetCore;
//using Microsoft.AspNetCore.Hosting;
//using Microsoft.Extensions.Logging;

public static IWebHost BuildWebHost(string[] args) =>
		WebHost.CreateDefaultBuilder(args)
			.ConfigureLogging((ILoggingBuilder logging) =>
			{
				logging.ClearProviders();
				//logging.AddConsole();
				logging.AddProvider(new CustomLoggerProvider());
			})
			.UseStartup<Startup>()
			.Build();
}

public class CustomLogger : ILogger
{
	public IDisposable BeginScope<TState>(TState state) => default;
	public bool IsEnabled(LogLevel logLevel) => true;

	public void Log<TState>(
		LogLevel logLevel,
		EventId eventId,
		TState state,
		Exception exception,
		Func<TState, Exception, string> formatter)
	{
		if (!IsEnabled(logLevel)) return;
		DomainPorts.Logger.Log(ConvertLogLevel(logLevel), formatter(state, exception), exception);
	}

	private static DNA.Shared.Logging.LogLevel ConvertLogLevel(LogLevel logLevel)
	{
		switch (logLevel)
		{
			case LogLevel.Trace: return DNA.Shared.Logging.LogLevel.Debug;
			case LogLevel.Debug: return DNA.Shared.Logging.LogLevel.Debug;
			case LogLevel.Information:
				return DNA.Shared.Logging.LogLevel.Info;
			case LogLevel.Warning:
				return DNA.Shared.Logging.LogLevel.Warning;
			case LogLevel.Error:
				return DNA.Shared.Logging.LogLevel.Error;
			case LogLevel.Critical:
				return DNA.Shared.Logging.LogLevel.Fatal;
			case LogLevel.None:
			default:
				return DNA.Shared.Logging.LogLevel.Info;
		}
	}
}

public sealed class CustomLoggerProvider : ILoggerProvider
{
	private static readonly CustomLogger logger = new();
	public ILogger CreateLogger(string categoryName) => logger;
	public void Dispose() { }
}
55160cookie-checkDotNet API Custom Logging