简体   繁体   English

记录实体框架 .Net Core 2.2 EF 以调试输出窗口

[英]Log Entity Framework .Net Core 2.2 EF to debug output window

Using Entity Framework in .Net Core 2.2, I'd like to log all SQL statements generated by EF to the Debug Output window in Visual Studio.在 .Net Core 2.2 中使用实体框架,我想将 EF 生成的所有 SQL 语句记录到 Visual Studio 中的调试输出窗口。

In .Net Framework I simply had to add this line to the DbContext constructor:在 .Net Framework 中,我只需将此行添加到 DbContext 构造函数中:

Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

In EF I'm trying the following.在 EF 中,我正在尝试以下操作。 It compiles, and the OnConfiguring method does get called, but no database calls are logged to my Debug Output window.它编译,并且 OnConfiguring 方法确实被调用,但没有数据库调用记录到我的调试输出窗口。 What am I missing?我错过了什么?

public class MyContext : DbContext
{
    private ILoggerFactory GetLoggerFactory()
    {
        IServiceCollection serviceCollection = new ServiceCollection();
        serviceCollection.AddLogging(builder => builder
            .AddDebug()
            .AddFilter(DbLoggerCategory.Database.Command.Name, LogLevel.Debug));
        return serviceCollection.BuildServiceProvider()
                .GetService<ILoggerFactory>();
    }

    public MyContext(DbContextOptions<MembershipContext> options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseLoggerFactory(GetLoggerFactory());
    }
}

My appsettings.json contains this:我的 appsettings.json 包含这个:

  "Logging": {
"LogLevel": {
  "Default": "Debug"
}

}, },

And my Startup.cs contains this line in the ConfigureServices method:我的 Startup.cs 在 ConfigureServices 方法中包含这一行:

services.AddDbContext<MyContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("MyConnectionSTring")));

Startup.cs also contains this per one of the answer below, but it does not cause EF SQL to get printed to the output window: Startup.cs 也包含下面的每个答案,但它不会导致 EF SQL 打印到输出窗口:

    public ILogger<Startup> Logger { get; set; }

    public Startup(IConfiguration configuration, ILogger<Startup> logger)
    {
        Configuration = configuration;
        Logger = logger;

        //the following line gets printed to my debug output window:
        logger.LogDebug("this is a debug message");
    }

I could not use .AddDebug() in my EFCore 3 application.我无法在我的 EFCore 3 应用程序中使用 .AddDebug()。 I added nuget package Microsoft.Extensions.Logging.Debug To my project and was able to use it.我在我的项目中添加了 nuget 包 Microsoft.Extensions.Logging.Debug 并且能够使用它。 I now see the generated SQL commands in the Output Window (Show output from Debug).我现在在输出窗口中看到生成的 SQL 命令(显示来自调试的输出)。

Create a field in the context:在上下文中创建一个字段:

public static readonly ILoggerFactory _loggerFactory
                    = LoggerFactory.Create(builder => builder.AddDebug().AddFilter((category, level) => level == LogLevel.Information && !category.EndsWith("Connection")));

and add the field to your optionsBuilder:并将该字段添加到您的 optionsBuilder:

 optionsBuilder.UseLoggerFactory(_loggerFactory);

you also need to add the ILogger Interface to the Startup.cs您还需要将 ILogger 接口添加到 Startup.cs

     public Startup(IConfiguration configuration, ILogger<Startup> logger, IHostingEnvironment hostingEnvironment)
        {   
            Configuration = configuration;
            Logger = logger;
            HostingEnvironment = hostingEnvironment;
        }

        public ILogger<Startup> Logger { get; }

I use Serilog and it works with following options in the appsetting just fine我使用 Serilog,它可以很好地与 appsetting 中的以下选项配合使用

    "Serilog": {
    "MinimumLevel": {
      "Default": "Debug"
    }

Thank you for the comments and answers.感谢您的评论和回答。 The issue here was between my ears.这里的问题是在我的耳朵之间。 The code I originally posted in my question works;我最初在问题中发布的代码有效; it logs raw SQL to the debug output window for Entity SQL queries.它将原始 SQL 记录到 Entity SQL 查询的调试输出窗口。

In fact, a lot less is needed if the application uses asp.net core (which this one does, it is a web api application).事实上,如果应用程序使用 asp.net core(这个应用程序是一个 web api 应用程序),则需要的更少。 By default Visual Studio 2017 inserts the following bit of code in Program.cs as part of the project template:默认情况下,Visual Studio 2017 在 Program.cs 中插入以下代码作为项目模板的一部分:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)  
            .UseStartup<Startup>();

The call to CreateDefaultBuilder adds 3 types of logging--Console, Debug, EventSource--and also fetches the "Logging" section from appsettings.json.对 CreateDefaultBuilder 的调用添加了 3 种类型的日志记录——控制台、调试、事件源——并且还从 appsettings.json 获取“日志记录”部分。 The "LoggerFactory" stuff in my original question is redundant and not needed.我原来问题中的“LoggerFactory”内容是多余的,不需要。

The code I was testing and failing with, while it used the database context, was executing a stored procedure using System.Data.Common.DbCommand, which does not pass information to the logger hooked up to the DbContext.我正在测试并失败的代码在使用数据库上下文时,正在使用 System.Data.Common.DbCommand 执行存储过程,该过程不会将信息传递给连接到 DbContext 的记录器。 I need to log System.Data.Common.DbCommand sql statements manually (this is also needed in .Net Framework, but it has been so many years since I've touched this I'd forgotten).我需要手动记录 System.Data.Common.DbCommand sql 语句(这在 .Net Framework 中也是需要的,但是自从我接触到这个我已经忘记了很多年了)。

When I created a DbSet in my DbContext and did a select against it using Entity SQL, eg:当我在 DbContext 中创建一个 DbSet 并使用实体 SQL 对其进行选择时,例如:

var log = _myContext.Log.FirstOrDefault(o => o.Id > 0);

this successfully logs the raw SQL to my debug output window, eg:这成功地将原始 SQL 记录到我的调试输出窗口,例如:

Microsoft.EntityFrameworkCore.Database.Command:Information: 
Executed DbCommand (6ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [o].[Id], [o].[Browser], [o].[Client], [o].[Date], [o].[Exception], 
[o].[Host], [o].[Level], [o].[Logger], [o].[Message], [o].[StackTrace], [o].[Thread], 
[o].[User]
FROM [Log] AS [o]
WHERE [o].[Id] > 0

You can try this if it will help.如果有帮助,你可以试试这个。 Thanks谢谢

 public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logger => {
                logger.AddDebug()
                      .AddFilter(DbLoggerCategory.Database.Command.Name, LogLevel.Information);
                //logger.AddConsole(); //UnComment out this line if you did not use CreateDefaultBuilder
            });

在此处输入图片说明

You can run this in Visual Studio Code and it will display the SQL queries. 您可以在Visual Studio Code中运行它,它将显示SQL查询。 VSCode is free. VSCode是免费的。 You can download it here: Click Here 你可以在这里下载: 点击这里

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

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