NetCore使用Nlog记录日志

2021-01-27 05:14

阅读:793

标签:ext   记录   OLE   core   soft   filename   trace   int   none   

当前环境: win10+vs2019+netcore3.1

添加Nuget包引用:NLog.Web.AspNetCore

技术图片

 

 

 2. 添加 nlog.config配置文件 或者安装包 nlog.confg

技术图片技术图片
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="Info"
      internalLogFile="c:\temp\internal-nlog.txt">

    
    extensions>
        add assembly="NLog.Web.AspNetCore"/>
    extensions>

    
    targets>
        
        target xsi:type="File" name="allfile" fileName="logs\nlog-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

        
        target xsi:type="File" name="ownFile-web" fileName="logs\nlog-own-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
    targets>

    
    rules>
        
        logger name="*" minlevel="Trace" writeTo="allfile" />

        
        logger name="Microsoft.*" maxlevel="Info" final="true" />
        
        logger name="*" minlevel="Trace" writeTo="ownFile-web" />
    rules>
nlog>
View Code

 

3. 在CreateHostBuilder 中添加使用Nlog ( ConfigureLogging)

public static IHostBuilder CreateHostBuilder(string[] args)
{
       return Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup();
                }).ConfigureLogging(
                    logging =>
                    {
                        // 清除系统默认的日志
                        //logging.ClearProviders();
                        logging.SetMinimumLevel(LogLevel.Trace);
                    }).UseNLog();
}

4. 配置文件路径

NLog.Web.NLogBuilder.ConfigureNLog("nlog.config")

5. 调用

    public class HomeController : Controller
    {
        private readonly ILogger _logger;

        public HomeController(ILogger logger)
        {
            _logger = logger;
            _logger.LogDebug(1, "NLog injected into HomeController");
        }

        public IActionResult Index()
        {
            _logger.LogInformation("Hello, this is the index!");
            return View();
        }
}

6. 效果

在bin\Debug\netcoreapp3.1 目录下生成了logs文件夹

 

NetCore使用Nlog记录日志

标签:ext   记录   OLE   core   soft   filename   trace   int   none   

原文地址:https://www.cnblogs.com/wtujvk/p/13222233.html


评论


亲,登录后才可以留言!