Claritta
Claritta

Reputation: 299

log4Net with entity framework

I have an asp.net application using log4Net to log messages to a file. I would like to log messages to a database knowing that I am using code first with entity framework. I am currently able to log message to database and file at the same time if the database already exists. However what I would like to achieve, is that if the database hasn't been created yet then the first call to log a message to database would both create the database and log the message. I can do this now by calling this code in global.asax.cs file:

using (var DataContext = new MyContext())
        {

            Log logsnew = DataContext.Logs.SingleOrDefault();                
        }

        logger.Info("info test message");

This is the constructor of my context:

public MyContext()
        : base($"name=MyConnectionString")
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
    }

I would like to avoid the using block each time I have to log a message, is there another way to do this please?

Upvotes: 0

Views: 964

Answers (1)

Peter
Peter

Reputation: 27944

If you want log4net to log to the database and file, just configure a FileAppender and an AdoNetAppender. You should not log into your application database, best practice is to make a separate database for your logging. If you have problems with your database, you can still log into your logging database.

Upvotes: 1

Related Questions