For .NET 5+ use built-in Simple console log formatter. It provides several customization options, for example:
builder.Services.AddLogging(logging =>
logging.AddSimpleConsole(options =>
{
options.SingleLine = true;
options.TimestampFormat = "yyyy-MM-dd HH:mm:ss ";
})
);
Output:
2023-04-13 21:43:47 info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5190
An advanced .NET Core console logger. I forked Microsoft code, improved and packaged it as a NuGet package. Starting from 0.4.0
version, it supports ASP.NET Core 2+ based apps.
With Microsoft.Extensions.Logging.Console:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:6002/hc
With LoggingAdvanced:
[2017.06.15 23:46:44] info: WebHost[1] Request starting HTTP/1.1 GET http://localhost:6002/hc
.NET Core 2 way:
var webHostBuilder = new WebHostBuilder()
.ConfigureLogging((hostingContext, loggingBuilder) =>
{
var loggingSection = hostingContext.Configuration.GetSection("Logging");
loggingBuilder.AddConsoleAdvanced(loggingSection);
})
.NET Core 1 way:
public void Configure(IApplicationBuilder app)
{
var loggerFactory = app.ApplicationServices.GetService<ILoggerFactory>();
loggerFactory.AddConsoleAdvanced(cfg.GetSection("Logging"));
}
Parametrize the AddConsoleAdvanced
call with settings:
loggingBuilder.AddConsoleAdvanced(new ConsoleLoggerSettings()
{
IncludeLineBreak = false,
IncludeTimestamp = true,
IncludeZeroEventId = false,
IncludeLogNamespace = false
});
Or keep the settings in appsettings.json
and provide the configuration section:
AddConsoleAdvanced(Configuration.GetSection("Logging"));
An appsettings.json
file example:
{
"Logging": {
"IncludeLineBreak": true,
"IncludeTimestamp": true,
"IncludeZeroEventId": true,
"IncludeLogNamespace": true,
"TimestampPolicy": {
"TimeZone": "Ulaanbaatar Standard Time",
"Format": "MM/dd/yyyy HH:mm:ss.fff"
}
}
}
Feel free to suggest new ideas.