Asp.net Core中Serilog日志换行问题:如何实现单事件单行可解析且可读
解决ASP.NET Core中Serilog日志单事件单行的问题
不用自己从头实现ITextFormatter复制一堆代码!这里有两个简单的方案,既能满足单事件单行的需求,又兼顾可读性和易解析性:
方案1:使用Serilog原生的JSON格式化器(推荐)
JSON格式天生适合处理带换行的内容,Serilog的RenderedCompactJsonFormatter会自动把日志中的换行符转义为\n,同时保证整个日志事件是单行输出,而且JSON格式本身非常容易被日志分析工具解析,可读性也不差(渲染后的消息是明文)。
配置代码示例:
using Serilog; using Serilog.Formatting.Compact; var builder = WebApplication.CreateBuilder(args); // 配置Serilog Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(builder.Configuration) .WriteTo.File( formatter: new RenderedCompactJsonFormatter(), path: "logs/app-.json", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7) .CreateLogger(); builder.Host.UseSerilog();
这样异常的堆栈信息、Microsoft事件中的换行都会被自动转义,每条日志都是独立的单行JSON,完美满足你的需求。
方案2:自定义轻量格式化器(包装原生实现)
如果你更偏好纯文本格式,不想用JSON,可以自定义一个简单的格式化器,包装Serilog原生的MessageTemplateTextFormatter,只处理换行替换的逻辑,完全复用原生的日志格式化逻辑,不用复制大量代码:
using Serilog; using Serilog.Events; using Serilog.Formatting; using Serilog.Formatting.Display; using System.IO; public class SingleLineTextFormatter : ITextFormatter { private readonly MessageTemplateTextFormatter _innerFormatter; // 可以传入自定义的日志模板,默认用常见的文本格式 public SingleLineTextFormatter(string format = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {Exception}") { _innerFormatter = new MessageTemplateTextFormatter(format); } public void Format(LogEvent logEvent, TextWriter output) { // 先让原生格式化器生成日志内容 using var tempWriter = new StringWriter(); _innerFormatter.Format(logEvent, tempWriter); // 替换所有换行符为空格(或者你想要的其他占位符) var singleLineText = tempWriter.ToString() .Replace(Environment.NewLine, " ") .Replace("\n", " ") .Replace("\r", " "); output.Write(singleLineText); } }
使用这个自定义格式化器的配置:
Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(builder.Configuration) .WriteTo.File( formatter: new SingleLineTextFormatter(), path: "logs/app-.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7) .CreateLogger();
这个方法的好处是:既保留了Serilog原生的日志模板解析、级别格式化等功能,只针对换行问题做处理,代码量极少,维护成本低。
不管用哪个方案,都能解决异常日志和Microsoft事件中的换行问题,实现单事件单行的效果,同时兼顾可读性和易解析性。
内容的提问来源于stack exchange,提问作者Andrew Radford
相关产品推荐
相关产品推荐

