一、新建ASP.NET Core 2.0 MVC项目,使用NuGet在浏览中搜索:NLog.Web.AspNetCore,如下图所示:
二、在项目的根目录下新建一个xml类型的nlog.config文件
nlog.config文件内容如下:
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 | <? 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}|${logger}|${uppercase:${level}}|${message} ${exception}" /> < target xsi:type="File" name="ownFile-web" fileName="nlog-my-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> < target xsi:type="Null" name="blackhole" /> </ targets > < rules > <!--All logs, including from Microsoft--> < logger name="*" minlevel="Trace" writeTo="allfile" /> <!--Skip Microsoft logs and so log only own logs--> < logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> < logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </ rules > </ nlog > |
三、在Startup类中添加配置
在Configure方法中增加ILoggerFactory loggerFactory参数,然后添加2行代码, 如下所示:
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 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler( "/Home/Error" ); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); loggerFactory.AddNLog(); //*****使用NLog作为日志记录工具 env.ConfigureNLog( "Nlog.config" ); //*****引入Nlog配置文件 app.UseMvc(routes => { routes.MapRoute( name: "default" , template: "{controller=Home}/{action=Index}/{id?}" ); }); } |
四、Program.cs中绑定
1 2 3 4 | public static IWebHostBuilder CreateWebHostBuilder( string [] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseNLog(); //使用Nlog日志 |
五、在控制器IActionResult中使用Nlog
1 2 3 4 5 6 7 8 9 10 11 12 13 | //获得日志的实例 public static Logger nlog = LogManager.GetCurrentClassLogger(); public IActionResult Index() { nlog.Info( "普通信息日志-----------" ); nlog.Debug( "调试日志-----------" ); nlog.Error( "错误日志-----------" ); nlog.Fatal( "异常日志-----------" ); nlog.Warn( "警告日志-----------" ); nlog.Trace( "跟踪日志-----------" ); nlog.Log(LogLevel.Warn, "Log日志------------------" ); return View(); } |
注:NLog日志的位置默认是在bin\Debug下面。
参考:http://www.voidcn.com/article/p-hukbuiwx-bch.html
其他参考的nlog.config配置文件
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 | <?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" throwConfigExceptions= "true" internalLogLevel= "info" internalLogFile= "d:\log\internal-nlog.txt" > <!-- the targets to write to --> <targets> <!-- write logs to file --> <target xsi:type= "File" name= "allfile" fileName= "d:\log\nlog-all-${shortdate}.log" layout= "${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" /> <!-- another file log, only own logs. Uses some ASP.NET core renderers --> <target xsi:type= "File" name= "ownFile-web" fileName= "d:\log\nlog-own-${shortdate}.log" layout= "${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" /> </targets> <!-- rules to map from logger name to target --> <rules> <!--All logs, including from Microsoft--> <logger name= "*" minlevel= "Trace" writeTo= "allfile" /> <!--Skip non-critical Microsoft logs and so log only own logs--> <logger name= "Microsoft.*" maxlevel= "Info" final= "true" /> <!-- BlackHole --> <logger name= "*" minlevel= "Trace" writeTo= "ownFile-web" /> </rules> </nlog> |
自己配置的的nlog.config文件
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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | <?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" throwExceptions= "false" internalLogLevel= "Off" internalLogFile= "c:\temp\nlog-internal.log" > <!--autoReload修改配置文件后是否允许自动加载无须重启程序--> <!--throwExceptions 内部日志系统抛出异常,建议throwExceptions的值设为“ false ”,这样由于日志引发的问题不至于导致应用程序的崩溃。--> <!--internalLogLevel 可选Trace|Debug|Info|Warn|Error|Fatal决定内部日志的级别 Off 关闭--> <!--internalLogFile 把内部的调试和异常信息都写入指定文件里--> <!--定义常量--> <variable name= "logDirectory" value= "${basedir}/logs/${shortdate}" /> <variable name= "layoutVal" value= "${longdate} ${uppercase:${level}} ${message}" /> <targets> <!--输出目标: name名称, xsi:type输出类型文件, fileName输出到程序根目录logs文件夹中, 以日期作为生成log文件名称, maxArchiveDays= "14" 保留14天内的日志 maxArchiveFiles= "14" 保留文档最大数量为14 layout生成内容的格式 --> <target name= "all" xsi:type= "File" encoding= "utf-8" fileName= "${logDirectory}/all.log" maxArchiveDays= "7" maxArchiveFiles= "7" layout= "${layoutVal}" /> <target name= "debug" xsi:type= "File" encoding= "utf-8" fileName= "${logDirectory}/debug.log" maxArchiveDays= "7" maxArchiveFiles= "7" layout= "${layoutVal}" /> <target name= "error" xsi:type= "File" encoding= "utf-8" fileName= "${logDirectory}/error.log" maxArchiveDays= "14" maxArchiveFiles= "14" layout= "${layoutVal}" /> </targets> <!--不输出--> <target xsi:type= "Null" name= "blackhole" /> <rules> <!-- name:记录者的名字。 minlevel :最低日志级别。 maxlevel:最高日志级别。 level:单一日志级别。 levels:一系列日志级别,由逗号分隔。 final:是否是最后的匹配路由, true 表示匹配到这里就结束。 writeTo:规则匹配时日志应该被写入的一系列目标,由逗号分隔。就是tagets对应的name。 日志级别有如下,自上而下,等级递增。 - Trace - 最常见的记录信息,一般用于普通输出 - Debug - 同样是记录信息,不过出现的频率要比Trace少一些,一般用来调试程序 - Info - 信息类型的消息 - Warn - 警告信息,一般用于比较重要的场合 - Error - 错误信息 - Fatal - 致命异常信息。一般来讲,发生致命异常之后程序将无法继续执行。 --> <!--Info级别以上日志写入info--> <logger name= "*" minlevel= "Trace" writeTo= "all" /> <!--屏蔽掉微软系统日志,只输出自己的日志--> <logger name= "Microsoft.*" minlevel= "Trace" writeTo= "blackhole" final= "true" /> <!--Debuy日志,单独写入debug--> <logger name= "*" level= "Debug" writeTo= "debug" /> <!--Error日志,单独写入error--> <logger name= "*" level= "Error" writeTo= "error" /> </rules> </nlog> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理