Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

In .Net Framework I simply had to add this line to the DbContext constructor:

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

In EF I'm trying the following. It compiles, and the OnConfiguring method does get called, but no database calls are logged to my Debug Output window. 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:

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

},

And my Startup.cs contains this line in the ConfigureServices method:

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:

    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");
    }
like image 690
Tom Regan Avatar asked Dec 23 '22 23:12

Tom Regan


1 Answers

I could not use .AddDebug() in my EFCore 3 application. I added nuget package Microsoft.Extensions.Logging.Debug To my project and was able to use it. I now see the generated SQL commands in the Output Window (Show output from Debug).

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.UseLoggerFactory(_loggerFactory);
like image 194
CANDIMAN Avatar answered Feb 19 '23 22:02

CANDIMAN