How to make EF log sql queries globally?

2019-03-03 09:54发布

How do I "tell" EF to log queries globally? I was reading this blog post: EF logging which tells in general how to log sql queries. But I still have a few questions regarding this logger.

  1. Where would I need to place this line context.Database.Log = s => logger.Log("EFApp", s);?
  2. Can it be globally set? Or do I have to place it everywhere I do DB operations?
  3. In the "Failed execution" section, the blogger wrote that, and I quote:

    For commands that fail by throwing an exception, the output contains the message from the exception.

Will this be logged too if I don't use the context.Database.Log?

2条回答
女痞
2楼-- · 2019-03-03 10:14
  1. Whenever you want the context to start logging.
  2. It appears to be done on the context object so it should be done every time you create a new context. You could add this line of code in your constructor though to ensure that it is always enabled.
  3. It will not log if you do not enable the logging.
查看更多
冷血范
3楼-- · 2019-03-03 10:26

I don't recommend to use that's functionality, because, it hasn't reason to exists in the real case. Thats it use a lot of to debug code only. But, wether you wanna know more than details ... access link... https://cmatskas.com/logging-and-tracing-with-entity-framework-6/ In this case you can put code like this

  public void Mylog()
    {
        //Thats a delegate where you can set this property to log using 
        //delegate type Action, see the code below

        context.Database.Log = k=>Console.Write("Any query SQL")
        //Or
        context.Database.Log = k=>Test("Any query SQL")

    }

    public void Test(string x){

        Console.Write(x)
    }

I hope thats useufull

查看更多
登录 后发表回答