本文转自:https://damienbod.com/2016/09/22/setting-the-nlog-database-connection-string-in-the-asp-net-core-appsettings-json/

NLog posts in this series:

  1. ASP.NET Core logging with NLog and Microsoft SQL Server
  2. ASP.NET Core logging with NLog and Elasticsearch
  3. Settings the NLog database connection string in the ASP.NET Core appsettings.json

The XML nlog.config file is the same as in the previous post, with no database connection string configured.

<?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:\git\damienbod\AspNetCoreNlog\Logs\internal-nlog.txt"> <targets> <target name="database" xsi:type="Database" > <!-- THIS is not required, read from the appsettings.json <connectionString>
Data Source=N275\MSSQLSERVER2014;Initial Catalog=Nlogs;Integrated Security=True;
</connectionString>
--> <!--
Remarks:
The appsetting layouts require the NLog.Extended assembly.
The aspnet-* layouts require the NLog.Web assembly.
The Application value is determined by an AppName appSetting in Web.config.
The "NLogDb" connection string determines the database that NLog write to.
The create dbo.Log script in the comment below must be manually executed. Script for creating the dbo.Log table. SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[Log] (
[Id] [int] IDENTITY(1,1) NOT NULL,
[Application] [nvarchar](50) NOT NULL,
[Logged] [datetime] NOT NULL,
[Level] [nvarchar](50) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[Logger] [nvarchar](250) NULL,
[Callsite] [nvarchar](max) NULL,
[Exception] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([Id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--> <commandText>
insert into dbo.Log (
Application, Logged, Level, Message,
Logger, CallSite, Exception
) values (
@Application, @Logged, @Level, @Message,
@Logger, @Callsite, @Exception
);
</commandText> <parameter name="@application" layout="AspNetCoreNlog" />
<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>
<logger name="*" minlevel="Trace" writeTo="database" /> </rules>
</nlog>

The NLog DatabaseTarget connectionstring is configured in the appsettings.json as described in the ASP.NET Core configuration docs.

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ElasticsearchUrl": "http://localhost:9200",
"ConnectionStrings": {
"NLogDb": "Data Source=N275\\MSSQLSERVER2014;Initial Catalog=Nlogs;Integrated Security=True;"
}
}

The configuration is then read in the Startup constructor.

public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

The Nlog DatabaseTagert is then configured to use the connection string from the app settings and sets all the DatabaseTarget instances for NLog to use this. All target properties can be configured in this way if required.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog(); foreach (DatabaseTarget target in LogManager.Configuration.AllTargets.Where(t => t is DatabaseTarget))
{
target.ConnectionString = Configuration.GetConnectionString("NLogDb");
} LogManager.ReconfigExistingLoggers(); app.UseMvc();
}

Links

https://github.com/NLog/NLog.Extensions.Logging

https://github.com/NLog

https://github.com/NLog/NLog/blob/38aef000f916bd5ffd8b80a5576afa2423192e84/examples/targets/Configuration%20API/Database/MSSQL/Example.cs

https://docs.asp.net/en/latest/fundamentals/logging.html

https://msdn.microsoft.com/en-us/magazine/mt694089.aspx

https://github.com/nlog/NLog/wiki/Database-target

https://docs.asp.net/en/latest/fundamentals/configuration.html

[转]Setting the NLog database connection string in the ASP.NET Core appsettings.json的更多相关文章

  1. ASP.NET Core 入门教程 10、ASP.NET Core 日志记录(NLog)入门

    一.前言 1.本教程主要内容 ASP.NET Core + 内置日志组件记录控制台日志 ASP.NET Core + NLog 按天记录本地日志 ASP.NET Core + NLog 将日志按自定义 ...

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

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

  3. Asp.Net Core中使用NLog记录日志

    2019/10/28, Asp.Net Core 3.0, NLog 4.6.7, NLog.Web.AspNetCore 4.9.0 摘要:NLog在asp.net网站中的使用,NLog日志写入数据 ...

  4. ASP.NET Core 实战:使用 NLog 将日志信息记录到 MongoDB

    一.前言 在项目开发中,日志系统是系统的一个重要组成模块,通过在程序中记录运行日志.错误日志,可以让我们对于系统的运行情况做到很好的掌控.同时,收集日志不仅仅可以用于诊断排查错误,由于日志同样也是大量 ...

  5. ASP.NET Core使用Elasticsearch记录NLog日志

    ASP.NET Core使用Elasticsearch记录NLog日志 1.新建一个 ASP.NET Core项目 2.安装Nuge包 运行:Install-Package NLog.Web.AspN ...

  6. Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near ';characterEncoding=UTF

    今天在使用springboot整合SSM的时候,配置好以后启动项目,报了一个这样的异常 java.sql.SQLNonTransientConnectionException: Cannot load ...

  7. .WrongArgumentException: Malformed database URL, failed to parse the connection string near ';characterEncoding=UTF-8&;serverTimezone=Asia/Shanghai'.)

    连接mysql库报的异常信息: org.springframework.transaction.CannotCreateTransactionException: Could not open JDB ...

  8. ASP.NET MVC 5 - 创建连接字符串(Connection String)并使用SQL Server LocalDB

    您创建的MovieDBContext类负责处理连接到数据库,并将Movie对象映射到数据库记录的任务中.你可能会问一个问题,如何指定它将连接到数据库? 实际上,确实没有指定要使用的数据库,Entity ...

  9. 转载 How to Encrypt connection string in web.config

    转载原地址: https://chiragrdarji.wordpress.com/2008/08/11/how-to-encrypt-connection-string-in-webconfig/ ...

