Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using context.Database.Log in MVC web app

Using the guide here, I'm trying to log the SQL generated by my MVC web application.

The guide uses the line:

context.Database.Log = Console.Write;

Which obviously doesn't work with a web application. The guide described the Log property:

The DbContext.Database.Log property can be set to a delegate for any method that takes a string.

And it's this I don't understand, delegates just confuse me. How can I use this EF6 feature?

like image 565
markpsmith Avatar asked Oct 10 '13 14:10

markpsmith


3 Answers

Using a delegate allows you to do write any function taking a string. As a very simple logging to a file, you could do the following:

context.Database.Log = message => File.AppendText("C:\\mylog.txt").WriteLine(message);

In a web environment, you may wish to use Trace to log this information:

context.Database.Log = message => Trace.WriteLine(message);

You can see more examples of using delegates on the MSDN page on Anonymous Functions.

like image 186
Richard Avatar answered Sep 30 '22 22:09

Richard


To write your logs to a file, try this:

using (var context = new MyDbContext())
{
    var logFile = new StreamWriter("C:\\temp\\log.txt");
    context.Database.Log = logFile.Write;

    // Execute your queries here
    // ....

    logFile.Close();
}
like image 22
Stacked Avatar answered Sep 30 '22 22:09

Stacked


You can print it in Debug window:

dbContext.Database.Log = message => Debug.Write(message);
like image 37
gtu Avatar answered Sep 30 '22 23:09

gtu