[英]How to format the output of logs in the console?(Microsoft.Extensions.Logging)
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]
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.
info:这是对紧急广播系统的测试。
How to format the output of logs in the console? 如何格式化控制台中的日志输出? I use the libraries Microsoft.Extensions.Logging, Microsoft.Extensions.Logging.Console.
我使用库Microsoft.Extensions.Logging,Microsoft.Extensions.Logging.Console。
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. 我开始创建一个名为
SimpleConsoleLogger
的类,它继承自ConsoleLogger
以便我可以覆盖WriteMessage()
方法,但原始方法中的代码依赖于一些私有内部结构和字段,我不想写整个方法从头开始。
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: 我最终根据ConsoleLogger.cs的源代码创建了我自己的
SimpleConsoleLogger
类,我可以在类别和事件id部分中删除WriteMessage()
中的以下行:
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: 然后,我必须创建一个基于
ConsoleLoggerProvider
的SimpleConsoleLoggerProvider
类,我在代码中替换了我的SimpleConsoleLogger
类,并使用ConsoleLoggerExtensions
执行相同操作以创建SimpleConsoleLoggerExtensions
,以便我可以将我的记录器连接到工厂,如下所示:
_loggerFactory = new LoggerFactory().AddSimpleConsole();
This is not the most simple solution, so the class name is a bit of a misnomer, but it works. 这不是最简单的解决方案,因此类名有点用词不当,但它有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.