本文转自:
NLog posts in this series:
- 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 , with no database connection string configured.
insert into dbo.Log ( Application, Logged, Level, Message, Logger, CallSite, Exception ) values ( @Application, @Logged, @Level, @Message, @Logger, @Callsite, @Exception );
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