I'm trying to use the 'Database' NLog target and would like NLog to read my connection string to avoid having to set it twice in the same config file. The problem is I have an Entity Framework-style connection string, so using the connectionStringName
attribute doesn't work.
In log4net, I can use a custom AdoNetAppender and extract the appropriate pieces of the connection string myself. Is there any way to customize NLog's Database target so I can pass in an appropriately styled connection string?
This problem can be easily solved by configuring logging target in code:
private DatabaseTarget CreateDatabaseTarget()
{
var entityFrameworkConnection = ConfigurationManager.ConnectionStrings["MyEntities"].ConnectionString;
var builder = new EntityConnectionStringBuilder(entityFrameworkConnection);
var connectionString = builder.ProviderConnectionString;
var target = new DatabaseTarget()
{
ConnectionString = connectionString,
CommandText = @"insert into Log ([DateTime], [Message]) values (@dateTime, @message);",
Parameters = {
new DatabaseParameterInfo("@dateTime", new NLog.Layouts.SimpleLayout("${date}")),
new DatabaseParameterInfo("@message", new NLog.Layouts.SimpleLayout("${message}")),
}
};
return target;
}
Then you can register it with your NLog configuration:
var target = CreateDatabaseTarget();
LogManager.Configuration.AddTarget("databaseTarget", CreateDatabaseTarget());
LogManager.Configuration.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Warn, target));
But if you're fine with taking some Nuget dependencies or want a more complete solution, you can take a look at NLog.Mvc and NLog.EntityFramework repositories who both have nuget packages available...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With