NLog如何打印日志(.Net5)
一、创建项目
首先创建.Net5 "ASP.NET Core Web应用”的项目NLogTest5;
二、添加引用
在依赖项上右击,
选择 “管理NuGet程序包(N)”
在浏览下,输入“NLog.Web.AspNetCore”,右边选择版本“1.14.0”,点击“安装”;
安装完成后显示如下(有NLog.Web.AspNetCore(4.14.0)):
三、创建配置文件
接着在项目上右击,选择“添加”,点击“新建项”
之后,找到“web配置文件”,名称输入“nlog.config”,点击“添加”;
如此“nlog.config”文件创建好了,
之后双击此文件,然后把下面的内容复制粘贴进去
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?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" > <variable name= "logDirectory" value= "${basedir}/logs" /> <!--fileName= "${D:}\testLog\test_logs_${shortdate}.log" 绝对路径 --> <targets> <target name= "logFile" xsi:type= "File" fileName= "${}.\TestLogDirectory\relativeTest_logs_${shortdate}.log" layout= "${longdate}|${logger}|${uppercase:${level}}|${message}${exception}" /> <target name= "logConsole" xsi:type= "Console" /> </targets> <rules> <logger name= "Microsoft.*" minlevel= "Trace" writeTo= "logConsole" final= "true" /> <logger name= "*" minlevel= "Trace" writeTo= "logFile" /> </rules> </nlog> |
四、创建控制器
在项目文件上右击,添加,新建文件夹,文件夹名称取名“Controllers”;
接着创建控制器(步骤如下图),控制器名称为“NLogController”(用于测试),最后点击“添加”;
双击刚刚创建好的NLogController文件,
往里面写入如下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; #region 引用Nlog using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using NLog.Web; #endregion namespace NLogTest5.Controllers { public class NLogController : Controller { public NLogController(ILogger<Program> logger) { Logger = logger; } public ILogger Logger { get ; } [Route( "/NLog/Index" )] public IActionResult Index() { Logger.LogError($ " {DateTime.Now}: testLog Error !" ); return View(); } } } |
五、在Program和Startup进行相应的依赖注入和配置
双击Program,添加代码“ .UseNLog();//配置使用NLog”
Program的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NLog.Web; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NLogTest5 { public class Program { public static void Main( string [] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder( string [] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .UseNLog(); //配置使用NLog } } |
双击“Startup”
写入如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | using AutoMapper; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using NLogTest5.Filters; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace NLogTest5 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get ; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddMvc(config => { config.EnableEndpointRouting = false ; //config.Filters.Add<JsonExceptionFilter>(); config.ReturnHttpNotAcceptable = true ; config.OutputFormatters.Add( new XmlSerializerOutputFormatter()); }).SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory ) { #region 默认 //if (env.IsDevelopment()) //{ // app.UseDeveloperExceptionPage(); //} //else //{ // app.UseExceptionHandler("/Error"); //} //app.UseStaticFiles(); //app.UseRouting(); //app.UseAuthorization(); //app.UseEndpoints(endpoints => //{ // endpoints.MapRazorPages(); //}); #endregion loggerFactory.AddNLog(); env.ContentRootPath = "nlog.config" ; app.UseHttpsRedirection(); app.UseMvc(); } } } |
六、运行项目
在浏览器上输入http://localhost:14206/NLog/Index,将会出现异常;
再来看文件夹是否有了日志(如下图,有日志了)
打开日志,下图是我测试出来的日志记录,表示日志打印成功!
(关注到其他的NLog: https://www.cnblogs.com/zhangchengye/p/6297685.html)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器