news 2026/8/8 7:05:18

.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/8/7 8:24:11

前端设计模式:轻量级实战指南

目录 1.简介 一. 什么是设计模式&#xff1f; 二、前端设计模式的“不一样” 1. 语言特性&#xff1a;弱类型、原型继承&#xff0c;让“类式模式”变“轻量” 2. 场景核心&#xff1a;DOM、异步、组件化&#xff0c;让模式“靶向落地” &#xff08;1&#xff09;DOM操作…

作者头像 李华
网站建设 2026/8/8 4:16:41

26、全功能应用:拼写检查与索引生成

全功能应用:拼写检查与索引生成 在文本处理领域,拼写检查和索引生成是两项重要的任务。下面将详细介绍如何使用相关工具和脚本完成这些任务。 拼写检查脚本 拼写检查脚本通过设置一个 shell 变量 AWKLIB 来指定 spellcheck.awk 脚本的位置。符号 “$*” 会展开为脚本名…

作者头像 李华
网站建设 2026/8/6 17:14:17

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

4.1 AI代码研究方法:快速掌握大型开源项目核心代码库 在现代软件开发中,理解和掌握大型开源项目的代码库是一项关键技能。传统的代码阅读方法往往效率低下且容易迷失在复杂的代码结构中。本节将介绍如何利用AI工具(如Cursor、Claude Code等)来快速、系统地解构和理解大型开…

作者头像 李华
网站建设 2026/8/7 22:50:07

4.1 AI赋能代码研究:快速解构大型开源项目

4.1 AI赋能代码研究:快速解构大型开源项目 在软件开发过程中,我们经常需要理解和学习大型开源项目的代码结构和实现原理。传统的代码阅读方式往往效率低下,难以快速把握项目的整体架构和核心逻辑。本节课将介绍如何利用AI工具(特别是Cursor和Claude Code)来快速解构和理解…

作者头像 李华
网站建设 2026/8/6 12:27:48

魔改YOLO13高阶版改进之结合C3k2与DySnakeConv电信天线设备检测

1. 魔改YOLO13高阶版改进之结合C3k2与DySnakeConv电信天线设备检测 1.1. &#x1f680; 前言 在当今5G和物联网快速发展的时代&#xff0c;电信天线设备的检测与维护变得越来越重要&#xff01;&#x1f50d; 传统的检测方法效率低下且容易出错&#xff0c;而基于深度学习的目…

作者头像 李华