EF Core logging of sql commands

Viewed 728

I need to do a logging of sql commands (select, update, delete, insert) in EF Core. I have the next realization:

public class CustomLoggerProvider : ILoggerProvider
{
    public ILogger CreateLogger(string categoryName)
    {
        if (string.Equals(categoryName, DbLoggerCategory.Database.Command.Name))
        {
            return new CustomLogger();
        }

        return NullLogger.Instance;
    }

    public void Dispose() { }

    private class CustomLogger : ILogger
    {
        public IDisposable BeginScope<TState>(TState state) => null;

        public bool IsEnabled(LogLevel logLevel) => true;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            var log = formatter(state, exception);
            AppLogger.Log(log);
        }
    }
}

...
dbcontext.GetService<ILoggerFactory>().AddProvider(new CustomLoggerProvider());

In case of INSERT command I get a set of logs. One of them is the next:

"Executing DbCommand [Parameters=[@p0='?' (Size = 128), @p1='?' (DbType = DateTimeOffset), @p2='?' (Size = 128), @p3='?' (Size = 128), @p4='?' (Size = 128) (DbType = Binary), @p5='?' (DbType = DateTimeOffset), @p6='?' (DbType = DateTimeOffset)], CommandType='Text', CommandTimeout='30']\r\nSET NOCOUNT ON;\r\nINSERT INTO [someSchema].[SomeTable] ([ID], [Column1], [Column2], [Column3], [Column4], [Column5], [Column6])\r\nVALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6);"

As you can see there are @p0='?' or @p0 instead of parameter values. Is there a way to resolve it?

1 Answers

you need to enable Sensitive Logging

services.AddDbContextPool<MyDbContext>(builder =>
{
    ....
    builder.EnableSensitiveDataLogging(true);
});

or

public class MyDbContext : DbContext
{

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    { 
        optionsBuilder.EnableSensitiveDataLogging();
        base.OnConfiguring(optionsBuilder);
    }

}

Reference

Related