NLog with an Entity Framework 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...
There is no way to customize the built in DatabaseTarget
because it's sealed
.
And there aren't any other extension points because the DatabaseTarget.InitializeTarget()
will always throw an exception because it cannot create the DbProviderFactory
form the EF providerName="System.Data.EntityClient"
So with the current NLog version 2.0.0.0
you have to following options:
- You can duplicate the connection string or you can use the DatabaseTarget DB configuration attributes.
- You can write your own custom target basically from scratch.
- You can submit a feature request, and wait until it's implemented.