I'm creating a console logger using:
_log = new LoggerFactory().AddConsole().CreateLogger(this.GetType().Name);
Now I'm getting the following warning:
controllers\DummyController.cs(31,20): warning CS0618:
'ConsoleLoggerExtensions.AddConsole(ILoggerFactory)' is obsolete:
'This method is obsolete and will be removed in a future version. The
recommended alternative is AddConsole(this ILoggingBuilder builder).'
I'm not in the context of a dependency injection container.
UPDATE: I also tried using DI like this:
var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
var log = serviceProvider.GetService<ILogger>();
log.LogInformation("testing _log");
But I get the following error:
Error Message:
System.ArgumentNullException : Value cannot be null.
Parameter name: logger
Stack Trace:
at Microsoft.Extensions.Logging.LoggerExtensions.Log(ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, String message, Object[] args)
at Microsoft.Extensions.Logging.LoggerExtensions.LogInformation(ILogger logger, String message, Object[] args)
It seems I can't get the logger from the container
The interface has changed, so that you use a static Create() factory method on LoggerFactory, with a delegate that is passed in a configuration object that you configure the provider on. The factory can then be used to create loggers as before:
ILogger<Program> logger = LoggerFactory
.Create(logging => logging.AddConsole())
.CreateLogger<Program>();
logger.LogInformation("Hello World!");
While an application should usually use a host builder, this can be very useful in unit testing, as you can pass in a real logger that writes to the console (instead of a mock), and see the output in your test results.
This is taken from the simple walkthough example at: https://github.com/sgryphon/essential-logging/tree/master/examples/GettingStarted
There is also further examples that show how to configure via a host builder, and how to use the Microsoft high performance logging pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With