我这样输出日志:
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(); }我收到消息:
信息:ConsoleLogging.Program [0]
info: ConsoleLogging.Program[0]
这是对紧急广播系统的测试.
This is a test of the emergency broadcast system.
但我想这样:
信息:这是对紧急广播系统的测试.
info: This is a test of the emergency broadcast system.
如何在控制台中格式化日志的输出? 我使用Microsoft.Extensions.Logging,Microsoft.Extensions.Logging.Console库.
How to format the output of logs in the console? I use the libraries Microsoft.Extensions.Logging, Microsoft.Extensions.Logging.Console.
推荐答案我正在尝试做同样的事情.
I'm trying to do the same thing.
我首先创建了一个从ConsoleLogger继承的名为SimpleConsoleLogger的类,以便可以覆盖WriteMessage()方法,但是原始方法中的代码依赖于一些私有内部结构和字段,而我没有不想从头开始编写整个方法.
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.cs的源代码,在其中我可以在WriteMessage()中的类别和事件ID部分中删除以下行:
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);然后我必须基于ConsoleLoggerProvider创建一个SimpleConsoleLoggerProvider类,在其中我用代码替换了SimpleConsoleLogger类,并对ConsoleLoggerExtensions进行了同样的操作以创建SimpleConsoleLoggerExtensions,这样我可以按以下方式将我的记录仪连接到工厂:
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.
更多推荐
如何在控制台中格式化日志的输出?(Microsoft.Extensions.Logging)
发布评论