NLog在.NET Core Console Apps中的简单应用

本文介绍了NLog日志框架的基础知识,包括如何在.NET Core应用程序中安装和配置NLog,以及如何通过示例代码记录日志信息。文章还详细展示了配置文件的设置方法,并演示了如何将NLog与ASP.NET Core集成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是NLog?

NLog is a free logging platform for .NET with rich log routing and management capabilities. It makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity.

It can process diagnostic messages emitted from any .NET language, augment them with contextual information, format them according to your preference and send them to one or more targets such as file or database.

NLog在GitHub的官网:https://github.com/NLog

NLog for .NET Core:https://github.com/NLog/NLog.Extensions.Logging

创建一个.NET Core Console 应用

使用CLI(Command Line Interface)创建一个example程序:

  • dotnet new
  • dotnet restore
  • dotnet run

这些命令行的具体意思这里就不再赘述。

更改project.json的配置

主要是新增了NLog相关的配置:

  • NLog的包引用;
  • 程序发布时包含NLog的配置文件。

新增NLog的配置文件

在程序的根目录下新增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"
      internalLogLevel="Warn"
      internalLogFile="internal-nlog.txt">

  <!-- define various log targets -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log"
                 layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="File" name="ownFile-web" fileName="nlog-own-${shortdate}.log"
             layout="${longdate}|${threadid}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}" />

    <target xsi:type="Null" name="blackhole" />
  </targets>

  <rules>
    <!--Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />
    <logger name="*" minlevel="Info" writeTo="ownFile-web" />
  </rules>
</nlog>

在Startup类中注册NLog的MiddleWare

 1 using Microsoft.AspNetCore.Builder;
 2 using Microsoft.AspNetCore.Hosting;
 3 using Microsoft.AspNetCore.Http;
 4 using Microsoft.Extensions.Logging;
 5 using NLog.Extensions.Logging;
 6 
 7 namespace ConsoleApplication
 8 {
 9     public class Startup
10     {
11         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
12         {
13             // Add NLog to ASP.NET Core
14             loggerFactory.AddNLog();
15             
16             // configure nlog.config in your project root
17             env.ConfigureNLog("nlog.config");
18 
19             app.Run(context =>
20             {
21                 return context.Response.WriteAsync("Hello World!!");
22             });
23         }
24     }
25 }

在入口类中记录日志

 1 using System.Threading;
 2 using Microsoft.AspNetCore.Hosting;
 3 using NLog;
 4 
 5 namespace ConsoleApplication
 6 {
 7     public class Program
 8     {
 9         private static Logger logger = LogManager.GetCurrentClassLogger();
10         public static void Main(string[] args)
11         {
12             logger.Info("Server is running...");
13             logger.Info(string.Format("Current Thead Id:{0}", Thread.CurrentThread.ManagedThreadId));
14             var host = new WebHostBuilder().UseKestrel().UseStartup<Startup>().Build();
15             host.Run();
16         }
17     }
18 }

运行程序后会在主目录下生成2个日志文件:

 

转载于:https://www.cnblogs.com/frankyou/p/5694306.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值