问题
I'm using the built in logging provider for logging into the console (Microsoft.Extensions.Logging.Console
) in a .NET Core console application.
Each logging entry produces two lines in the output. I would like to have each entry in one single line. Is there a way to customize the output format?
Here is an example how I use it:
static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddLogging() // This adds the Microsoft logging.
.AddSingleton<IProjectGeneratorService, CSharpProjectGeneratorService>()
.BuildServiceProvider();
// Configure the console logging.
serviceProvider
.GetService<ILoggerFactory>()
.AddConsole(LogLevel.Debug);
// Write a logging entry
var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Program>();
logger.LogDebug("Application started...");
}
What I get is:
dbug: Generator.Program[0]
Application started...
What I would like to have is something like this:
dbug: Generator.Program[0]: Application started...
Any idea? I know, I could write a custom logger, but I would like to know if there is an other way.
Thanks.
回答1:
At the moment, this not configurable. The source code is here on GitHub:
logBuilder.Append(logName); logBuilder.Append("["); logBuilder.Append(eventId); logBuilder.AppendLine("]");
If you want that, you need to write your own logger. However you can just copy the source code of the console logger, modify as needed and change the namespaces so it doesn't interfere with the version Microsoft ships.
You can also open an issue on the logging repo to ask for this option.
回答2:
As @MartinUllrich already mentioned this line break can't be disabled and you have to implement a custom logger to avoid it.
Registration:
loggerFactory.AddProvider(new CustomLoggerProvider());
The implementation (can be extended with using of the original ConsoleLogger source code - for example, you could add the GetLogLevelConsoleColors
method):
public class CustomLoggerProvider : ILoggerProvider
{
public void Dispose() { }
public ILogger CreateLogger(string categoryName)
{
return new CustomConsoleLogger(categoryName);
}
public class CustomConsoleLogger : ILogger
{
private readonly string _categoryName;
public CustomConsoleLogger(string categoryName)
{
_categoryName = categoryName;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
Console.WriteLine($"{logLevel}: {_categoryName}[{eventId.Id}]: {formatter(state, exception)}");
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
}
}
回答3:
Although you can't specify your own custom format, it does support an alternative "systemd" format which you can select like this:
logging.AddConsole(options => {
options.Format=ConsoleLoggerFormat.Systemd;
});
This outputs each log entry on one line even if you the text has newlines in it (so exceptions aren't very pretty). It also doesn't use colors which is an advantage if you're redirecting to a file.
回答4:
You can use a logging library like Serilog.
Using the instructions from the ASP.NET Core integration you can later simply provide a logging output template via the Console sink
.WriteTo.Console(
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
回答5:
This is updated in .NET 5: https://docs.microsoft.com/en-us/dotnet/core/extensions/console-log-formatter. Now provides simple, systemd and json
来源:https://stackoverflow.com/questions/44230373/is-there-a-way-to-format-the-output-format-in-net-core-logging