当前位置: 首页 > news >正文

ASP.NET Core中使用NLog和注解实现日志记录

本文介绍了在ASP.NET Core中使用NLog实现日志记录的方法。主要内容包括:1) 通过NuGet安装NLog并配置nlog.config文件,设置日志格式、存储路径和归档规则;2) 定义LogAttribute注解类,可配置日志级别、是否记录请求参数/响应结果/执行时间等选项;3) 实现LogActionFilter过滤器,在请求处理前后记录相关信息,支持根据注解配置过滤敏感字段。该方案通过AOP方式实现了灵活可配置的日志记录功能,便于系统监控和问题排查。

配置NLog

NuGet 安装 NLog,根目录新建 nlog.config

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"autoReload="true"watchInterval="30"watchTimeout="5000"internalLogLevel="Warn"internalLogFile="${basedir:dir=logs}/nlog-internal.log"throwExceptions="false"throwConfigExceptions="false"><variable name="logDirectory" value="${basedir:dir=logs}" /><variable name="archiveDirectory" value="${basedir:dir=archives}" /><variable name="defaultLayout" value="${longdate:format=yyyy-MM-dd HH\:mm\:ss.fff} | ${level:uppercase=true} | ${logger:shortName=true} | ${message} ${onexception:${newline}EXCEPTION: ${exception:format=ToString,Data:maxInnerExceptionLevel=5} ${newline}STACKTRACE: ${stacktrace:topFrames=10} ${newline}}" /><variable name="consoleLayout" value="[${date:format=yyyy-MM-dd HH\:mm\:ss}] [${level:uppercase=true}] ${logger:shortName=true} | ${message} ${onexception:EXCEPTION: ${exception:format=Message}}" /><targets async="true"><target name="log_file" xsi:type="File"fileName="${logDirectory}/${shortdate}/${level}-${shortdate}.log"layout="${defaultLayout}"createDirs="true"archiveFileName="${archiveDirectory}/${shortdate}/${level}-${shortdate}-{00000}.log"archiveAboveSize="10485760"archiveNumbering="Sequence"maxArchiveFiles="30"concurrentWrites="true"keepFileOpen="false"encoding="UTF-8"writeBom="false"enableFileDelete="true"bufferSize="8192"flushTimeout="5000"></target><target name="colorConsole" xsi:type="ColoredConsole"layout="${consoleLayout}"><highlight-row condition="level == LogLevel.Trace" foregroundColor="DarkGray" /><highlight-row condition="level == LogLevel.Debug" foregroundColor="Gray" /><highlight-row condition="level == LogLevel.Info" foregroundColor="Cyan" /><highlight-row condition="level == LogLevel.Warn" foregroundColor="Yellow" backgroundColor="DarkGray" /><highlight-row condition="level == LogLevel.Error" foregroundColor="White" backgroundColor="Red" /><highlight-row condition="level == LogLevel.Fatal" foregroundColor="White" backgroundColor="DarkRed" /></target></targets><rules><logger name="Microsoft.*" minlevel="Info" maxlevel="Info" final="true" /><logger name="Microsoft.*" minlevel="Warn" writeTo="log_file,colorConsole" final="true" /><logger name="*" minlevel="Trace" maxlevel="Debug" writeTo="log_file" /><logger name="*" minlevel="Info" writeTo="log_file" /><logger name="*" minlevel="Warn" writeTo="colorConsole" /></rules>
</nlog>

定义日志过滤器注解

using System;/// <summary>
/// 日志记录注解
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
public class LogAttribute : Attribute
{/// <summary>/// 是否记录请求参数/// </summary>public bool LogParameters { get; set; } = true;/// <summary>/// 是否记录响应结果/// </summary>public bool LogResult { get; set; } = true;/// <summary>/// 是否记录执行时间/// </summary>public bool LogExecutionTime { get; set; } = true;/// <summary>/// 排除的字段(用于敏感信息过滤)/// </summary>public string[] ExcludeFields { get; set; } = Array.Empty<string>();/// <summary>/// 日志级别/// </summary>public string LogLevel { get; set; } = "Info";
}

过滤器处理日志逻辑

