How to log SQL generated by EF using log4net

时光怂恿深爱的人放手 提交于 2021-02-07 09:19:21

问题


In my web project I'm using EF6 and I'd like to log generated SQL for debugging purpose.

I'm also using log4net to handle logs, so I'm looking for a way to integrate them together.

What's the correct way to achieve this?


回答1:


At the moment I'm using this approach: in my BaseController I have something like this:

public class BaseController
{
    protected MyDbContext DataContext { get; set; }
    protected readonly ILog logger;

    public BaseController()
    {
        DataContext = new MyDbContext();
        logger = LogManager.GetLogger(GetType());

        DataContext.Database.Log = (dbLog => logger.Debug(dbLog));

        // ...
    }

    //...

}

I don't know if this is the best way, but it works...




回答2:


if someone after 2 years still searches for a solution:

the solution of @davioooh led me to something similar (if you probably use Entity Framework not with a WebApi, or don't want to use a BaseController-class):

Just when inheriting from DbContext you could also do this in the constructor:

public class MyContext:DbContext
{
    private readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public MyContext()
           : base("<connectionstring>")
    {
        Database.Log = log => _logger.Debug(log);
    }
}


来源:https://stackoverflow.com/questions/31983706/how-to-log-sql-generated-by-ef-using-log4net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!