简体   繁体   English

如何在全球范围内进行EF日志SQL查询?

[英]How to make EF log sql queries globally?

How do I "tell" EF to log queries globally? 如何“告诉” EF以全局方式记录查询? I was reading this blog post: EF logging which tells in general how to log sql queries. 我正在阅读此博客文章: EF日志记录 ,它通常介绍如何记录sql查询。 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); 我需要在哪里放置此行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? 还是我必须将其放置在执行DB操作的任何地方?
  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 ? 如果我不使用context.Database.Log也将记录此日志吗?

  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. 如果您未启用日志记录,它将不会记录日志。

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 但是,您是否想知道更多细节...访问链接... https://cmatskas.com/logging-and-tracing-with-entity-framework-6/在这种情况下,您可以放置​​这样的代码

  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 我希望那是有用的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM