找回密码
 立即注册
首页 业界区 业界 Util应用框架基础(六) - 日志记录(一) - 正文 ...

Util应用框架基础(六) - 日志记录(一) - 正文

呼延冰枫 2025-6-9 08:20:02
本文介绍Util应用框架如何记录日志.
日志记录共分4篇,本文是正文,后续还有3篇分别介绍写入不同日志接收器的安装和配置方法.
概述

日志记录对于了解系统执行情况非常重要.
Asp.Net Core 抽象了日志基础架构,支持使用日志提供程序进行扩展,提供控制台日志等简单实现.
Serilog 是 .Net 流行的第三方日志框架,支持结构化日志,并能与 Asp.Net Core 日志集成.
Serilog 支持多种日志接收器,可以将日志发送到不同的地方.
我们可以将日志写入文本文件,但查看文本文件比较困难,文件如果很大,查找问题非常费力.
对于生产环境,我们需要包含管理界面的日志系统.
Seq 是一个日志系统,可以很好的展示结构化日志数据,并提供模糊搜索功能.
Exceptionless 是基于 Asp.Net Core 开发的日志系统.
与 Seq 相比,Exceptionless 搜索能力较弱.
Seq 和 Exceptionless 都提供了 Serilog 日志接收器,可以使用 Serilog 接入它们.
Util应用框架使用 Serilog 日志框架,同时集成了 SeqExceptionless 日志系统.
Util简化了日志配置,并对常用功能进行扩展.
日志配置

选择日志接收器

Util应用框架默认支持三种 Serilog 日志接收器:

  • 日志文件
  • Seq
  • Exceptionless
你可以从中选择一种或多种,如果都不能满足要求,你也可以引用 Serilog 支持的其它日志接收器,或自行实现.
配置日志接收器

请转到特定日志接收器章节查看配置方法.
配置日志级别

Asp.Net Core 使用日志级别表示日志的严重程度,定义如下:

  • Trace = 0
  • Debug = 1
  • Information = 2
  • Warning = 3
  • Error = 4
  • Critical = 5
  • None = 6
None不开启日志,Trace的严重程度最低,Critical的严重程度最高,需要高度关注.
可以在 appsettings.json 配置文件设置日志级别.
  1. {
  2.   "Logging": {
  3.     "LogLevel": {
  4.       "Default": "Information"
  5.     }
  6.   }
  7. }
复制代码
Logging 配置节用于配置日志.
LogLevel 为所有日志提供程序配置日志级别.
Default 为所有日志类别设置默认的日志级别.
上面的配置将默认日志级别设置为 Information.
意味着只输出日志级别等于或大于 Information 的日志.
现在 Trace 和 Debug 两个级别的日志被禁用了.
可以为特定日志类别设置日志级别.
  1. {
  2.   "Logging": {
  3.     "LogLevel": {
  4.       "Default": "Information",
  5.       "Microsoft": "Debug",
  6.     }
  7.   }
  8. }
复制代码
配置增加了 Microsoft 日志类别,并设置为 Debug 日志级别.
日志类别用来给日志分类,一般使用带命名空间的类名作为日志类别.
日志类别支持模糊匹配, Microsoft 日志类别不仅匹配 Microsoft ,而且还能匹配以 Microsoft 开头的所有日志类别,比如 Microsoft.AspNetCore .
Serilog 的日志级别

Serilog 定义了自己的日志级别,不支持上面介绍的标准配置方式.
Exceptionless 也是如此.
使用第三方框架的日志级别会导致复杂性.
Util应用框架扩展了 Serilog 和 Exceptionless 的日志级别配置,允许以统一的标准方式进行配置.
记录日志

.Net 提供了标准的日志记录接口 Microsoft.Extensions.Logging.ILogger.
你可以使用 ILogger 记录日志.
Util应用框架还提供了一个 Util.Logging.ILog 接口.
当你需要写入很长的日志时,可能需要使用 StringBuilder 拼接日志内容.
ILog 提供了一种更简单的方式写入长内容日志.
使用 ILogger 记录日志

