NLog posts in this series:
- ASP.NET Core logging with NLog and Microsoft SQL Server
- ASP.NET Core logging with NLog and Elasticsearch
- 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:gitdamienbodAspNetCoreNlogLogsinternal-nlog.txt"> <targets> <target name="database" xsi:type="Database" > <!-- THIS is not required, read from the appsettings.json <connectionString> Data Source=N275MSSQLSERVER2014;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://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