Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NLog with an Entity Framework connection string?

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?

like image 355
ladenedge Avatar asked Feb 03 '12 21:02

ladenedge


1 Answers

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...

like image 75
Valeriu Caraulean Avatar answered Sep 23 '22 11:09

Valeriu Caraulean