Using context.Database.Log in MVC web app

前端 未结 3 1753
我在风中等你
我在风中等你 2021-01-17 21:47

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;
         


        
相关标签:
3条回答
  • 2021-01-17 22:17

    You can print it in Debug window:

    dbContext.Database.Log = message => Debug.Write(message);
    
    0 讨论(0)
  • 2021-01-17 22:18

    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();
    }
    
    0 讨论(0)
  • 2021-01-17 22:25

    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.

    0 讨论(0)
提交回复
热议问题