I recently updated my .NET Core REST API from 3.1 to 6.0. When I run the App locally without Docker in development or release configuration the logs are formatted as always:
When running the App as Docker container, the logs become transformed to JSON. This just appeared after the migration to .Net 6.
How can I get back to the standard logging format in the Docker environment?
The change was made in .NET 5, not 6. In .NET Core 3.1 the Console log format was fixed. In .NET 5 this is now customizable with 3 predefined formatters: Simple (the old one), Systemd and Json (the default). It's possible to create a custom formatter.
As the docs show, it's possible to use the Simple formatter by using the AddSimpleConsole method instead of AddConsole:
using ILoggerFactory loggerFactory =
LoggerFactory.Create(builder =>
builder.AddSimpleConsole(options =>
{
options.IncludeScopes = true;
options.SingleLine = true;
options.TimestampFormat = "hh:mm:ss ";
}));
There are similar methods for the other two formatters: AddSystemdConsole and AddJsonConsole.
It's possible to set the formatter through configuration :
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"Console": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
"FormatterName": "json",
"FormatterOptions": {
"SingleLine": true,
"IncludeScopes": true,
"TimestampFormat": "HH:mm:ss ",
"UseUtcTimestamp": true,
"JsonWriterOptions": {
"Indented": true
}
}
}
},
"AllowedHosts": "*"
}
Finally it's possible to create a completely new formatter by inheriting from ConsoleFormatter and overriding the Write method :
public sealed class CustomFormatter : ConsoleFormatter, IDisposable
{
...
public override void Write<TState>(
in LogEntry<TState> logEntry,
IExternalScopeProvider scopeProvider,
TextWriter textWriter)
{
string? message =
logEntry.Formatter?.Invoke(
logEntry.State, logEntry.Exception);
if (message is null)
{
return;
}
CustomLogicGoesHere(textWriter);
textWriter.WriteLine(message);
}
...
}