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 });
}

 

posted @   牛腩  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2019-08-01 WPF,回车即是tab
点击右上角即可分享
微信分享提示