随机推荐

  1. 二、安装Node.js和npm

    1.Note的各个版本官方下载地址: https://nodejs.org/en/download/releases/ 这里我们选择7.6版本为例进行下载安装: 根据自己的情况下载对应的msi安装包 ...

  2. 【leetcode 5040. 边框着色】解题报告

    方法一:dfs的非递归形式 using ll=long long; const ll MAXN=50LL; unordered_set<ll> vis,mark; vector<ve ...

  3. 钩子(hook)编程

    一.钩子介绍 1.1钩子的实现机制 钩子英文名叫Hook,是一种截获windows系统中某应用程序或者所有进程的消息的一种技术.下图是windows应用程序传递消息的过程: 如在键盘中按下一键,操作系 ...

  4. 「BZOJ 3123」「SDOI 2013」森林「启发式合并」

    题意 你有一个森林,你需要支持两个操作 查询两个结点路径上权值第\(k\)小 两个点之间连一条边 强制在线,结点数\(\leq 8\times 10^4\) 题解 如果可以离线,这就是一个主席树板子题 ...

  5. 上课总结-模电chapter 2

    1.无明显失真时电压放大倍数——输出与输入电压的变化量之比 .无明显失真时 电流放大倍数——输出与输入电流的变化量之比 3.最大输出幅度 ①无明显失真时最大输出电压(或最大输出电流) ②交流有效值(U ...

  6. 如何下载火山小视频-附火山小视频下载youtube视频下载网站

    火山小视频下载方法: 1. 打开火山小视频APP 2. 点开某个视频,点击右下角分享按钮,在分享弹框中点击复制链接,或者通过分享到微信QQ等获取视频链接 3. 打开在线免费的火山小视频解析下载工具 h ...

  7. vim使用及vimrc配置

    参考文章 https://segmentfault.com/a/1190000011466454 如有侵权,请联系本人删除!

  8. Java面向对象之关键字static 入门实例

    一.基础概念 静态关键字 static 是成员修饰符,直接用于修饰成员. (一)特点: 1.被静态修饰的成果,可以直接被类名所调用. 2.静态成员优先于对象存在. 3.静态成员随着类的加载而加载.随着 ...

  9. 用python的正则表达式实现简单的计算器功能

    #!/usr/bin/env python # -*- coding:utf-8 -*- import sys import re def welcome_func(): ""&q ...

  10. OpenStack-Mitaka

    一.Cloud 基础概念 IAAS:Infrastructre As A Service 基础架构及服务,OpenStack,CloudStack PAAS:Platform As A Service ...