Search code examples
c#.netpostgresqlentity-framework-corenpgsql

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?


Solution

  • 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)
        });