ARTICLE AD BOX
I'm trying to figure out how to implement Logging in my ASP.NET Core 9.0 Web API. I don't like having to pass a logger object around everywhere, so have been exploring different ways of implementing logging.
I am trying to use a singleton with a static instance using lazy initialization (currently just wraps the built-in ILogger). The only problem is that this seems to require a copy of the ServiceProvider, which results in an additional copy of all the singleton services defined in the container.
I'm wondering what folks' opinion is on this, and if they have any more elegant solutions for this kind of thing.
namespace MyApi.Logging { public class MyLogger { private static readonly Lazy<MyLogger> _instance = new Lazy<MyLogger>(() => new MyLogger( /* Need ServiceLocator pattern to inject ILogger here */)); public static MyLogger Instance = _instance.Value; private readonly ILogger _logger; private MyLogger(ILogger logger) { _logger = logger; } public void LogInformation(string message) => _logger.LogInformation(message); public void LogDebug(string message) => _logger.LogDebug(message); public void LogWarning(string message) => _logger.LogWarning(message); public void LogError(string message) => _logger.LogError(message); public void LogCritical(string message) => _logger.LogCritical(message); } }