news 2026/5/12 9:44:07

.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/5/9 2:50:00

设计模式:一个实例用全创建型模式

1.概要这里结合多种模式完成需求&#xff0c;为了体现各模式的使用价值&#xff0c;在对比中对某种模式的特点有一个相对形象的认识。还是一坦克大战作为需求原型&#xff0c;因为需求简单&#xff0c;易于理解&#xff0c;不会在需求本身上消耗太多精力&#xff0c;更容易专注…

作者头像 李华
网站建设 2026/5/9 2:00:16

上市公司元宇宙技术专利数据说明(1990—2025)

数据简介CNPaperData元宇宙技术专利是推动元宇宙产业发展的关键创新领域&#xff0c;涵盖了从硬件设备到软件应用的广泛技术&#xff0c;在构建虚拟世界、实现虚实交互以及提升用户体验等方面发挥着重要作用&#xff0c;是元宇宙行业蓬勃发展的核心技术支撑。其中&#xff0c;与…

作者头像 李华
网站建设 2026/5/11 1:20:40

3.3 实战项目升级:为智能数据库查询工具添加多数据库支持

3.3 实战项目升级:为智能数据库查询工具添加多数据库支持 在前几周的学习中,我们已经构建了一个基础的智能数据库查询工具,它能够将自然语言转换为SQL查询并执行。现在,我们将对这个项目进行升级,添加对多种数据库系统的支持,包括MySQL、PostgreSQL、SQLite和MongoDB。这…

作者头像 李华
网站建设 2026/5/9 1:21:18

LobeChat能否对接CRM系统?客户关系管理一体化

LobeChat 与 CRM 系统的深度融合&#xff1a;打造智能化客户关系管理新范式 在企业服务日益追求“以客户为中心”的今天&#xff0c;客户关系管理&#xff08;CRM&#xff09;系统早已不再是简单的联系人数据库。它承载着销售线索、服务记录、交互历史乃至客户情绪的完整画像。…

作者头像 李华
网站建设 2026/5/9 2:08:08

4.1 AI代码研究方法论:快速掌握大型开源项目核心原理

4.1 AI代码研究方法论:快速掌握大型开源项目核心原理 在前面的章节中,我们学习了AI编程工具的使用和项目开发实践。从本章开始,我们将探讨如何利用AI工具快速理解和掌握大型开源项目的代码库。本节课将介绍一套系统性的AI代码研究方法论,帮助开发者高效地解构和理解复杂的…

作者头像 李华
网站建设 2026/5/12 4:40:26

4.3 AI驱动的可视化生成:将代码和描述转换为图表

4.3 AI驱动的可视化生成:将代码和描述转换为图表 在技术文档和系统设计中,可视化图表是传达复杂信息的有力工具。传统的图表制作过程往往耗时且需要专业技能。本节将介绍如何利用AI工具将代码和自然语言描述自动转换为各种类型的图表,包括流程图、架构图、时序图等。 可视…

作者头像 李华