经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
零基础写框架(3): Serilog.NET 中的日志使用技巧
来源:cnblogs  作者:痴者工良  时间:2024/6/19 15:17:44  对本文有异议

.NET 中的日志使用技巧

Serilog

Serilog 是 .NET 社区中使用最广泛的日志框架,所以笔者使用一个小节单独讲解使用方法。

示例项目在 Demo2.Console 中。

创建一个控制台程序,引入两个包:

  1. Serilog.Sinks.Console
  2. Serilog.Sinks.File

除此之外,还有 Serilog.Sinks.ElasticsearchSerilog.Sinks.RabbitMQ 等。Serilog 提供了用于将日志事件以各种格式写入存储的接收器。下面列出的许多接收器都是由更广泛的 Serilog 社区开发和支持的;https://github.com/serilog/serilog/wiki/Provided-Sinks

可以直接使用代码配置 Serilog:

  1. private static Serilog.ILogger GetLogger()
  2. {
  3. const string LogTemplate = "{SourceContext} {Scope} {Timestamp:HH:mm} [{Level}] {Message:lj} {Properties:j} {NewLine}{Exception}";
  4. var logger = new LoggerConfiguration()
  5. .Enrich.WithMachineName()
  6. .Enrich.WithThreadId()
  7. .Enrich.FromLogContext()
  8. #if DEBUG
  9. .MinimumLevel.Debug()
  10. #else
  11. .MinimumLevel.Information()
  12. #endif
  13. .WriteTo.Console(outputTemplate: LogTemplate)
  14. .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day, outputTemplate: LogTemplate)
  15. .CreateLogger();
  16. return logger;
  17. }

如果想从配置文件中加载,添加 Serilog.Settings.Configuration:

  1. private static Serilog.ILogger GetJsonLogger()
  2. {
  3. IConfiguration configuration = new ConfigurationBuilder()
  4. .SetBasePath(AppContext.BaseDirectory)
  5. .AddJsonFile(path: "serilog.json", optional: true, reloadOnChange: true)
  6. .Build();
  7. if (configuration == null)
  8. {
  9. throw new ArgumentNullException($"未能找到 serilog.json 日志配置文件");
  10. }
  11. var logger = new LoggerConfiguration()
  12. .ReadFrom.Configuration(configuration)
  13. .CreateLogger();
  14. return logger;
  15. }

serilog.json 配置文件示例:

  1. {
  2. "Serilog": {
  3. "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
  4. "MinimumLevel": {
  5. "Default": "Debug"
  6. },
  7. "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
  8. "WriteTo": [
  9. {
  10. "Name": "Console",
  11. "Args": {
  12. "outputTemplate": "{SourceContext} {Scope} {Timestamp:HH:mm} [{Level}] {Message:lj} {Properties:j} {NewLine}{Exception}"
  13. }
  14. },
  15. {
  16. "Name": "File",
  17. "Args": {
  18. "path": "logs/log-.txt",
  19. "rollingInterval": "Day",
  20. "outputTemplate": "{SourceContext} {Scope} {Timestamp:HH:mm} [{Level}] {Message:lj} {Properties:j} {NewLine}{Exception}"
  21. }
  22. }
  23. ]
  24. }
  25. }

依赖注入 Serilog。

引入 Serilog.Extensions.Logging 包。

  1. private static Microsoft.Extensions.Logging.ILogger InjectLogger()
  2. {
  3. var logger = GetJsonLogger();
  4. var ioc = new ServiceCollection();
  5. ioc.AddLogging(builder => builder.AddSerilog(logger: logger, dispose: true));
  6. var loggerProvider = ioc.BuildServiceProvider().GetRequiredService<ILoggerProvider>();
  7. return loggerProvider.CreateLogger("Program");
  8. }

最后,使用不同方式配置 Serilog 日志,然后启动程序打印日志。

  1. static void Main()
  2. {
  3. var log1 = GetLogger();
  4. log1.Debug("溪源More、痴者工良");
  5. var log2 = GetJsonLogger();
  6. log2.Debug("溪源More、痴者工良");
  7. var log3 = InjectLogger();
  8. log3.LogDebug("溪源More、痴者工良");
  9. }
  1. 20:50 [Debug] 溪源More、痴者工良 {"MachineName": "WIN-KQDULADM5LA", "ThreadId": 1}
  2. 20:50 [Debug] 溪源More、痴者工良 {"MachineName": "WIN-KQDULADM5LA", "ThreadId": 1}
  3. 20:50 [Debug] 溪源More、痴者工良 {"MachineName": "WIN-KQDULADM5LA", "ThreadId": 1}

