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

 

posted @ 2019-04-24 11:36  大空白纸  阅读(2232)  评论(1编辑  收藏  举报