ILogger 支持泛型参数, 用来指定日志类别,使用带命名空间的类名作为日志类别.
  1. namespace Demo;
  2. public class DemoController : WebApiControllerBase {
  3.     public DemoController( ILogger<DemoController> logger ) {
  4.         logger.LogDebug( "Util" );
  5.     }
  6. }
复制代码
示例在控制器构造方法注入 ILogger ,日志类别为 Demo.DemoController .
ILogger 扩展了一些以 Log 开头的方法,比如 LogDebug,表示写入日志级别为 Debug 的消息.
logger.LogDebug( "Util" ) 以 Debug 日志级别写入消息'Util'.
使用 ILog 记录日志

Util应用框架定义了 ILog 接口.
ILog 是对 ILogger 接口的简单包装, 对日志内容的设置进行了扩展.
ILog 也使用泛型参数来指定日志类别.
使用 ILog 完成上面相同的示例.
  1. public class DemoController : WebApiControllerBase {
  2.     public DemoController( ILog<DemoController> log ) {
  3.         log.Message( "Util" ).LogDebug();
  4.     }
  5. }
复制代码
Message 是 ILog 定义的方法, 用来设置日志消息,可以多次调用它拼接内容.
当你需要写比较长的日志内容, ILog 可以帮你拼接内容,这样省去了定义 StringBuilder 的麻烦.
可以在 ILog 添加自定义扩展方法来设置内容, Util应用框架内置了一些设置日志消息的扩展方法, 比如 AppendLine.
  1. public class DemoController : WebApiControllerBase {
  2.     public DemoController( ILog<DemoController> log ) {
  3.         log.AppendLine( "内容1" )
  4.             .AppendLine( "内容2" )
  5.             .LogDebug();
  6.     }
  7. }
复制代码
你可以定义自己的扩展方法,以更加语义化的方式记录日志.
范例:
  1. public class DemoController : WebApiControllerBase {
  2.     public DemoController( ILog<DemoController> log ) {
  3.         log.Caption( "标题" )
  4.             .Content( "内容" )
  5.             .Sql( "Sql" )
  6.             .LogDebug();
  7.     }
  8. }
复制代码
ILog 与 ILogger 比较:
ILog 更擅长记录内容很长的日志.
ILog 是有状态服务,不能在多个线程共享使用.
可以使用 ILog 记录业务日志,其它场景应使用 ILogger.
结构化日志支持

Serilog 日志框架对结构化日志提供了支持.
结构化日志使用特定语法的消息模板日志格式,可以从日志文本中提取搜索元素.
结构化日志的优势主要体现在日志系统对日志消息的展示和搜索方式上.
不同的日志系统对结构化日志的展示方式和搜索能力不同.
请参考 Seq 和 Exceptionless 的 结构化日志支持 小节.
日志操作上下文

记录日志时,我们除了需要记录业务内容,还需要知道一些额外的信息,比如操作用户是谁.
我们希望记录日志时仅设置业务内容,这些额外的信息最好能自动记录.
Util应用框架通过日志上下文自动设置这些额外信息.

  • UserId 设置当前操作用户标识
  • Application 设置当前应用程序名称.
  • Environment 设置当前环境名称.
  • TraceId 设置跟踪号.
  • Stopwatch 设置计时器,用于记录请求执行花了多长时间.
在 Asp.Net Core 环境, 日志上下文由日志上下文中间件 Util.Applications.Logging.LogContextMiddleware 创建.
无需手工添加日志上下文中间件,只要引用 Util.Application.WebApi 类库, 就会自动添加到中间件管道.
对于 Web 请求, 跟踪号是一个重要的信息,可以通过查询跟踪号,将相关的请求日志全部查出来.
另外, Exceptionless 会自动收集很多系统信息.
源码解析

ILog 日志操作

ILog 日志操作接口提供链式调用方式设置日志内容.

  • Message 方法设置日志消息.
  • Property 方法设置扩展属性.
  • State 设置日志参数对象.