在 ASP.NET Core 中使用日志

示例项目在 Demo2.Api 中。

新建一个 ASP.NET Core API 新项目,引入 Serilog.AspNetCore 包。

在 Program 中添加代码注入 Serilog 。

  1. var builder = WebApplication.CreateBuilder(args);
  2. Log.Logger = new LoggerConfiguration()
  3. .ReadFrom.Configuration(builder.Configuration)
  4. .CreateLogger();
  5. builder.Host.UseSerilog(Log.Logger);
  6. //builder.Host.UseSerilog();

将前面示例中的 serilog.json 文件内容复制到 appsettings.json 中。

启动程序后,尝试访问 API 接口,会打印示例如下的日志:

  1. Microsoft.AspNetCore.Hosting.Diagnostics 20:32 [Information] Request finished HTTP/1.1 GET http://localhost:5148/WeatherForecast - - - 200 - application/json;+charset=utf-8 1029.4319ms {"ElapsedMilliseconds": 1029.4319, "StatusCode": 200, "ContentType": "application/json; charset=utf-8", "ContentLength": null, "Protocol": "HTTP/1.1", "Method": "GET", "Scheme": "http", "Host": "localhost:5148", "PathBase": "", "Path": "/WeatherForecast", "QueryString": "", "EventId": {"Id": 2}, "RequestId": "0HMOONQO5ONKU:00000003", "RequestPath": "/WeatherForecast", "ConnectionId": "0HMOONQO5ONKU"}

