参见:https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

补充:

  如在本地能写log,但是发布到IIS无法写log,请注意引用程序池的账号,默认的“ApplicationPoolIdentity”应该是没有权限的,将其改为“LocalSystem”即可。

大致步骤:

  • Nuget中引用NLog及NLog.Web.AspNetCore 4.5+
  • 创建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="info"
    internalLogFile="logs\internal-nlog.log"> <!-- enable asp.net core layout renderers -->
    <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
    </extensions> <!-- the targets to write to -->
    <targets>
    <!-- write logs to file -->
    <target name="allFile" xsi:type="File" fileName="logs\nlog-all-${shortdate}.log"
    layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" /> <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
    <target name="ownFile" xsi:type="File" fileName="logs\nlog-own-${shortdate}.log"
    layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" /> <target name="blackHole" xsi:type="Null" /> </targets> <!-- rules to map from logger name to target -->
    <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allFile" />
    <!--Own logs-->
    <logger name="HiP.*" minlevel="Trace" writeTo="ownFile" /> <!--Skip non-critical Microsoft logs and so log only own logs-->
    <!--<logger name="Microsoft.*" maxLevel="Info" writeTo="blackHole" final="true" />--> </rules>
    </nlog>
    <!--LogLevel="Trace|Debug|Info|Warn|Error|Fatal"-->
  • 右键nlog.config,属性,生成操作设为“内容”,复制到输出目录为“始终复制”
  • Program.cs中:
    public static void Main(string[] args)
    {
    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    try
    {
    logger.Debug("init main"); CreateHostBuilder(args).Build().Run();
    }
    catch (Exception ex)
    {
    //NLog: catch setup errors
    logger.Error(ex, "Stopped program because of exception");
    throw ex;
    }
    finally
    {
    // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
    NLog.LogManager.Shutdown();
    } } public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .UseServiceProviderFactory(new AutofacServiceProviderFactory()) //会调用Startup中的ConfigureContainer方法
    .ConfigureWebHostDefaults(webBuilder =>
    {
    webBuilder
    .UseStartup<Startup>()
    .UseUrls("http://localhost:8080")
    //这里是配置log的
    .ConfigureLogging((hostingContext, builder) =>
    {
    builder.ClearProviders();
    //builder.SetMinimumLevel(LogLevel.Warning); //使用Nlogs的配置
    //builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
    //builder.AddConsole();
    //builder.AddDebug();
    })
    .UseNLog(); // NLog: setup NLog for Dependency injection. 3.0中这样添加
    });
    }
  • 配置appsettings.json。注意在配置中的设置将覆盖代码中的SetMinimumLevel属性。所以要么删除“Default”使用代码中的配置,要么就要设置正确。

    {
    "Logging": {
    "LogLevel": {
    "Default": "Trace",
    "Microsoft": "Information"
    }
    }
    }

    注意:如你有多个环境,注意appsetings.Development.json的配置。

  • 使用:
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();
}
  • 结果查看。如你的配置与我一致,则在项目的logs文件夹会存在internal-nlog.txt文件。在bin\Debug\netcoreappXX\logs目录下会以日期存在输出日志。

.Net Core使用NLog记录日志的更多相关文章

  1. ASP.NET Core使用NLog记录日志到Microsoft Sql Server

    在之前的文章中介绍了如何在ASP.NET Core使用NLog,本文为您介绍在ASP.NET Core使用NLog记录到Microsoft Sql Server 1.我们需要添加依赖: NLog.We ...

  2. .Net Core 使用NLog记录日志到文件和数据库

    NLog 记录日志是微软官方推荐使用. 接下来,通过配置日志记录到文件和Sql Server数据库. 第一步:首先添加包NLog.Config (可通过微软添加包命令Install-Package 包 ...

  3. asp.net core 使用NLog记录日志到txt文件

    一.使用VisualStudioCode创建一个webapi项目(也可以是mvc等).一个类库(用于封装记录日志方法,当然如果使用依赖注入到控制台项目,就不需要此类库了). 二.在类库中添加NLog. ...

  4. ASP.NET Core使用NLog记录日志

    1.根目录新建nlog.config配置文件 <?xml version="1.0"?> <nlog xmlns="http://www.nlog-pr ...

  5. [.Net Core] - 使用 NLog 记录日志到 Sql Server

    1. 使用 Nuget 安装 NLog. 2. 在 Sql Server 中创建 NLog 数据表. CREATE TABLE [dbo].[NLogInfo]( ,) NOT NULL, [Date ...

  6. .netcore3.1使用log4net/nlog记录日志

    .netcore3.1使用log4net/nlog记录日志 .netcore3.1与2.x之间很是有不少差异的.本来想通过ctrl+c,ctrl+v将在2.2中实现的简单日志记录搬到.netcore3 ...

  7. [转]C# 使用Nlog记录日志到数据库

    本文转自:http://www.cnblogs.com/weixing/archive/2013/04/26/3044422.html 摘要]Nlog是一个很不错的.NET日志记录组件,它可以将日志输 ...

  8. .NET中使用NLog记录日志

    以前小编记录日志使用的是Log4Net,虽然好用但和NLog比起来稍显复杂.下面小编就和大伙分享一下NLog的使用方式. 引用NLog.Config 在使用NLog之前,我们要首先添加对NLog.Co ...

  9. Nlog 记录日志到 sqlite

    最近研究了一下Nlog这个日志框架,这里记录一下如何将日志写到sqlite中. 第一步:使用NuGet获取Nlog和Sqlite 第二步:在sqlite中创建一个database,这里我用了SQLit ...

随机推荐

  1. What if you are involved in an automobile accident in the US

    What if you are involved in an automobile accident in the US With increasing Chinese tourists and vi ...

  2. Java对象的serialVersion序列化和反序列化

    Java基础学习总结——Java对象的序列化和反序列化 一.序列化和反序列化的概念 把对象转换为字节序列的过程称为对象的序列化. 把字节序列恢复为对象的过程称为对象的反序列化. 对象的序列化主要有两种 ...

  3. Microsoft SQL Server 2012 管理 (2): 实例与数据库管理

    1.加密数据库 /* Module 2 Implementing Transparent Data Encryption */ -- 2.1 Create DataBase Master Key US ...

  4. Sending Email In .NET Core 2.0

    Consider the following written in .NET Core 2.0. SmtpClient client = ) { UseDefaultCredentials = tru ...

  5. leetcode 两数之和 II - 输入有序数组

    给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2. 说明: 返回的下标值 ...

  6. SSRS (一)创建基础报表

    ReportService创建基础报表 1.数据库SQL Server2012选择SQL Server Data Tools 2.创建商业智能(BI)项目 选择报表服务器项目 ReportServic ...

  7. 如何使用socket进行java网络编程(二)

    通过在如何使用socket进行java网络编程(一)中程序的编写,可以总结出一些常用的java socket编程的范例来. ServerSocket server = new ServerSocket ...

  8. 920. Number of Music Playlists

    Your music player contains N different songs and she wants to listen to L (not necessarily different ...

  9. *p++与(*p)++与*(p++)------自增运算符常见误区

    自增运算符(++) 自增\自减运算符分为前缀形(++a)和后缀形(a++),这里重点分析自增 大部分人对前缀和后缀的理解一般是,前缀形式是先++再使用(先变后用),后缀形式是先使用再++(先用后变) ...

  10. Bonjour Operations

    https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/NetServices/Articles/NetServi ...