简体   繁体   中英

Get NpgSql Entity Framework query text

I am using Npgsql.EntityFrameworkCore.PostgreSQL 2.2.0. I want to be able to see the query that will be executed on the database. Is there any way of doing this?

Normally there is no need to configure LoggerFactory explcitly if you are using .AddDbContext or .AddDbContextPool on service registration. EF Core automatically grabs existing logger factory (configured) and uses Debug level log in order to log queries.

You can alternatively enable

builder.EnableSensitiveDataLogging();  // << Enables query parameter/value logging
builder.EnableDetailedErrors(); // << Enables Detailed Errors such as parameter mapping errors
builder.ConfigureWarnings(warnings => 
    warnings.Log(CoreEventId.IncludeIgnoredWarning));  << Includes ignored warnings

The only thing you need to do is to change the logging level accordingly

"Logging": {
  "LogLevel": {
    ....
    "Microsoft.EntityFrameworkCore.Database.Command": "Information"
  }
}

or you may use Custom logger factory

public static readonly LoggerFactory MyLoggerFactory
    = new LoggerFactory(new[]
    {
        new ConsoleLoggerProvider((category, level)
            => category == DbLoggerCategory.Database.Command.Name
               && level == LogLevel.Information, true)
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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