
NetCore3.1 日志组件 Nlog的使用
发布日期:2021-05-09 01:18:04
浏览次数:20
分类:原创文章
本文共 4543 字,大约阅读时间需要 15 分钟。
十年河东,十年河西,莫欺少年穷
学无止境,精益求精
本篇博客系转载至:
1.添加Nuget程序包
NLog
和
NLog.Web.AspNetCore
2.创建名称为: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" internalLogLevel="Info"> <!-- 启用.net core的核心布局渲染器 --> <extensions> <add assembly="NLog.Web.AspNetCore" /> </extensions> <!-- 写入日志的目标配置 --> <targets> <!-- 调试 --> <target xsi:type="File" name="debug" fileName="logs/debug-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" /> <!-- 警告 --> <target xsi:type="File" name="warn" fileName="logs/warn-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" /> <!-- 错误 --> <target xsi:type="File" name="error" fileName="logs/error-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" /> </targets> <!-- 映射规则 --> <rules> <!-- 调试 --> <logger name="*" minlevel="Trace" maxlevel="Debug" writeTo="debug" /> <!--跳过不重要的微软日志--> <logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- 警告 --> <logger name="*" minlevel="Info" maxlevel="Warn" writeTo="warn" /> <!-- 错误 --> <logger name="*" minlevel="Error" maxlevel="Fatal" writeTo="error" /> </rules></nlog>
3.Program.cs 添加Nlog
public class Program { public static void Main(string[] args) { //这里添加Nlog var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { //测试Nlog日志输出 logger.Debug("init main"); CreateHostBuilder(args).Build().Run(); } catch (Exception exception) { logger.Error(exception, "Stopped program because of exception"); throw; } finally { NLog.LogManager.Shutdown(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }).UseNLog();//添加你的日志组件 }
4.通过构造方法注入实现写日志功能
using FranchiseeInterface.Franchisee;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.Logging;using Newtonsoft.Json;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace FranchiseeApi.Helper.Middlewares{ public class ExceptionMiddlewares { private readonly RequestDelegate next; private IHostingEnvironment environment; //Nlog构造方法注入 private readonly ILogger<ExceptionMiddlewares> _logger; public ExceptionMiddlewares(RequestDelegate next, IHostingEnvironment environment, ILogger<ExceptionMiddlewares> logger) { _logger = logger; this.next = next; this.environment = environment; } public async Task Invoke(HttpContext context) { try { await next.Invoke(context); var features = context.Features; } catch (Exception e) { await HandleException(context, e); } } private async Task HandleException(HttpContext context, Exception e) { context.Response.StatusCode = 500; context.Response.ContentType = "text/json;charset=utf-8;"; string error = ""; if (environment.IsDevelopment()) { var json = new { message = e.Message }; //// log.Error(json); //_logger.LogDebug("这里是homeController构造方法"); //_logger.Log(LogLevel.Information,"测试"); _logger.LogError(JsonConvert.SerializeObject(json)); error = JsonConvert.SerializeObject(json); } else error = "抱歉,出错了"; await context.Response.WriteAsync(error); } }}
至此,就结束了。
发表评论
最新留言
表示我来过!
[***.240.166.169]2025年04月17日 12时24分24秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Linux ipv6设置
2025-04-06
Linux ip命令:网络的瑞士军刀
2025-04-06
Linux iSCSI 磁盘共享实战
2025-04-06
linux jar包启动脚本
2025-04-06
Linux java环境出现not a valid identifier问题解决方法
2025-04-06
linux java网站打不开 tomcat启动不了
2025-04-06
Linux kdump Crash故障定位分析详解
2025-04-06
Linux Kernel 6.13 正式发布!新增很多功能和亮点
2025-04-06
Linux Kernel 内核优化方案实战
2025-04-06
Linux kernel 内核概述
2025-04-06
Linux Kernel 内核模块详解
2025-04-06
Linux Kernel 内核管理实战
2025-04-06
linux kernel系列四:嵌入式系统中的文件系统以及MTD
2025-04-06
linux known_hosts 的作用
2025-04-06
Linux logrotate 命令教程日志分割
2025-04-06
Linux losetup命令
2025-04-06
linux ls命令详解
2025-04-06
Linux LVM 逻辑卷管理
2025-04-06
Linux LVM学习总结——创建卷组VG
2025-04-06