Safely Log EF Core SQL Queries in Production
Of course. Here is the rewritten blog post, following your style guide and prompt.
Stop Flying Blind: Safely Log EF Core SQL in Production
I remember the incident vividly. P95 latency for our main API shot through the roof overnight. Our logs showed a bunch of slow HTTP requests, but nothing about why they were slow. We were flying blind. After hours of frantic debugging, we found the culprit: a seemingly innocent LINQ query was generating a monster SQL join, causing a full table scan on a massive table.
We had no visibility into what Entity Framework Core was doing. This one burned me, and I promised myself: never again.
Most developers face this. They either accept the black box and pray, or they enable dangerous logging flags that leak sensitive user data. There’s a much better way to see exactly what SQL EF Core is executing in production without compromising security.
TL;DR: Use a custom DbCommandInterceptor
to log SQL, execution time, and parameter metadata (but never the values). Correlate logs with a TraceId
and use sampling or thresholds to avoid log noise.
The Common Mistakes That’ll Get You Paged at 3 AM
Before we get to the right way, let’s talk about the traps. I’ve seen these “temporary fixes” make their way into production code, and the results are always painful.
- Never use
EnableSensitiveDataLogging()
in production. I can’t stress this enough. It logs parameter values. That means passwords, personal user info, and …