本文转自: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. java中int转String 固定位数 不足补零

    转载自:http://ych0108.iteye.com/blog/2174134 String.format("%010d", 25); //25为int型 0代表前面要补的字符 ...

  2. Xcode9新功能

    1.折叠代码 局部折叠(折叠一个函数):Command+Option+Left/Right 全局折叠(折叠当前文件下的全部函数): Shift+Command+Option+Left/Right 折叠 ...

  3. 异常上报功能Bugly简介

    目的:为了能够快速定位到线上版本bug位置,经过比较之后,决定使用腾讯家的Bugly. 1.注册产品 官方文档使用指南 1.1 登录 - 使用 QQ 登录Bugly官网 没有账号就注册,要实名就实名, ...

  4. C# Winform下一个热插拔的MIS/MRP/ERP框架(多语言方案)

    个别时候,我们需要一种多语种切换方案. 我的方案是这样的: 1.使用文本文本存储多语言元素,应用程序启动时加载到内存表中: 2.应用程序启动时从配置文件加载语种定义: 3.所有窗体继承自一个Base基 ...

  5. Win7下C/C++跨平台开发工具IDE的安装之CodeBlocks

    1. Win7下安装CodeBlocks: 下载带有mingw的CodeBlocks:http://www.codeblocks.org/downloads/26#windows 运行所下载程序: 点 ...

  6. 基于Spring MVC的文件上传和下载功能的实现

    配置文件中配置扫描包,以便创建各个类的bean对象 <context:component-scan base-package="com.neuedu.spring_mvc"& ...

  7. controller运行springboot项目

    搭建完springboot项目后,新建HelloController.java文件,编写main方法,启动HelloController.java,具体代码如图: 在浏览器访问127.0.0.1:80 ...

  8. CentOS安装pip并修改源为豆瓣源

    使用yum进行安装 yum install python-pip 若出现 No package python-pip available. 则解决方法如下: yum -y install epel-r ...

  9. 【原创】elasticsearch入门

    示例 示例一: 示例二: 示例三: 示例四: ES介绍 ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Ela ...

  10. POJ_3696 The Luckiest number 【欧拉定理+同余式+对取模的理解】

    一.题目 Chinese people think of '8' as the lucky digit. Bob also likes digit '8'. Moreover, Bob has his ...