Log 开头的日志记录方法,将日志操作委托给 ILogger 相关方法.
  1. /// <summary>
  2. /// 日志操作
  3. /// </summary>
  4. /// <typeparam name="TCategoryName">日志类别</typeparam>
  5. public interface ILog<out TCategoryName> : ILog {
  6. }
  7. /// <summary>
  8. /// 日志操作
  9. /// </summary>
  10. public interface ILog {
  11.     /// <summary>
  12.     /// 设置日志事件标识
  13.     /// </summary>
  14.     /// <param name="eventId">日志事件标识</param>
  15.     ILog EventId( EventId eventId );
  16.     /// <summary>
  17.     /// 设置异常
  18.     /// </summary>
  19.     /// <param name="exception">异常</param>
  20.     ILog Exception( Exception exception );
  21.     /// <summary>
  22.     /// 设置自定义扩展属性
  23.     /// </summary>
  24.     /// <param name="propertyName">属性名</param>
  25.     /// <param name="propertyValue">属性值</param>
  26.     ILog Property( string propertyName, string propertyValue );
  27.     /// <summary>
  28.     /// 设置日志状态对象
  29.     /// </summary>
  30.     /// <param name="state">状态对象</param>
  31.     ILog State( object state );
  32.     /// <summary>
  33.     /// 设置日志消息
  34.     /// </summary>
  35.     /// <param name="message">日志消息</param>
  36.     /// <param name="args">日志消息参数</param>
  37.     ILog Message( string message, params object[] args );
  38.     /// <summary>
  39.     /// 是否启用
  40.     /// </summary>
  41.     /// <param name="logLevel">日志级别</param>
  42.     bool IsEnabled( LogLevel logLevel );
  43.     /// <summary>
  44.     /// 开启日志范围
  45.     /// </summary>
  46.     /// <typeparam name="TState">日志状态类型</typeparam>
  47.     /// <param name="state">日志状态</param>
  48.     IDisposable BeginScope<TState>( TState state );
  49.     /// <summary>
  50.     /// 写跟踪日志
  51.     /// </summary>
  52.     ILog LogTrace();
  53.     /// <summary>
  54.     /// 写调试日志
  55.     /// </summary>
  56.     ILog LogDebug();
  57.     /// <summary>
  58.     /// 写信息日志
  59.     /// </summary>
  60.     ILog LogInformation();
  61.     /// <summary>
  62.     /// 写警告日志
  63.     /// </summary>
  64.     ILog LogWarning();
  65.     /// <summary>
  66.     /// 写错误日志
  67.     /// </summary>
  68.     ILog LogError();
  69.     /// <summary>
  70.     /// 写致命日志
  71.     /// </summary>
  72.     ILog LogCritical();
  73. }
复制代码
ILogExtensions 日志操作扩展

Util应用框架内置了几个日志操作扩展方法,你可以定义自己的扩展方法,以方便内容设置.
  1. /// <summary>
  2. /// 日志操作扩展
  3. /// </summary>
  4. public static class ILogExtensions {
  5.     /// <summary>
  6.     /// 添加消息
  7.     /// </summary>
  8.     /// <param name="log">配置项</param>
  9.     /// <param name="message">消息</param>
  10.     /// <param name="args">日志消息参数</param>
  11.     public static ILog Append( this ILog log,string message, params object[] args ) {
  12.         log.CheckNull( nameof( log ) );
  13.         log.Message( message, args );
  14.         return log;
  15.     }
  16.     /// <summary>
  17.     /// 当条件为true添加消息
  18.     /// </summary>
  19.     /// <param name="log">配置项</param>
  20.     /// <param name="message">消息</param>
  21.     /// <param name="condition">条件,值为true则添加消息</param>
  22.     /// <param name="args">日志消息参数</param>
  23.     public static ILog AppendIf( this ILog log, string message,bool condition, params object[] args ) {
  24.         log.CheckNull( nameof( log ) );
  25.         if ( condition )
  26.             log.Message( message, args );
  27.         return log;
  28.     }
  29.     /// <summary>
  30.     /// 添加消息并换行
  31.     /// </summary>
  32.     /// <param name="log">配置项</param>
  33.     /// <param name="message">消息</param>
  34.     /// <param name="args">日志消息参数</param>
  35.     public static ILog AppendLine( this ILog log, string message, params object[] args ) {
  36.         log.CheckNull( nameof( log ) );
  37.         log.Message( message, args );
  38.         log.Message( Environment.NewLine );
  39.         return log;
  40.     }
  41.     /// <summary>
  42.     /// 当条件为true添加消息并换行
  43.     /// </summary>
  44.     /// <param name="log">配置项</param>
  45.     /// <param name="message">消息</param>
  46.     /// <param name="condition">条件,值为true则添加消息</param>
  47.     /// <param name="args">日志消息参数</param>
  48.     public static ILog AppendLineIf( this ILog log, string message, bool condition, params object[] args ) {
  49.         log.CheckNull( nameof( log ) );
  50.         if ( condition ) {
  51.             log.Message( message, args );
  52.             log.Message( Environment.NewLine );
  53.         }
  54.         return log;
  55.     }
  56.     /// <summary>
  57.     /// 消息换行
  58.     /// </summary>
  59.     /// <param name="log">配置项</param>
  60.     public static ILog Line( this ILog log ) {
  61.         log.CheckNull( nameof(log) );
  62.         log.Message( Environment.NewLine );
  63.         return log;
  64.     }
  65. }
