news 2026/2/25 3:55:48

.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/2/22 12:20:59

揭秘Maxun智能数据筛选:告别冗余信息,精准捕获目标内容

在信息爆炸的时代&#xff0c;网页数据提取常常面临"大海捞针"的困境——抓取结果中混杂着大量无关信息&#xff0c;真正有价值的内容反而被淹没其中。Maxun作为开源无代码网页数据提取平台&#xff0c;通过创新的元数据过滤技术&#xff0c;让数据筛选变得像使用智能…

作者头像 李华
网站建设 2026/2/20 21:41:40

企业凭证安全终极指南:15分钟构建TruffleHog自动化防护体系

企业凭证安全终极指南&#xff1a;15分钟构建TruffleHog自动化防护体系 【免费下载链接】trufflehog Find and verify credentials 项目地址: https://gitcode.com/GitHub_Trending/tr/trufflehog 在数字化转型浪潮中&#xff0c;企业凭证安全已成为保障业务连续性的关键…

作者头像 李华
网站建设 2026/2/17 22:38:52

LobeChat角色预设功能实测:快速切换AI身份的便捷之道

LobeChat角色预设功能实测&#xff1a;快速切换AI身份的便捷之道 在如今这个大模型遍地开花的时代&#xff0c;几乎每个团队都在尝试搭建自己的AI对话系统。但很快就会遇到一个现实问题&#xff1a;同一个AI&#xff0c;怎么能既当严谨的数据分析师&#xff0c;又做幽默风趣的朋…

作者头像 李华
网站建设 2026/2/20 18:18:36

LobeChat能否支持HTTPS加密访问?SSL证书配置教程

LobeChat 能否支持 HTTPS 加密访问&#xff1f;SSL 证书配置实战指南 在 AI 应用加速落地的今天&#xff0c;越来越多开发者选择将 LobeChat 部署为私有化的智能对话门户。这款基于 Next.js 的开源聊天界面以优雅的设计、灵活的插件系统和对多模型的良好兼容性&#xff0c;成为…

作者头像 李华
网站建设 2026/2/22 18:15:41

深度学习优化策略:从理论到实践的完整指南

深度学习优化策略&#xff1a;从理论到实践的完整指南 【免费下载链接】nndl.github.io 《神经网络与深度学习》 邱锡鹏著 Neural Network and Deep Learning 项目地址: https://gitcode.com/GitHub_Trending/nn/nndl.github.io 在神经网络训练过程中&#xff0c;你是否…

作者头像 李华