guys. I try to add logging to my console app with DI (.NET Core 3.1) and seems that IoC container works fine for that, injects logger dependency to my classes, but LogXXX method doesn't log to output. What can be the reason? Maybe there are some additional configurations?
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace DependencyInjection
{
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
ConfigureServices(services);
var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetService<ILogger<Program>>();
logger.LogInformation("Hello world!");
}
static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(loggerBuilder =>
{
loggerBuilder.ClearProviders();
loggerBuilder.AddConsole();
});
}
}
}
Set the environment key Logging:LogLevel:Microsoft to a value of Information on Windows. Test the settings when using an app created with the ASP.NET Core web application templates. The dotnet run command must be run in the project directory after using set .
ILoggerFactory is a factory interface that we can use to create instances of the ILogger type and register logging providers. It acts as a wrapper for all the logger providers registered to it and a logger it creates can write to all the logger providers at once.
NLog is one of the most popular, and one of the best-performing logging frameworks for . NET. Setting up NLog is fairly simple. Developers can use Nuget to download the dependency, then edit the NLog.
Docs have current example for Console App
class Program
{
static void Main(string[] args)
{
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
.AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
.AddConsole();
});
ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation("Example log message");
}
}
Of course you need to install the appropriate Nuget packages:
Microsoft.Extensions.Logging
Microsoft.Extensions.Logging.Console
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