复制代码
LogContext 日志上下文

通过日志上下文自动记录重要的额外信息.
  1. /// <summary>
  2. /// 日志上下文
  3. /// </summary>
  4. public class LogContext {
  5.     /// <summary>
  6.     /// 初始化日志上下文
  7.     /// </summary>
  8.     public LogContext() {
  9.         Data = new Dictionary<string, object>();
  10.     }
  11.     /// <summary>
  12.     /// 计时器
  13.     /// </summary>
  14.     public Stopwatch Stopwatch { get; set; }
  15.     /// <summary>
  16.     /// 跟踪标识
  17.     /// </summary>
  18.     public string TraceId { get; set; }
  19.     /// <summary>
  20.     /// 用户标识
  21.     /// </summary>
  22.     public string UserId { get; set; }
  23.     /// <summary>
  24.     /// 应用程序
  25.     /// </summary>
  26.     public string Application { get; set; }
  27.     /// <summary>
  28.     /// 执行环境
  29.     /// </summary>
  30.     public string Environment { get; set; }
  31.     /// <summary>
  32.     /// 扩展数据
  33.     /// </summary>
  34.     public IDictionary<string, object> Data { get; }
  35. }
复制代码
LogContextMiddleware 日志上下文中间件

日志上下文中间件创建日志上下文,并添加到 HttpContext 对象的 Items .
  1. /// <summary>
  2. /// 日志上下文中间件
  3. /// </summary>
  4. public class LogContextMiddleware {
  5.     /// <summary>
  6.     /// 下个中间件
  7.     /// </summary>
  8.     private readonly RequestDelegate _next;
  9.     /// <summary>
  10.     /// 初始化日志上下文中间件
  11.     /// </summary>
  12.     /// <param name="next">下个中间件</param>
  13.     public LogContextMiddleware( RequestDelegate next ) {
  14.         _next = next;
  15.     }
  16.     /// <summary>
  17.     /// 执行中间件
  18.     /// </summary>
  19.     /// <param name="context">Http上下文</param>
  20.     public async Task Invoke( HttpContext context ) {
  21.         var traceId = context.Request.Headers["x-correlation-id"].SafeString();
  22.         if ( traceId.IsEmpty() )
  23.             traceId = context.TraceIdentifier;
  24.         var session = context.RequestServices.GetService<Util.Sessions.ISession>();
  25.         var environment = context.RequestServices.GetService<IWebHostEnvironment>();
  26.         var logContext = new LogContext {
  27.             Stopwatch = Stopwatch.StartNew(),
  28.             TraceId = traceId,
  29.             UserId = session?.UserId,
  30.             Application = environment?.ApplicationName,
  31.             Environment = environment?.EnvironmentName
  32.         };
  33.         context.Items[LogContextAccessor.LogContextKey] = logContext;
  34.         await _next( context );
  35.     }
  36. }
复制代码
ILogContextAccessor 日志上下文访问器

