news 2026/9/7 10:47:28

.NET 6 API使用Serilog APM

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
.NET 6 API使用Serilog APM

本文介绍如何在.NET 6 API中使用Serilog的APM。

1. 引用Serilog相关的packages

<PackageReferenceInclude="Elastic.Apm.SerilogEnricher"Version="8.11.1"/><PackageReferenceInclude="Serilog.AspNetCore"Version="8.0.2"/><PackageReferenceInclude="Serilog.Enrichers.Environment"Version="3.0.1"/><PackageReferenceInclude="Serilog.Exceptions"Version="8.4.0"/><PackageReferenceInclude="Serilog.Formatting.Elasticsearch"Version="10.0.0"/><PackageReferenceInclude="Serilog.Settings.Configuration"Version="8.0.2"/><PackageReferenceInclude="Serilog.Sinks.Elasticsearch"Version="10.0.0"/>

2. appsettings.json添加配置文件

"SeriLog":{"Using":["Serilog.Sinks.Console","Serilog.Sinks.File","Serilog.Sinks.Elasticsearch"],"MinimumLevel":{"Default":"Information"},"Enrich":["FromLogContext","WithMachineName","WithThreadId","WithElasticApmCorrelationInfo"]},"SerilogSupplementer":{"WriteToFile":true,"LogFilePath":"c:/temp/logs/mes-api/mes-api-.json","FileRestrictToMinimumLevel":"Information","FileSizeLimitBytes":10485760,//10 MB"RetainedFileTimeLimit":"10.00:00",// Retain files for a maximum of 10 days 0 Hrs 0 Mins"rollOnFileSizeLimit":true,"EnrichFromLogContext":true,"MinimumLevelControlledBy":null,"EnrichProperties":{"Application":"mes-api","Environment":"Development"},"MinimumLevelOverrides":{"Microsoft.NetCore":"Warning","Elastic.Apm":"Warning"},"EnrichWithExceptionDetails":true,"AddElasticApmCorrelationInfo":true,"WriteToConsole":true,"ConsoleFormat":"{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] [{SourceContext}] [{EventId}] {Message}{NewLine}{Exception}"},"ElasticApm":{"ServerUrls":"http://localhost:8200",// URL of your APM server"ServiceName":"mes-api","Environment":"Development","CentralConfig":false,"LogLevel":"Error"},

3. 注册

3.1 创建SerilogSupplementerConfiguration.cs

usingSerilog.Core;usingSerilog.Events;namespaceMES.API.Logging;publicclassSerilogSupplementerConfiguration{publicboolWriteToFile{get;set;}publicstringLogFilePath{get;set;}=string.Empty;publicLogEventLevelFileRestrictedToMinimumLevel{get;set;}=LogEventLevel.Debug;publicboolEnrichFromLogContext{get;set;}=true;publicLoggingLevelSwitch?MinimumLevelControlledBy{get;set;}publicDictionary<string,object>EnrichProperties{get;set;}=new();publicDictionary<string,LogEventLevel>MinimumLevelOverrides{get;set;}=new();publicboolEnrichWithExceptionDetails{get;set;}=true;publicboolAddElasticApmCorrelationInfo{get;set;}publicboolWriteToConsole{get;set;}publicstringConsoleFormat{get;set;}=string.Empty;publicstringRetainedFileTimeLimit{get;set;}="10.00:00";//Default to 10 dayspubliclongFileSizeLimitBytes{get;set;}=10485760;//Default to 10 MBpublicboolRollOnFileSizeLimit{get;set;}}

3.2 注册

usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;usingAlterDomus.a360.Core.Logging;usingSerilog;usingSerilog.Exceptions;usingElastic.Apm.SerilogEnricher;usingSerilog.Formatting.Elasticsearch;usingSerilog.Exceptions.Core;namespaceMES.API.Extensions;publicstaticclassMESExtensions{/// <summary>/// Add Serilog ILogger using configuration. SerilogSupplementerConfiguration will be read from configuration if exists./// </summary>/// <param name="services"></param>/// <param name="configuration"></param>/// <param name="logArgs"></param>publicstaticIServiceCollectionAddSerilog(thisIServiceCollectionservices,IConfigurationconfiguration){varserilogConfig=newSerilog.LoggerConfiguration().ReadFrom.Configuration(configuration);varserilogSupplementer=configuration.GetSection("SerilogSupplementer").Get<SerilogSupplementerConfiguration>()??new();varretainedFileTimeLimit=TimeSpan.Parse(serilogSupplementer.RetainedFileTimeLimit);varfileSizeLimitBytes=serilogSupplementer.FileSizeLimitBytes;varrollOnFileSizeLimit=serilogSupplementer.RollOnFileSizeLimit;if(serilogSupplementer!=null){if(serilogSupplementer.MinimumLevelControlledBy!=null){serilogConfig.MinimumLevel.ControlledBy(serilogSupplementer.MinimumLevelControlledBy);}foreach(varkvpinserilogSupplementer.MinimumLevelOverrides){serilogConfig.MinimumLevel.Override(kvp.Key,kvp.Value);}if(serilogSupplementer.EnrichFromLogContext){serilogConfig.Enrich.FromLogContext();}if(serilogSupplementer.AddElasticApmCorrelationInfo){serilogConfig.Enrich.WithElasticApmCorrelationInfo();}if(serilogSupplementer.WriteToConsole||!string.IsNullOrEmpty(serilogSupplementer.ConsoleFormat)){if(string.IsNullOrEmpty(serilogSupplementer.ConsoleFormat)){serilogConfig.WriteTo.Console();}else{serilogConfig.WriteTo.Console(outputTemplate:serilogSupplementer.ConsoleFormat);}}if(serilogSupplementer.EnrichWithExceptionDetails){serilogConfig.Enrich.WithExceptionDetails(newDestructuringOptionsBuilder().WithDefaultDestructurers());}if(serilogSupplementer.WriteToFile){serilogConfig.WriteTo.File(newElasticsearchJsonFormatter(renderMessage:true,renderMessageTemplate:false),path:serilogSupplementer.LogFilePath,restrictedToMinimumLevel:serilogSupplementer.FileRestrictedToMinimumLevel,rollingInterval:RollingInterval.Day,fileSizeLimitBytes:fileSizeLimitBytes,retainedFileTimeLimit:retainedFileTimeLimit,rollOnFileSizeLimit:rollOnFileSizeLimit,shared:true);}foreach(varkvpinserilogSupplementer.EnrichProperties){serilogConfig.Enrich.WithProperty(kvp.Key,kvp.Value);}if(!serilogSupplementer.EnrichProperties.ContainsKey("UserName")){serilogConfig.Enrich.WithProperty("UserName",Environment.UserName);}}ILoggerlogger=serilogConfig.CreateLogger();services.AddSingleton<Serilog.ILogger>(logger);returnservices;}}

3.3 在program.cs使用

builder.Services.AddSerilog(builder.Configuration);builder.Host.UseSerilog();builder.Services.AddAllElasticApm();
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/7 17:44:19

UniHacker终极指南:免费解锁Unity完整开发环境的简单方法

还在为Unity软件的高昂授权费用而烦恼吗&#xff1f;想要零成本体验完整功能的Unity开发环境吗&#xff1f;UniHacker就是你一直在寻找的完美解决方案&#xff01;这款跨平台开源工具专为Unity开发者设计&#xff0c;帮助你在Windows、MacOS和Linux系统上轻松绕过授权限制&…

作者头像 李华
网站建设 2026/9/7 2:23:55

软考-系统集成项目管理工程师案例简答题

一、项目管理概论 1&#xff0e;项目管理原则 &#xff08;1&#xff09;勤勉、尊重和关心他人&#xff1b; &#xff08;2&#xff09;营造协作的项目团队环境&#xff1b; &#xff08;3&#xff09;促进干系人有效参与&#xff1b; &#xff08;4&#xff09;聚焦于价值&…

作者头像 李华
网站建设 2026/9/7 2:34:03

4.2 技术文档自动生成:从代码到专业文档的转化

4.2 技术文档自动生成:从代码到专业文档的转化 在软件开发过程中,技术文档的编写往往是一项耗时且容易被忽视的工作。然而,高质量的技术文档对于项目的维护、团队协作和知识传承至关重要。本节课将介绍如何利用AI工具(特别是Cursor和Claude Code)自动生成专业级技术文档,…

作者头像 李华
网站建设 2026/9/7 2:33:43

FMEA在软件可靠性测试中的实践与应用

1. FMEA方法论概述与软件测试适配性 失效模式与影响分析&#xff08;Failure Mode and Effects Analysis&#xff0c;FMEA&#xff09;作为系统化的风险管理方法&#xff0c;已在制造业领域成熟应用数十年。随着软件系统复杂度的指数级增长&#xff0c;该方法在软件可靠性测试…

作者头像 李华
网站建设 2026/9/7 1:10:44

Playwright MCP在UI自动化测试中的定位与思考

如果你和我的团队一样&#xff0c;长期受困于维护一个庞大而脆弱的UI自动化测试脚本库&#xff0c;那么对下面这个场景一定不会陌生&#xff1a;前端的一个轻微重构——也许只是改了一个CSS类名或调整了组件结构——就可能导致精心编写的测试脚本大面积报红&#xff0c;修复工作…

作者头像 李华