asp.net core 日志

  日志输出是应用程序必不可少的部分,log4net,nlog这些成熟的组件在之前的项目中被广泛使用,在asp.net core的项目中没有找到与之对应的log4net版本,nlog对core提供了很好的支持,使用上也就简单几步即可完成日志组件的安装。

github上提供了非常明细的操作步骤:

https://github.com/NLog/NLog.Extensions.Logging/blob/master/README.md

1,project.json文件增加引用 

"dependencies": {
    "NLog.Extensions.Logging": "1.0.0-*"
  }

2,项目根目录增加配置文件nlog.config

3,startup.cs增加引用

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();//添加NLog
            
            env.ConfigureNLog("nlog.config");

4,project.json增加日志配置文件

 "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "nlog.config",//增加nlog
"web.config" ] },

 

配置文件范例:

https://raw.githubusercontent.com/NLog/NLog.Extensions.Logging/03971763546cc70660529bbe28b282304adb7571/examples/aspnet-core-example/src/aspnet-core-example/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="c:\temp\internal-nlog.txt">

  <!-- define various log targets -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
                 layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

   
    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
             layout="${longdate}|${event-properties:item=EventId.Id}|${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>

 

posted @ 2016-12-31 00:42  京沙  阅读(696)  评论(0编辑  收藏  举报