使用 log4net 从 class 库登录 Api

Using log4net to log in Api from class library

我有一个正在尝试调试的网络api。

我使用通用存储库结构,因此我的所有 entity framework 调用都是在单独的 class 库中进行的。

所以我的网站 Api post 端点实际上只是调用 service.insert(entity)。通用插入位于单独的 class 库中。

日志记录当前正在 api 中设置和工作。现在我想在父应用程序文本日志文件中记录由 entity framework 生成的插入 Sql(因为实时环境中发生了一些奇怪的事情)

请问我该怎么做?

如何执行此操作取决于您使用的实体框架版本。在 EF6 及更高版本中很简单:

using (var context = new DataContext())
{
    // log is a log4net logger
    context.Database.Log = message => log.Debug(message);

    // insert the entity
}

有关早期 EF 版本的选项,请参阅 this blog series for more information - part 3 shows an example of logging to NLog with a command interceptor - and this page