using System.Reflection;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using NLog;/// <summary>
/// 日志过滤器
/// </summary>
public class LogActionFilter : IAsyncActionFilter
{private static readonly Logger Logger = LogManager.GetCurrentClassLogger();public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next){// 获取当前请求的日志配置(方法级别优先于类级别)var logConfig = GetLogConfiguration(context);if (logConfig == null){// 没有日志注解,直接执行后续操作await next();return;}// 记录请求信息var requestLog = new StringBuilder();var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;requestLog.AppendLine($"请求开始: {context.HttpContext.Request.Method} {context.HttpContext.Request.Path}");requestLog.AppendLine($"控制器: {actionDescriptor?.ControllerName}, 方法: {actionDescriptor?.ActionName}");// 记录请求参数(根据配置)if (logConfig.LogParameters && context.ActionArguments.Count > 0){requestLog.AppendLine("请求参数:");foreach (var arg in context.ActionArguments){// 过滤敏感字段var filteredValue = FilterSensitiveData(arg.Value, logConfig.ExcludeFields);requestLog.AppendLine($"{arg.Key}: {JsonSerializer.Serialize(filteredValue)}");}}// 根据配置的日志级别记录LogMessage(logConfig.LogLevel, requestLog.ToString());// 记录开始时间var startTime = DateTime.UtcNow;var resultContext = await next(); // 执行后续操作// 记录响应信息var responseLog = new StringBuilder();responseLog.AppendLine($"请求结束: {context.HttpContext.Request.Method} {context.HttpContext.Request.Path}");// 记录执行时间(根据配置)if (logConfig.LogExecutionTime){var executionTime = DateTime.UtcNow - startTime;responseLog.AppendLine($"执行时间: {executionTime.TotalMilliseconds:F2}ms");}// 记录响应结果(根据配置)if (logConfig.LogResult){if (resultContext.Result is ObjectResult objectResult){var filteredResult = FilterSensitiveData(objectResult.Value, logConfig.ExcludeFields);responseLog.AppendLine($"响应结果: {JsonSerializer.Serialize(filteredResult)}");}else if (resultContext.Result is ContentResult contentResult){responseLog.AppendLine($"响应内容: {contentResult.Content}");}else if (resultContext.Result is EmptyResult){responseLog.AppendLine("响应结果: 空");}}// 记录异常if (resultContext.Exception != null){Logger.Error(resultContext.Exception, $"请求执行异常: {resultContext.Exception.Message}");}else{LogMessage(logConfig.LogLevel, responseLog.ToString());}}/// <summary>/// 获取日志配置(方法 > 类)/// </summary>private LogAttribute GetLogConfiguration(ActionExecutingContext context){var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;if (actionDescriptor == null) return null;// 先检查方法是否有日志注解var methodAttr = actionDescriptor.MethodInfo.GetCustomAttribute<LogAttribute>();if (methodAttr != null)return methodAttr;// 再检查类是否有日志注解return actionDescriptor.ControllerTypeInfo.GetCustomAttribute<LogAttribute>();}/// <summary>/// 过滤敏感数据/// </summary>private object FilterSensitiveData(object data, string[] excludeFields){if (data == null || excludeFields.Length == 0)return data;// 简单实现:将敏感字段替换为***// 实际项目中可根据需要扩展var json = JsonSerializer.Serialize(data);foreach (var field in excludeFields){json = json.Replace($"\"{field}\":\"[^\"]*\"", $"\"{field}\":\"***\"");}return JsonSerializer.Deserialize<object>(json);}/// <summary>/// 根据日志级别记录日志/// </summary>private void LogMessage(string level, string message){switch (level?.ToLower()){case "trace":Logger.Trace(message);break;case "debug":Logger.Debug(message);break;case "warn":Logger.Warn(message);break;case "error":Logger.Error(message);break;case "fatal":Logger.Fatal(message);break;default: // infoLogger.Info(message);break;}}
}

注册过滤器并使用注解

builder.Services.AddControllers(options =>
{// 注册日志过滤器options.Filters.Add<LogActionFilter>();
});
using Microsoft.AspNetCore.Mvc;[ApiController]
[Route("api/[controller]")]
// 类级别日志配置
[Log(LogExecutionTime = true, ExcludeFields = new[] { "Password", "Token" })]
public class UserController : ControllerBase
{// 方法级别日志配置(会覆盖类级别配置)[HttpPost("login")][Log(LogParameters = true, LogResult = true, LogLevel = "Info")]public IActionResult Login([FromBody] LoginRequest request){// 业务逻辑if (request.Username == "admin" && request.Password == "123456"){return Ok(new { Token = "fake-jwt-token", Expires = DateTime.Now.AddHours(1) });}return Unauthorized("用户名或密码错误");}[HttpGet("{id}")][Log(LogParameters = true, LogResult = true, LogExecutionTime = false, LogLevel = "Debug")]public IActionResult GetUser(int id){var user = new { Id = id, Name = "Test User", Email = "test@example.com" };return Ok(user);}// 不使用日志注解,不会记录日志[HttpPost("logout")]public IActionResult Logout(){return Ok();}
}public class LoginRequest
{public string Username { get; set; }public string Password { get; set; }
}
http://www.xdnf.cn/news/1219717.html

相关文章:

  • 某讯视频风控参数逆向分析
  • 计算机存储正数,负数
  • .NET Core部署服务器
  • 搭建 Mock 服务,实现前端自调
  • Rust × WebAssembly 项目脚手架详解
  • 正向运动学(Forward Kinematics,简称FK)和逆向运动学(Inverse Kinematics,简称IK)
  • ABS系统专用磁阻式汽车轮速传感器
  • 【扩散模型专栏】01 扩散模型入门:概念与背景
  • USRP捕获手机/路由器数据传输信号波形(中)
  • 多云场景实战:华为手机 QR 码绑定与 AWS云服务器终端登录全解
  • 【n8n教程笔记——工作流Workflow】文本课程(第二阶段)——1 理解数据结构 (Understanding the data structure)
  • Day15--二叉树--222. 完全二叉树的节点个数,110. 平衡二叉树,257. 二叉树的所有路径,404. 左叶子之和
  • 基于 Amazon Nova Sonic 和 MCP 构建语音交互 Agent
  • 日语学习-日语知识点小记-构建基础-JLPT-N3阶段(12):文法+单词
  • O2OA 平台:助力企业在信创浪潮下实现高效国产化转型
  • Python单例类、元类详解
  • FFmpegHandler 功能解析,C语言程序化设计与C++面向对象设计的核心差异
  • 【科普】在STM32中有哪些定时器?
  • 掩码语言模型(MLM)技术解析:理论基础、演进脉络与应用创新
  • Spring AI 系列之二十八 - Spring AI Alibaba-基于Nacos的prompt模版
  • Java实习面试记录
  • 【go】字符串操作
  • 常用设计模式系列(十七)—命令模式
  • 设计模式:责任链模式 Chain of Responsibility
  • 【力扣】面试经典150题总结01-数组/字符串
  • 前端框架Vue3(二)——Vue3核心语法之OptionsAPI与CompositionAPI与setup
  • 脚手架搭建React项目
  • 面试题及解答:锁
  • 《棒球规则》棒球界外球怎么算·棒球1号位
  • 33.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--单体转微服务--财务服务--记账