ASP.NET CORE下日志NLOG使用
ASP.NET CORE下日志NLOG使用
摘自《深入浅出ASP.NET CORE》
NUGET:NLog.Web.AspNetCore 4.9.0
根目录下nlog.config
1 2 3 4 5 6 7 8 9 10 | <?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" > <targets> <target name= "allfile" xsi:type= "File" fileName= "Logs/${shortdate}.log" ></target> </targets> <rules> <logger name= "*" minlevel= "Trace" writeTo= "allfile" ></logger> </rules> </nlog> |
.net core 3.1项目中的program
1 2 3 4 5 6 7 8 9 10 | public static IHostBuilder CreateHostBuilder( string [] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging((hostingContext, logging) => { logging.AddNLog(); //加入nlog }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); |
net7项目中的program 只需要加一句:builder.Logging.AddNLog(); 就行,如果要测试把下面的 if (!app.Environment.IsDevelopment())注释掉就行
/home/error方法里的代码:
1 2 3 4 5 6 7 8 9 10 11 12 | private readonly ILogger<HomeController> _logger; [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true )] public IActionResult Error() { var ex = HttpContext.Features.Get<IExceptionHandlerPathFeature>(); ViewBag.ExceptionPath = ex.Path; ViewBag.ExceptionMessage = ex.Error.Message; ViewBag.StackTrace = ex.Error.StackTrace; _logger.LogError($ "异常路径:{ex.Path}\r\n异常信息:{ex.Error.Message}\r\n堆栈跟踪:{ex.Error.StackTrace}\r\n\r\n\r\n" ); return View( new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } |
撸码:复制、粘贴,拿起键盘就是“干”!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2019-08-01 WPF,回车即是tab