日志上下文访问器从 HttpContext.Items 获取日志上下文.
  1. /// <summary>
  2. /// 日志上下文访问器
  3. /// </summary>
  4. public interface ILogContextAccessor {
  5.     /// <summary>
  6.     /// 日志上下文
  7.     /// </summary>
  8.     LogContext Context { get; set; }
  9. }
  10. /// <summary>
  11. /// 日志上下文访问器
  12. /// </summary>
  13. public class LogContextAccessor : ILogContextAccessor {
  14.     /// <summary>
  15.     /// 日志上下文键名
  16.     /// </summary>
  17.     public const string LogContextKey = "Util.Logging.LogContext";
  18.     /// <summary>
  19.     /// 日志上下文
  20.     /// </summary>
  21.     public LogContext Context {
  22.         get => Util.Helpers.Convert.To<LogContext>( Web.HttpContext.Items[LogContextKey] );
  23.         set => Web.HttpContext.Items[LogContextKey] = value;
  24.     }
  25. }
复制代码
LogContextEnricher 日志上下文扩展

Serilog 提供 ILogEventEnricher 接口用于设置扩展属性.
LogContextEnricher 使用 Ioc.Create 方法获取依赖服务 ILogContextAccessor.
这是因为不能使用依赖注入,它要求实现类必须是无参构造函数.
Ioc.Create 在 Asp.Net Core 环境获取依赖服务是安全的,但在其它环境则可能获取失败.
如果获取日志上下文失败,也不会对功能造成影响,只是丢失了一些上下文信息.
  1. /// <summary>
  2. /// 日志上下文扩展属性
  3. /// </summary>
  4. public class LogContextEnricher : ILogEventEnricher {
  5.     /// <summary>
  6.     /// 扩展属性
  7.     /// </summary>
  8.     /// <param name="logEvent">日志事件</param>
  9.     /// <param name="propertyFactory">日志事件属性工厂</param>
  10.     public void Enrich( LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
  11.         var accessor = Ioc.Create<ILogContextAccessor>();
  12.         if ( accessor == null )
  13.             return;
  14.         var context = accessor.Context;
  15.         if ( context == null )
  16.             return;
  17.         if ( logEvent == null )
  18.             return;
  19.         if ( propertyFactory == null )
  20.             return;
  21.         RemoveProperties( logEvent );
  22.         AddDuration( context,logEvent, propertyFactory );
  23.         AddTraceId( context, logEvent, propertyFactory );
  24.         AddUserId( context, logEvent, propertyFactory );
  25.         AddApplication( context, logEvent, propertyFactory );
  26.         AddEnvironment( context, logEvent, propertyFactory );
  27.         AddData( context, logEvent, propertyFactory );
  28.     }
  29.     /// <summary>
  30.     /// 移除默认设置的部分属性
  31.     /// </summary>
  32.     private void RemoveProperties( LogEvent logEvent ) {
  33.         logEvent.RemovePropertyIfPresent( "ActionId" );
  34.         logEvent.RemovePropertyIfPresent( "ActionName" );
  35.         logEvent.RemovePropertyIfPresent( "RequestId" );
  36.         logEvent.RemovePropertyIfPresent( "RequestPath" );
  37.         logEvent.RemovePropertyIfPresent( "ConnectionId" );
  38.     }
  39.     /// <summary>
  40.     /// 添加执行持续时间
  41.     /// </summary>
  42.     private void AddDuration( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
  43.         if ( context?.Stopwatch == null )
  44.             return;
  45.         var property = propertyFactory.CreateProperty( "Duration", context.Stopwatch.Elapsed.Description() );
  46.         logEvent.AddOrUpdateProperty( property );
  47.     }
  48.     /// <summary>
  49.     /// 添加跟踪号
  50.     /// </summary>
  51.     private void AddTraceId( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
  52.         if ( context == null || context.TraceId.IsEmpty() )
  53.             return;
  54.         var property = propertyFactory.CreateProperty( "TraceId", context.TraceId );
  55.         logEvent.AddOrUpdateProperty( property );
  56.     }
  57.     /// <summary>
  58.     /// 添加用户标识
  59.     /// </summary>
  60.     private void AddUserId( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
  61.         if ( context == null || context.UserId.IsEmpty() )
  62.             return;
  63.         var property = propertyFactory.CreateProperty( "UserId", context.UserId );
  64.         logEvent.AddOrUpdateProperty( property );
  65.     }
  66.     /// <summary>
  67.     /// 添加应用程序
  68.     /// </summary>
  69.     private void AddApplication( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
  70.         if ( context == null || context.Application.IsEmpty() )
  71.             return;
  72.         var property = propertyFactory.CreateProperty( "Application", context.Application );
  73.         logEvent.AddOrUpdateProperty( property );
  74.     }
  75.     /// <summary>
  76.     /// 添加执行环境
  77.     /// </summary>
  78.     private void AddEnvironment( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
  79.         if ( context == null || context.Environment.IsEmpty() )
  80.             return;
  81.         var property = propertyFactory.CreateProperty( "Environment", context.Environment );
  82.         logEvent.AddOrUpdateProperty( property );
  83.     }
  84.     /// <summary>
  85.     /// 添加扩展数据
  86.     /// </summary>
  87.     private void AddData( LogContext context, LogEvent logEvent, ILogEventPropertyFactory propertyFactory ) {
  88.         if ( context?.Data == null || context.Data.Count == 0 )
  89.             return;
  90.         foreach ( var item in context.Data ) {
  91.             var property = propertyFactory.CreateProperty( item.Key, item.Value );
  92.             logEvent.AddOrUpdateProperty( property );
  93.         }
  94.     }
  95. }
