You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC5中使用Serilog写JSON日志如何让Exception字段仅显示异常名称

实现方案

自定义JsonFormatter修改Exception字段输出

默认的JsonFormatter会直接调用异常的ToString()方法输出完整内容,我们只需要继承该类重写异常写入逻辑即可:

using Serilog.Events;
using Serilog.Formatting.Json;
using System.IO;

public class CustomJsonFormatter : JsonFormatter
{
    public CustomJsonFormatter(bool renderMessage = false, bool renderMessageTemplate = false) 
        : base(renderMessage, renderMessageTemplate)
    {
    }

    protected override void WriteException(Exception exception, TextWriter output)
    {
        if (exception == null) return;
        // 仅输出异常类型全称,如果你需要同时显示异常消息可以改成 $"{exception.GetType().FullName}: {exception.Message}"
        WriteStringValue(exception.GetType().FullName, output);
    }
}

修改你原有的RollingFile配置,将默认JsonFormatter替换为自定义的实现即可:

.WriteTo.RollingFile(new CustomJsonFormatter(),
    HttpContext.Current.Server.MapPath($"~/logs/log-.json"),
    LogEventLevel.Debug,
    fileSizeLimitBytes: 655360)

修改完成后Exception字段就只会输出你需要的异常名称,不会携带堆栈信息,原本的ExceptionDetails字段不受任何影响。

Logger类优化建议
  • 替换已过时的RollingFile Sink:Serilog.Sinks.File 包现在已经原生支持滚动日志功能,RollingFile 包早已停止维护,建议替换为如下写法:
.WriteTo.File(new CustomJsonFormatter(),
    HttpContext.Current.Server.MapPath($"~/logs/log-.json"),
    LogEventLevel.Debug,
    fileSizeLimitBytes: 655360,
    rollingInterval: RollingInterval.Day, // 按天滚动
    retainedFileCountLimit: 30, // 仅保留最近30天日志,避免磁盘占用过高
    flushToDiskInterval: TimeSpan.FromSeconds(10)) // 定时刷入磁盘,避免程序异常退出丢失日志
  • 降低耦合度:当前静态Logger类和具体实现强绑定,不利于单元测试,建议将Logger注入到容器中,通过依赖注入的方式使用,方便单元测试时Mock日志实例。
  • 增加边界校验:在LogError、LogWarning等方法中增加入参校验,比如当异常对象为null时做兼容处理,避免不必要的空引用异常。
  • 本地开发增加控制台Sink:本地调试阶段可以增加WriteTo.Console()输出日志,不用每次都打开日志文件排查问题,线上环境可以关闭该输出。
  • 增加日志过滤规则:可以根据命名空间过滤不必要的框架层面日志,减少无效日志输出,节省磁盘空间。

内容的提问来源于stack exchange,提问作者Junaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 04:21:03