Reputation: 51
I make logs output like this:
static void Main(string[] args)
{
ILoggerFactory loggerFactory = new LoggerFactory()
.AddConsole();
ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation(
"This is a test of the emergency broadcast system.");
Console.WriteLine("Press any key...");
Console.Read();
}
And I receive messages:
info: ConsoleLogging.Program[0]
This is a test of the emergency broadcast system.
But I would like so:
info: This is a test of the emergency broadcast system.
How to format the output of logs in the console? I use the libraries Microsoft.Extensions.Logging, Microsoft.Extensions.Logging.Console.
Upvotes: 5
Views: 3754
Reputation: 3157
I'm trying to do the same thing.
I started out by creating a class called SimpleConsoleLogger
that inherits from ConsoleLogger
so that I could override the WriteMessage()
method, but the code in the original method relies on some private internal structs and fields, and I didn't want to write the whole method from scratch.
I ended up creating my own SimpleConsoleLogger
class based off the source code for ConsoleLogger.cs where I could remove the following lines in WriteMessage()
in the category and event id section:
logBuilder.Append(logName);
logBuilder.Append("[");
logBuilder.Append(eventId);
logBuilder.AppendLine("]");
...and the following line in the message section:
logBuilder.Append(_messagePadding);
I then had to create a SimpleConsoleLoggerProvider
class based on ConsoleLoggerProvider
, where I substituted my SimpleConsoleLogger
class in the code, and did the same with ConsoleLoggerExtensions
in order to create SimpleConsoleLoggerExtensions
, so that I may wire my logger into the factory as follows:
_loggerFactory = new LoggerFactory().AddSimpleConsole();
This is not the most simple solution, so the class name is a bit of a misnomer, but it works.
Upvotes: 2