# ASP.NET Core 2.x 使用Nlog
## 第一步
> 创建一个 ASP.NET Core 2.x 项目

## 第二步
  > 添加nuget包

  > + NLog 
  > + NLog.Web.AspNetCore 
  > + NLog.Extensions.Logging

## 第三步
  > 根目录创建配置文件 nlog.config, 至少配置一项Target和一项Rules

## 第四步
 > 配置文件属性配置为"复制到输出目录"

## 第五步
> 更新 program.cs

``` csharp
using NLog.Web;
using Microsoft.Extensions.Logging;

public static void Main(string[] args)
{
    // NLog: setup the logger first to catch all errors
    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    try
    {
        logger.Debug("init main");
        CreateWebHostBuilder(args).Build().Run(); 
    }
    catch (Exception ex)
    {
        //NLog: catch setup errors
        logger.Error(ex, "Stopped program because of exception");
        throw;
    }
    finally
    {
        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        NLog.LogManager.Shutdown();
    }
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
        })
        .UseNLog();  // NLog: setup NLog for Dependency injection
```

## 第六步
> 配置 appsettings.json 

> 在appsettings.json中指定的日志配置将覆盖对setminimumlevel的任何调用。所以要么去掉“默认”:要么根据你的需要调整它。

``` json
{
    "Logging": {
        "LogLevel": {
            "Default": "Trace",
            "Microsoft": "Information"
        }
    }
}
```
> 记住还要更新任何特定于环境的配置,以避免任何意外。例如:appsettings.development.json

## 第七步
> 写日志:在controller中,注入 ILogger

```csharp
using Microsoft.Extensions.Logging;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Index page says hello");
        return View();
    }
}
```

## 第八步

> 查看日志