[英]Log Entity Framework .Net Core 2.2 EF to debug output window
在 .Net Core 2.2 中使用實體框架,我想將 EF 生成的所有 SQL 語句記錄到 Visual Studio 中的調試輸出窗口。
在 .Net Framework 中,我只需將此行添加到 DbContext 構造函數中:
Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
在 EF 中,我正在嘗試以下操作。 它編譯,並且 OnConfiguring 方法確實被調用,但沒有數據庫調用記錄到我的調試輸出窗口。 我錯過了什么?
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());
}
}
我的 appsettings.json 包含這個:
"Logging": {
"LogLevel": {
"Default": "Debug"
}
},
我的 Startup.cs 在 ConfigureServices 方法中包含這一行:
services.AddDbContext<MyContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnectionSTring")));
Startup.cs 也包含下面的每個答案,但它不會導致 EF SQL 打印到輸出窗口:
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");
}
我無法在我的 EFCore 3 應用程序中使用 .AddDebug()。 我在我的項目中添加了 nuget 包 Microsoft.Extensions.Logging.Debug 並且能夠使用它。 我現在在輸出窗口中看到生成的 SQL 命令(顯示來自調試的輸出)。
在上下文中創建一個字段:
public static readonly ILoggerFactory _loggerFactory
= LoggerFactory.Create(builder => builder.AddDebug().AddFilter((category, level) => level == LogLevel.Information && !category.EndsWith("Connection")));
並將該字段添加到您的 optionsBuilder:
optionsBuilder.UseLoggerFactory(_loggerFactory);
您還需要將 ILogger 接口添加到 Startup.cs
public Startup(IConfiguration configuration, ILogger<Startup> logger, IHostingEnvironment hostingEnvironment)
{
Configuration = configuration;
Logger = logger;
HostingEnvironment = hostingEnvironment;
}
public ILogger<Startup> Logger { get; }
我使用 Serilog,它可以很好地與 appsetting 中的以下選項配合使用
"Serilog": {
"MinimumLevel": {
"Default": "Debug"
}
感謝您的評論和回答。 這里的問題是在我的耳朵之間。 我最初在問題中發布的代碼有效; 它將原始 SQL 記錄到 Entity SQL 查詢的調試輸出窗口。
事實上,如果應用程序使用 asp.net core(這個應用程序是一個 web api 應用程序),則需要的更少。 默認情況下,Visual Studio 2017 在 Program.cs 中插入以下代碼作為項目模板的一部分:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
對 CreateDefaultBuilder 的調用添加了 3 種類型的日志記錄——控制台、調試、事件源——並且還從 appsettings.json 獲取“日志記錄”部分。 我原來問題中的“LoggerFactory”內容是多余的,不需要。
我正在測試並失敗的代碼在使用數據庫上下文時,正在使用 System.Data.Common.DbCommand 執行存儲過程,該過程不會將信息傳遞給連接到 DbContext 的記錄器。 我需要手動記錄 System.Data.Common.DbCommand sql 語句(這在 .Net Framework 中也是需要的,但是自從我接觸到這個我已經忘記了很多年了)。
當我在 DbContext 中創建一個 DbSet 並使用實體 SQL 對其進行選擇時,例如:
var log = _myContext.Log.FirstOrDefault(o => o.Id > 0);
這成功地將原始 SQL 記錄到我的調試輸出窗口,例如:
Microsoft.EntityFrameworkCore.Database.Command:Information:
Executed DbCommand (6ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [o].[Id], [o].[Browser], [o].[Client], [o].[Date], [o].[Exception],
[o].[Host], [o].[Level], [o].[Logger], [o].[Message], [o].[StackTrace], [o].[Thread],
[o].[User]
FROM [Log] AS [o]
WHERE [o].[Id] > 0
如果有幫助,你可以試試這個。 謝謝
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logger => {
logger.AddDebug()
.AddFilter(DbLoggerCategory.Database.Command.Name, LogLevel.Information);
//logger.AddConsole(); //UnComment out this line if you did not use CreateDefaultBuilder
});
您可以在Visual Studio Code中運行它,它將顯示SQL查詢。 VSCode是免費的。 你可以在這里下載: 點擊這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.