复制代码
LoggerEnrichmentConfigurationExtensions

将 LogContextEnricher 扩展到 LoggerEnrichmentConfiguration 上.
  1. /// <summary>
  2. /// Serilog扩展属性配置扩展
  3. /// </summary>
  4. public static class LoggerEnrichmentConfigurationExtensions {
  5.     /// <summary>
  6.     /// 添加日志上下文扩展属性
  7.     /// </summary>
  8.     /// <param name="source">日志扩展配置</param>
  9.     public static LoggerConfiguration WithLogContext( this LoggerEnrichmentConfiguration source ) {
  10.         source.CheckNull( nameof( source ) );
  11.         return source.With<LogContextEnricher>();
  12.     }
  13.     /// <summary>
  14.     /// 添加日志级别扩展属性
  15.     /// </summary>
  16.     /// <param name="source">日志扩展配置</param>
  17.     public static LoggerConfiguration WithLogLevel( this LoggerEnrichmentConfiguration source ) {
  18.         source.CheckNull( nameof( source ) );
  19.         return source.With<LogLevelEnricher>();
  20.     }
  21. }
复制代码
AddSerilog 配置方法

AddSerilog 配置方法封装了 Serilog 的配置.

  • 配置 ILog 接口服务依赖.
  • 将 Asp.Net Core 日志级别转换为 Serilog 日志级别.
  • 设置日志上下文扩展.
  1. /// <summary>
  2. /// Serilog日志操作扩展
  3. /// </summary>
  4. public static class AppBuilderExtensions {
  5.     /// <summary>
  6.     /// 配置Serilog日志操作
  7.     /// </summary>
  8.     /// <param name="builder">应用生成器</param>
  9.     public static IAppBuilder AddSerilog( this IAppBuilder builder ) {
  10.         return builder.AddSerilog( false );
  11.     }
  12.     /// <summary>
  13.     /// 配置Serilog日志操作
  14.     /// </summary>
  15.     /// <param name="builder">应用生成器</param>
  16.     /// <param name="isClearProviders">是否清除默认设置的日志提供程序</param>
  17.     public static IAppBuilder AddSerilog( this IAppBuilder builder, bool isClearProviders ) {
  18.         return builder.AddSerilog( options => {
  19.             options.IsClearProviders = isClearProviders;
  20.         } );
  21.     }
  22.     /// <summary>
  23.     /// 配置Serilog日志操作
  24.     /// </summary>
  25.     /// <param name="builder">应用生成器</param>
  26.     /// <param name="appName">应用程序名称</param>
  27.     public static IAppBuilder AddSerilog( this IAppBuilder builder, string appName ) {
  28.         return builder.AddSerilog( options => {
  29.             options.Application = appName;
  30.         } );
  31.     }
  32.     /// <summary>
  33.     /// 配置Serilog日志操作
  34.     /// </summary>
  35.     /// <param name="builder">应用生成器</param>
  36.     /// <param name="setupAction">日志配置操作</param>
  37.     public static IAppBuilder AddSerilog( this IAppBuilder builder, Action<LogOptions> setupAction ) {
  38.         builder.CheckNull( nameof( builder ) );
  39.         var options = new LogOptions();
  40.         setupAction?.Invoke( options );
  41.         builder.Host.ConfigureServices( ( context, services ) => {
  42.             services.AddSingleton<ILogFactory, LogFactory>();
  43.             services.AddTransient( typeof( ILog<> ), typeof( Log<> ) );
  44.             services.AddTransient( typeof( ILog ), t => t.GetService<ILogFactory>()?.CreateLog( "default" ) ?? NullLog.Instance );
  45.             var configuration = context.Configuration;
  46.             services.AddLogging( loggingBuilder => {
  47.                 if ( options.IsClearProviders )
  48.                     loggingBuilder.ClearProviders();
  49.                 SerilogLog.Logger = new LoggerConfiguration()
  50.                     .Enrich.WithProperty( "Application", options.Application )
  51.                     .Enrich.FromLogContext()
  52.                     .Enrich.WithLogLevel()
  53.                     .Enrich.WithLogContext()
  54.                     .ReadFrom.Configuration( configuration )
  55.                     .ConfigLogLevel( configuration )
  56.                     .CreateLogger();
  57.                 loggingBuilder.AddSerilog();
  58.             } );
  59.         } );
  60.         return builder;
  61.     }
  62. }