如果需要为请求上下文添加一些属性信息,可以添加一个中间件,示例如下:

  1. app.UseSerilogRequestLogging(options =>
  2. {
  3. options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
  4. {
  5. diagnosticContext.Set("TraceId", httpContext.TraceIdentifier);
  6. };
  7. });
  1. HTTP GET /WeatherForecast responded 200 in 181.9992 ms {"TraceId": "0HMSD1OUG2DHG:00000003" ... ...

对请求上下文添加属性信息,比如当前请求的用户信息,在本次请求作用域中使用日志打印信息时,日志会包含这些上下文信息,这对于分析日志还有帮助,可以很容易分析日志中那些条目是同一个上下文。在微服务场景下,会使用 ElasticSearch 等日志存储引擎查询分析日志,如果在日志中添加了相关的上下文属性,那么在分析日志时可以通过对应的属性查询出来,分析日志时可以帮助排除故障。

如果需要打印 http 的请求和响应日志,我们可以使用 ASP.NET Core 自带的 HttpLoggingMiddleware 中间件。

首先注入请求日志拦截服务。

  1. builder.Services.AddHttpLogging(logging =>
  2. {
  3. logging.LoggingFields = HttpLoggingFields.All;
  4. // 避免打印大量的请求和响应内容,只打印 4kb
  5. logging.RequestBodyLogLimit = 4096;
  6. logging.ResponseBodyLogLimit = 4096;
  7. });

通过组合 HttpLoggingFields 枚举,可以配置中间件打印 Request、Query、HttpMethod、Header、Response 等信息。

可以将HttpLogging 中间件放在 Swagger、Static 之后,这样的话可以避免打印哪些用处不大的请求,只保留 API 请求相关的日志。

  1. app.UseHttpLogging();

HttpLoggingMiddleware 中的日志模式是以 Information 级别打印的,在项目上线之后,如果每个请求都被打印信息的话,会降低系统性能,因此我们可以在配置文件中覆盖配置,避免打印普通的日志。

  1. "Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information"

上下文属性和作用域

示例项目在 Demo2.ScopeLog 中。

日志范围注意事项
Microsoft.Extensions.Logging.Abstractions 提供 BeginScopeAPI,可用于添加任意属性以记录特定代码区域内的事件。

解释其作用

API 有两种形式:

  1. IDisposable BeginScope<TState>(TState state)
  2. IDisposable BeginScope(this ILogger logger, string messageFormat, params object[] args)

使用如下的模板:

  1. {SourceContext} {Timestamp:HH:mm} [{Level}] (ThreadId:{ThreadId}) {Message}{NewLine}{Exception} {Scope}

使用示例:

  1. static void Main()
  2. {
  3. var logger = GetLogger();
  4. using (logger.BeginScope("Checking mail"))
  5. {
  6. // Scope is "Checking mail"
  7. logger.LogInformation("Opening SMTP connection");
  8. using (logger.BeginScope("Downloading messages"))
  9. {
  10. // Scope is "Checking mail" -> "Downloading messages"
  11. logger.LogError("Connection interrupted");
  12. }
  13. }
  14. }

image-20231220212411976

而在 Serilog 中,除了支持上述接口外,还通过 LogContext 提供了在日志中注入上下文属性的方法。其作用是添加属性之后,使得在其作用域之内打印日志时,日志会携带这些上下文属性信息。

  1. using (LogContext.PushProperty("Test", 1))
  2. {
  3. // Process request; all logged events will carry `RequestId`
  4. Log.Information("{Test} Adding {Item} to cart {CartId}", 1,1);
  5. }

嵌套复杂一些:

  1. using (LogContext.PushProperty("A", 1))
  2. {
  3. log.Information("Carries property A = 1");
  4. using (LogContext.PushProperty("A", 2))
  5. using (LogContext.PushProperty("B", 1))
  6. {
  7. log.Information("Carries A = 2 and B = 1");
  8. }
  9. log.Information("Carries property A = 1, again");
  10. }

当需要设置大量属性时,下面的方式会比较麻烦;

  1. using (LogContext.PushProperty("Test1", 1))
  2. using (LogContext.PushProperty("Test2", 2))
  3. {
  4. }

例如在 ASP.NET Core 中间件中,我们可以批量添加:

  1. public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  2. {
  3. var enrichers = new List<ILogEventEnricher>();
  4. if (!string.IsNullOrEmpty(correlationId))
  5. {
  6. enrichers.Add(new PropertyEnricher(_options.EnricherPropertyNames.CorrelationId, correlationId));
  7. }
  8. using (LogContext.Push(enrichers.ToArray()))
  9. {
  10. await next(context);
  11. }
  12. }

在业务系统中,可以通过在中间件获取 Token 中的用户信息,然后注入到日志上下文中,这样打印出来的日志,会携带用户信息。

非侵入式日志

非侵入式的日志有多种方法,比如 ASP.NET Core 中间件管道,或者使用 AOP 框架。

这里可以使用笔者开源的 CZGL.AOP 框架,Nuget 中可以搜索到。

czgl.aop

示例项目在 Demo2.AopLog 中。

有一个类型,我们需要在执行 SayHello 之前和之后打印日志,将参数和返回值记录下来。

  1. public class Hello
  2. {
  3. public virtual string SayHello(string content)
  4. {
  5. var str = $"Hello,{content}";
  6. return str;
  7. }
  8. }

编写统一的切入代码,这些代码将在函数被调用时执行。

Before 会在被代理的方法执行前或被代理的属性调用时生效,你可以通过 AspectContext 上下文,获取、修改传递的参数。

After 在方法执行后或属性调用时生效,你可以通过上下文获取、修改返回值。

  1. public class LogAttribute : ActionAttribute
  2. {
  3. public override void Before(AspectContext context)
  4. {
  5. Console.WriteLine($"{context.MethodInfo.Name} 函数被执行前");
  6. foreach (var item in context.MethodValues)
  7. Console.WriteLine(item.ToString());
  8. }
  9. public override object After(AspectContext context)
  10. {
  11. Console.WriteLine($"{context.MethodInfo.Name} 函数被执行后");
  12. Console.WriteLine(context.MethodResult.ToString());
  13. return context.MethodResult;
  14. }
  15. }

改造 Hello 类,代码如下:

  1. [Interceptor]
  2. public class Hello
  3. {
  4. [Log]
  5. public virtual string SayHello(string content)
  6. {
  7. var str = $"Hello,{content}";
  8. return str;
  9. }
  10. }

然后创建代理类型:

  1. static void Main(string[] args)
  2. {
  3. Hello hello = AopInterceptor.CreateProxyOfClass<Hello>();
  4. hello.SayHello("any one");
  5. Console.Read();
  6. }

启动程序,会输出:

  1. SayHello 函数被执行前
  2. any one
  3. SayHello 函数被执行后
  4. Hello,any one

你完全不需要担心 AOP 框架会给你的程序带来性能问题,因为 CZGL.AOP 框架采用 EMIT 编写,并且自带缓存,当一个类型被代理过,之后无需重复生成。

CZGL.AOP 可以通过 .NET Core 自带的依赖注入框架和 Autofac 结合使用,自动代理 CI 容器中的服务。这样不需要 AopInterceptor.CreateProxyOfClass 手动调用代理接口。

CZGL.AOP 代码是开源的,可以参考笔者另一篇博文:

https://www.cnblogs.com/whuanle/p/13160139.html

原文链接:https://www.cnblogs.com/whuanle/p/18253597

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号