如何在控制台中格式化日志的输出?(Microsoft.Extensions.Logging)

编程入门 行业动态 更新时间:2024-10-26 13:30:49
本文介绍了如何在控制台中格式化日志的输出?(Microsoft.Extensions.Logging)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我这样输出日志:

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)

本文发布于:2023-11-15 04:09:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591018.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制台   如何在   日志   Logging   Extensions

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!