复制代码
AddExceptionless 配置方法

AddExceptionless 配置方法封装了 Serilog 和 Exceptionless 的配置.

  • 配置 ILog 接口服务依赖.
  • 将 Asp.Net Core 日志级别转换为 Exceptionless 日志级别.
  • 设置日志上下文扩展.
  1. /// <summary>
  2. /// Exceptionless日志操作扩展
  3. /// </summary>
  4. public static class AppBuilderExtensions {
  5.     /// <summary>
  6.     /// 配置Exceptionless日志操作
  7.     /// </summary>
  8.     /// <param name="builder">应用生成器</param>
  9.     /// <param name="isClearProviders">是否清除默认设置的日志提供程序</param>
  10.     public static IAppBuilder AddExceptionless( this IAppBuilder builder, bool isClearProviders = false ) {
  11.         return builder.AddExceptionless( null, isClearProviders );
  12.     }
  13.     /// <summary>
  14.     /// 配置Exceptionless日志操作
  15.     /// </summary>
  16.     /// <param name="builder">应用生成器</param>
  17.     /// <param name="appName">应用程序名称</param>
  18.     public static IAppBuilder AddExceptionless( this IAppBuilder builder, string appName ) {
  19.         return builder.AddExceptionless( null, appName );
  20.     }
  21.     /// <summary>
  22.     /// 配置Exceptionless日志操作
  23.     /// </summary>
  24.     /// <param name="builder">应用生成器</param>
  25.     /// <param name="configAction">Exceptionless日志配置操作</param>
  26.     /// <param name="isClearProviders">是否清除默认设置的日志提供程序</param>
  27.     public static IAppBuilder AddExceptionless( this IAppBuilder builder, Action<ExceptionlessConfiguration> configAction, bool isClearProviders = false ) {
  28.         return builder.AddExceptionless( configAction, t => t.IsClearProviders = isClearProviders );
  29.     }
  30.     /// <summary>
  31.     /// 配置Exceptionless日志操作
  32.     /// </summary>
  33.     /// <param name="builder">应用生成器</param>
  34.     /// <param name="configAction">Exceptionless日志配置操作</param>
  35.     /// <param name="appName">应用程序名称</param>
  36.     public static IAppBuilder AddExceptionless( this IAppBuilder builder, Action<ExceptionlessConfiguration> configAction, string appName ) {
  37.         return builder.AddExceptionless( configAction, t => t.Application = appName );
  38.     }
  39.     /// <summary>
  40.     /// 配置Exceptionless日志操作
  41.     /// </summary>
  42.     /// <param name="builder">应用生成器</param>
  43.     /// <param name="configAction">Exceptionless日志配置操作</param>
  44.     /// <param name="setupAction">日志配置</param>
  45.     public static IAppBuilder AddExceptionless( this IAppBuilder builder, Action<ExceptionlessConfiguration> configAction, Action<LogOptions> setupAction ) {
  46.         builder.CheckNull( nameof( builder ) );
  47.         var options = new LogOptions();
  48.         setupAction?.Invoke( options );
  49.         builder.Host.ConfigureServices( ( context, services ) => {
  50.             services.AddSingleton<ILogFactory, LogFactory>();
  51.             services.AddTransient( typeof( ILog<> ), typeof( Log<> ) );
  52.             services.AddTransient( typeof( ILog ), t => t.GetService<ILogFactory>()?.CreateLog( "default" ) ?? NullLog.Instance );
  53.             var configuration = context.Configuration;
  54.             services.AddLogging( loggingBuilder => {
  55.                 if ( options.IsClearProviders )
  56.                     loggingBuilder.ClearProviders();
  57.                 ConfigExceptionless( configAction, configuration );
  58.                 SerilogLog.Logger = new LoggerConfiguration()
  59.                     .Enrich.WithProperty( "Application", options.Application )
  60.                     .Enrich.FromLogContext()
  61.                     .Enrich.WithLogLevel()
  62.                     .Enrich.WithLogContext()
  63.                     .WriteTo.Exceptionless()
  64.                     .ReadFrom.Configuration( configuration )
  65.                     .ConfigLogLevel( configuration )
  66.                     .CreateLogger();
  67.                 loggingBuilder.AddSerilog();
  68.             } );
  69.         } );
  70.         return builder;
  71.     }
  72.     /// <summary>
  73.     /// 配置Exceptionless
  74.     /// </summary>
  75.     private static void ConfigExceptionless( Action<ExceptionlessConfiguration> configAction, IConfiguration configuration ) {
  76.         ExceptionlessClient.Default.Startup();
  77.         if ( configAction != null ) {
  78.             configAction( ExceptionlessClient.Default.Configuration );
  79.             ConfigLogLevel( configuration, ExceptionlessClient.Default.Configuration );
  80.             return;
  81.         }
  82.         ExceptionlessClient.Default.Configuration.ReadFromConfiguration( configuration );
  83.         ConfigLogLevel( configuration, ExceptionlessClient.Default.Configuration );
  84.     }
  85.     /// <summary>
  86.     /// 配置日志级别
  87.     /// </summary>
  88.     private static void ConfigLogLevel( IConfiguration configuration, ExceptionlessConfiguration options ) {
  89.         var section = configuration.GetSection( "Logging:LogLevel" );
  90.         foreach ( var item in section.GetChildren() ) {
  91.             if ( item.Key == "Default" ) {
  92.                 options.Settings.Add( "@@log:*", GetLogLevel( item.Value ) );
  93.                 continue;
  94.             }
  95.             options.Settings.Add( $"@@log:{item.Key}*", GetLogLevel( item.Value ) );
  96.         }
  97.     }
  98.     /// <summary>
  99.     /// 获取日志级别
  100.     /// </summary>
  101.     private static string GetLogLevel( string logLevel ) {
  102.         switch ( logLevel.ToUpperInvariant() ) {
  103.             case "TRACE":
  104.                 return "Trace";
  105.             case "DEBUG":
  106.                 return "Debug";
  107.             case "INFORMATION":
  108.                 return "Info";
  109.             case "ERROR":
  110.                 return "Error";
  111.             case "CRITICAL":
  112.                 return "Fatal";
  113.             case "NONE":
  114.                 return "Off";
  115.             default:
  116.                 return "Warn";
  117.         }
  118.     }
  119. }
复制代码
欢迎转载何镇汐的技术博客微信扫描二维码支持Util
1.jpeg

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册