ASP.NET Core 和 NLog 集成

一直很喜欢 NLog 的简洁和扩展性,所以准备将 ASP.NET Core 提供的默认日志提供程序替换成 NLog

步骤 1

在项目的project.json中添加依赖NLog.Extensions.Logging

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

或者通过NuGet程序包管理器添加。

步骤 2

在ASP.NET Core的启动类StartupConfigure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)方法中添加:

// using NLog.Extensions.Logging;

loggerFactory.AddNLog();
//needed for non-NETSTANDARD platforms: configure nlog.config in your project root
env.ConfigureNLog("nlog.config");

步骤 3

在项目目录下添加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"
      throwConfigExceptions="true"
      internalLogLevel="Warn"
      internalLogToTrace="true"
      internalLogFile="AppData/Logs/NLogInternal.log">

  <!-- 
    - 日志文件被放置于 AppData/Logs 文件夹中,文件名为 {日志类目}.log 或 {日志类目}.err
    - 日志按天存档,放置于 AppData/Logs/Archives/{日志类目} 文件夹中,文件名为 {日期}.log 或 {日期}.err
  --&g
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
.Net Core2.1+NLog+数据库连接 <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" throwExceptions="true" internalLogLevel="warn" internalLogFile="logfiles/internal-nlog.txt"> <targets> <target xsi:type="Null" name="blackhole" /> <target name="database" xsi:type="Database" dbProvider="System.Data.SqlClient" connectionString="Data Source=127.0.0.1;Initial Catalog=MiddleData;User ID=lzhu;Password=bl123456;" > <!-- create table NLog ( Id int identity, Application nvarchar(50) null, Logged datetime null, Level nvarchar(50) null, Message nvarchar(512) null, Logger nvarchar(250) null, Callsite nvarchar(512) null, Exception nvarchar(512) null, constraint PK_NLOG primary key (Id) ) --> <commandText> insert into nlog ( Application, Logged, Level, Message, Logger, CallSite, Exception ) values ( @Application, @Logged, @Level, @Message, @Logger, @Callsite, @Exception ); </commandText> <parameter name="@application" layout="NLogTestDemo" /> <parameter name="@logged" layout="${date}" /> <parameter name="@level" layout="${level}" /> <parameter name="@message" layout="${message}" /> <parameter name="@logger" layout="${logger}" /> <parameter name="@callSite" layout="${callsite:filename=true}" /> <parameter name="@exception" layout="${exception:tostring}" /> </target> </targets> <rules> <!--Skip Microsoft logs and so log only own logs--> <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> <logger name="NLogTestDemo.*" minlevel="Info" writeTo="database" /> </rules> </nlog>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值