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

AddConsole()? It's not the same but it will help to isolate the problem