EF Core - Logging
在平穩無波的資料操作背後,EF Core 為我們自動生成了大量 SQL 語法。這些語法就像資料的悄悄話,大部分時間默默運作,沒出錯就好。但一旦效能下滑、查詢遲緩,這些悄悄話就需要被「聽見」。
因此,我們需要打開 EF Core 的日誌紀錄機制,看看背後究竟在跑什麼樣的 SQL。
🌊 為什麼要紀錄 EF Core 自動產生的 SQL 命令?
EF Core 是一套功能強大的 ORM 框架,幫助我們用物件導向的方式操作資料。但 ORM 所產生的 SQL 並非總是最有效率的選擇。
透過 Logging,我們可以:
- 檢查 EF Core 實際送出的 SQL 語法
- 發現不必要的 JOIN 或 WHERE 條件
- 優化查詢速度(例如加上索引、改用 View 或 Stored Procedure)
這對效能調教與除錯都非常有幫助。
🌊 調整 appsettings.json
的 LogLevel
1 | { |
這樣設定後,就能把 EF Core 執行的 SQL 命令印出來。
🌊 在程式中啟用敏感資料紀錄(選配)
1 | builder.Services.AddDbContext<AdventureWorks2022>(options => |
可以進一步 Log 出經過的事件
1 | builder.Services.AddDbContext<AdventureWorks2022>(options => |
這樣能看到查詢中的參數值,對除錯特別有幫助。但要小心不要在 Production 使用,避免洩露敏感資料。
🌊 設定 LogTo:印出日誌到 Console 或其他地方
1 | options.LogTo(Console.WriteLine, LogLevel.Information); |
你也可以指定 LogLevel 或類別:
1 | options.LogTo(Console.WriteLine, new[] { DbLoggerCategory.Database.Name }, LogLevel.Information); |
這樣能針對 SQL Command 類別做過濾,更聚焦。
輸出到檔案中:永久保存你的 SQL 日誌
可以把日誌寫到檔案中
1 | private readonly StreamWriter _logStream = new StreamWriter("EFCoreDebug.log", append: true); |
這種方式適合長時間觀察 SQL 執行狀況,或做問題追蹤。
🌊 閱讀:從官方與社群學更多
Logging SQL and Change-Tracking Events in EF Core
Overview of Logging and Interception
Logging in Entity Framework Core
Entity Framework Core: Show Parameter Values in Logging
🌊 結語
開啟 EF Core Logging,就像戴上一副能聽懂資料庫語言的耳機。它能幫助你更清楚每一筆資料的來去、每一次查詢的代價。
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment