• asp.net core NLog将日志写到文件


    1、安装Nlog包

    Install-Package NLog.Extensions.Logging -Pre

    2、在项目添加nlog.config文件

     2.1、nlog.config 

    复制代码
    <?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="Loggers/${shortdate}.log"
                     layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
    
    
        <target xsi:type="File" name="ownFile-web" fileName="Loggers/${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>
    复制代码

    3、在项目中添加project.json 配置文件

      3.2、project.json 文件内容

    复制代码
    {
      "publishOptions": {
        "include": [
          "wwwroot",
          "Views",
          "appsettings.json",
          "web.config",
          "Config/nlog.config" //加上nlog配置文件
        ]
      }
    }
    复制代码

    4、在Startup.cs 中Configure方法添加如下代码

    复制代码
      // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactor)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                //此方法被LogManager.LoadConfiguration替代 
                //loggerFactor.ConfigureNLog("Config/nlog.config");
                //加载Nlog的nlog.config配置文件
                LogManager.LoadConfiguration("Config/nlog.config");
                //添加NLog
                loggerFactor.AddNLog();
    
                app.UseMvcWithDefaultRoute();
    
                app.Run(async (context) =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            }
    复制代码

    5、Controller 调用Nlog 方法

    复制代码
       public class BlogController : Controller
        {
            private TestDBContext dBContext;
            private readonly ILogger<BlogController> logger;
            public BlogController(TestDBContext _dBContext, ILogger<BlogController>  _logger)
            {
                dBContext = _dBContext;
                logger = _logger;
            }
    
            public IActionResult Index()
            {
                logger.LogInformation("你访问了首页55555");
                logger.LogWarning("警告信息55555");
                logger.LogError("错误信息55555");
    
                var list = dBContext.Blog.Select(a => new BlogViewModel() {
                    CreateTime = a.CreateTime,
                    Id = a.BlogId,
                    Title = a.Title,
                    Url = a.Url
                }).ToList();
                return View(list);
            }
    }
    复制代码

    6、运行项目成功,查看log

    log 目录在bin 目录下 

    7、NLog GitHub 项目

     https://github.com/linezero/Blog/tree/master/NETCoreLogging

  • 相关阅读:
    前端页面模拟浏览器搜索功能Ctrl+F实现
    正则表达式中?=和?:和?!的理解
    JRebel激活教程
    BAT脚本一键启动多个程序
    WinInet简介及操作流程
    通过线程传递消息
    两串口收发测试
    获取PC可用串口端口,并将其在combo box中显示
    为MFC应用程序添加登录对话框界面
    Using CInternetFile open an Url
  • 原文地址:https://www.cnblogs.com/bruce1992/p/15077341.html
Copyright © 2020-2023  润新知