.NET Core使用Nlog记录日志
1.引入Nuget包
Nlog.Web.AspNetCore
2.添加nlog配置文件
- <?xml version="1.0" encoding="utf-8"?>
- <nlogxmlns="http://www.nlog-project.org/schemas/NLog.xsd"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- autoReload="true"
- internalLogLevel="Warn"
- internalLogFile="internal-nlog.txt">
- <!--define various log targets-->
- <targets>
- <!--write logs to file-->
- <targetxsi:type="File"name="allfile"fileName="nlog-all-${shortdate}.log"
- layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}"/>
- <targetxsi:type="File"name="ownFile-web"fileName="nlog-my-${shortdate}.log"
- layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}"/>
- <targetxsi:type="Null"name="blackhole"/>
- </targets>
- <rules>
- <!--All logs, including from Microsoft-->
- <loggername="*"minlevel="Trace"writeTo="allfile"/>
- <!--Skip Microsoft logs and so log only own logs-->
- <loggername="Microsoft.*"minlevel="Trace"writeTo="blackhole"final="true"/>
- <loggername="*"minlevel="Trace"writeTo="ownFile-web"/>
- </rules>
- </nlog>
3.建立日志公共类方法Logger.cs
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace System
- {
- public class Logger
- {
- //写入操作日志
- const string mainLogger = "logger";
- /// <summary>
- /// 输出操作日志到NLog
- /// </summary>
- public static void Info(string msg)
- {
- var logger = NLog.LogManager.GetLogger(mainLogger);
- logger.Info(msg);
- }
- public static void Error(string msg)
- {
- var logger = NLog.LogManager.GetLogger(mainLogger);
- logger.Error(msg);
- }
- public static void Debug(string msg)
- {
- var logger = NLog.LogManager.GetLogger(mainLogger);
- logger.Debug(msg);
- }
- public static void Exception(Exception ex)
- {
- var logger = NLog.LogManager.GetLogger(mainLogger);
- logger.Error(ex);
- }
- }
- }
============ 欢迎各位老板打赏~ ===========
与本文相关的文章
- · .NET5面试汇总
- · .NET Core微服务之基于Ocelot实现API网关服务
- · 利用阿里云快速安装最新版docker和加速docker pull
- · The instance of entity type ‘Customer’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked.
- · .NET8实时更新nginx ip地址归属地
- · 解决.NET Blazor子组件不刷新问题
- · .NET8如何在普通类库中引用 Microsoft.AspNetCore
- · .NET8 Mysql SSL error
- · ASP.NET Core MVC的Razor视图渲染中文乱码的问题
- · .NETCORE 依赖注入服务生命周期
- · asp.net zero改mysql
- · .Net连接Mysql数据库的Convert Zero Datetime日期问题