• 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

  • 相关阅读:
    Oracle死锁只会回滚跟死锁有关的那条SQL,而不会回滚整个事务
    Mysql安装过程(linux:2.6.18-194.el5,Mysql:)
    格式化分区,报/dev/sdb1 is apparently in use by the system; will not make a filesystem here!
    安装Oracle 11gR2,报错:[INS-06101] IP address of localhost could not be determined
    mysql-5.5.25-winx64在win7 x64 免安装配置
    insert遭遇阻塞
    linux中轻松使用backspace和上下按键
    排序
    MySQL
    基于Boost的同步TCP通信
  • 原文地址:https://www.cnblogs.com/bruce1992/p/15077341.html
Copyright © 2020-2023  润新知