Skip to content

ADR: Watching your own SQL, explained

ADR: Watching your own SQL, explained

Status: written for a developer who has used an ORM but never hooked one, 2026-09-03. Companion to ADR: What the database is actually doing, which is the decision. This one is the walkthrough.

In plain words

This page shows a developer how to see the SQL the code's data mapper sends, by asking it to hand over each command (an EF Core interceptor) instead of parsing log text. It also shows how a type with no field for parameter values keeps email addresses off a public page.

What that is worth: a developer learns to build a type that has no place for a secret, and the organization gets query timings on a public page without a metrics library.

The problem, in one sentence

You want to see the SQL your ORM sends, and you cannot see it by reading your own code, because your own code does not contain any SQL.

That is the trade you made when you picked an ORM. You write db.Vehicles.OrderBy(v => v.Seq).ToList() and something else decides what the database receives. Most of the time that is fine. The moment it is not fine is the moment somebody asks why a page takes two seconds, and the answer is a query nobody has ever looked at.

The three ways to look, and why two of them are traps

Turn on the log. Entity Framework already logs every command at Information. One line of configuration and it is on your console. This is the right answer for local debugging and it is where you should start.

It stops being the right answer the moment you want the data somewhere other than a console, because a log line is a string. To put the duration in a column you have to find it in the string. To group by statement you have to find that in the string too. You are now writing a parser for a message format that is not a contract and changes between versions.

Time it yourself. Wrap your repository calls in a stopwatch. This tells you how long your method took, which is not the same question. Your method might send four queries, or one, or none because the value was cached, and the stopwatch cannot tell you which.

Ask the ORM to hand you the command. EF Core has a type for this:

public sealed class SqlLogInterceptor(ISqlLog log, ICurrentRequest request) : DbCommandInterceptor
{
    public override DbDataReader ReaderExecuted(
        DbCommand command, CommandExecutedEventData eventData, DbDataReader result)
    {
        Record(command, eventData.Duration, "read");
        return base.ReaderExecuted(command, eventData, result);
    }
}

You get the DbCommand itself. Not a rendering of it: the object, with CommandText as a string you did not have to parse and Parameters as a collection you can walk. And eventData.Duration is a TimeSpan that EF measured, so you are not guessing where to start your own stopwatch.

You register it on the context:

builder.Services.AddDbContextFactory<YardDbContext>((services, options) =>
{
    yard.Configure(options);
    options.AddInterceptors(new SqlLogInterceptor(sqlLog, services.GetRequiredService<ICurrentRequest>()));
});

There are six methods to override rather than one, because there are three kinds of command (a reader, a non-query, a scalar) and each has a synchronous and an asynchronous form. Override the ones you use and the rest fall through to the base.

The part that is a security decision, not a logging one

Here is the thing to take away from this record, and it is not about EF.

This application's Admin page is public. So the SQL on it is public. And the parameters of a registration are an email address.

The first design anybody reaches for is a redaction rule: show the values, hide the sensitive ones. Think about what that rule is. It is a list, written today, of which columns are sensitive. Next year somebody adds a phone number. The rule does not know about it. Nothing fails. The page shows it.

The design that does not have that problem is not a better rule. It is no rule:

public sealed record SqlParameterShape(string Name, string Type, int? Size);

There is nowhere to put a value. Not a redacted one, not a masked one. The code that builds these reads ParameterName, DbType and Size and never touches Value, and a future column cannot leak through a field that does not exist.

This is worth recognising as a shape, because it comes up constantly and it has a name in older books: make the illegal state unrepresentable. When you are about to write a rule that says "and remember to hide X", check first whether you can build a type that has no X.

And note this is also why the interceptor beats the log line here. EF's log message has the values formatted into it before any of your code runs. By the time you could strip them, they have already been built, already been in memory, and already been handed to every other logging provider in the process, which in this application includes Application Insights. Taking something out of a string after you have broadcast the string is not taking it out.

The percentile, which is smaller than it looks

The page shows p50 and p95 per endpoint. Those sound like they need a metrics library. They need eleven lines:

public static long Of(IReadOnlyList<long> values, int percentile)
{
    if (values.Count == 0)
    {
        return 0;
    }

    long[] sorted = values.ToArray();
    Array.Sort(sorted);
    int rank = (int)Math.Ceiling(percentile / 100.0 * sorted.Length) - 1;
    return sorted[Math.Clamp(rank, 0, sorted.Length - 1)];
}

Sort, then take the value at that position. That is the nearest-rank percentile, and it is exact.

The reason real systems do not do this is that they cannot keep every sample: at a million requests a minute you need a sketch, which is an approximation with a memory bound. This application keeps its last five hundred requests in a ring buffer, so sorting five hundred longs on each page load costs microseconds and the answer is exact for that window.

The lesson is not "percentiles are easy". It is that the expensive machinery exists to solve a scale problem, and you should know whether you have that problem before you take on the machinery.

  • The decision, with the constraint that drove it: ADR: What the database is actually doing.
  • Where the ports came from and why Infrastructure does not know what an HttpContext is: ADR: Program.cs, explained.
  • Why the Admin page is public at all: ADR: Observability.

The interceptor this record explains, read from this build. It subclasses EF Core's DbCommandInterceptor, overrides one method per command kind, and writes the statement's shape into the port in SqlLog.cs, never a parameter's value:

/// <summary>
/// Reads every command EF Core sends and hands it to the <see cref="IStatementLog"/>.
///
/// This is an interceptor rather than a log filter on purpose. EF's own
/// "Executed DbCommand" log line already contains everything, including the
/// parameter values, as one formatted string. Parsing that string to take the
/// values back out would mean the values had already been built, already been
/// in memory as a message, and already been handed to every other logging
/// provider in the process, Application Insights included. The interceptor sees
/// the <see cref="DbCommand"/> itself, so this code can read a parameter's name,
/// type and size and never touch <c>Value</c> at all.
/// </summary>
public sealed class SqlLogInterceptor(IStatementLog log, ICurrentRequest request, TimeProvider clock) : DbCommandInterceptor
{
    // A statement is trimmed before it is stored: EF writes a SELECT of every
    // column of Vehicles, which is thirty of them, and the Admin tab is a page
    // rather than a query editor.
    private const int MaxTextLength = 2_000;

    private void Record(DbCommand command, TimeSpan duration, string outcome)
    {
        // Nothing in here is allowed to break a query that worked.
        //
        // This runs on the path of every command the application sends. A
        // provider whose DbType getter throws for some exotic parameter, or a
        // ring that is somehow in a bad state, would otherwise turn a healthy
        // SELECT into a failed request, and the Admin tab would have caused the
        // outage it exists to explain. An observability hook that can break the
        // thing it observes is worse than no hook.
        try
        {
            RecordOrThrow(command, duration, outcome);
        }
        catch
        {
            // Deliberately silent, and deliberately not logged: this is called
            // from inside a database command, and a logger here is one more
            // thing that can fail on the same path.
        }
    }

    private void RecordOrThrow(DbCommand command, TimeSpan duration, string outcome)
    {
        var parameters = new List<ParameterShape>(command.Parameters.Count);
        foreach (DbParameter parameter in command.Parameters)
        {
            // Name, type, size. Never Value. See the comment on StoreStatement.
            parameters.Add(new ParameterShape(
                parameter.ParameterName,
                parameter.DbType.ToString(),
                parameter.Size == 0 ? null : parameter.Size));
        }

        string text = command.CommandText.Length <= MaxTextLength
            ? command.CommandText
            : command.CommandText[..MaxTextLength] + "\n... trimmed";

        log.Record(new StoreStatement(
            clock.GetUtcNow(),
            text,
            parameters,
            (long)duration.TotalMilliseconds,
            outcome,
            request.Describe()));
    }

    /// <summary>Records a query that returned rows, as "read", and hands the reader on untouched.</summary>
    public override DbDataReader ReaderExecuted(DbCommand command, CommandExecutedEventData eventData, DbDataReader result)
    {
        Record(command, eventData.Duration, "read");
        return base.ReaderExecuted(command, eventData, result);
    }

    /// <summary>Records a query that returned rows on the asynchronous path, which is the one the application uses.</summary>
    public override ValueTask<DbDataReader> ReaderExecutedAsync(
        DbCommand command, CommandExecutedEventData eventData, DbDataReader result, CancellationToken cancellationToken = default)
    {
        Record(command, eventData.Duration, "read");
        return base.ReaderExecutedAsync(command, eventData, result, cancellationToken);
    }

    /// <summary>Records a statement that changed rows, with how many it affected as the outcome, because that count is the only evidence a write did anything.</summary>
    public override int NonQueryExecuted(DbCommand command, CommandExecutedEventData eventData, int result)
    {
        Record(command, eventData.Duration, $"{result} row(s) affected");
        return base.NonQueryExecuted(command, eventData, result);
    }

    /// <summary>Records a statement that changed rows on the asynchronous path, with the same affected count.</summary>
    public override ValueTask<int> NonQueryExecutedAsync(
        DbCommand command, CommandExecutedEventData eventData, int result, CancellationToken cancellationToken = default)
    {
        Record(command, eventData.Duration, $"{result} row(s) affected");
        return base.NonQueryExecutedAsync(command, eventData, result, cancellationToken);
    }

    /// <summary>Records a statement that returned one value, as "scalar". The value itself is never recorded: it is data, and this log is about statements.</summary>
    public override object? ScalarExecuted(DbCommand command, CommandExecutedEventData eventData, object? result)
    {
        Record(command, eventData.Duration, "scalar");
        return base.ScalarExecuted(command, eventData, result);
    }

    /// <summary>Records a statement that returned one value on the asynchronous path, and keeps the value out in the same way.</summary>
    public override ValueTask<object?> ScalarExecutedAsync(
        DbCommand command, CommandExecutedEventData eventData, object? result, CancellationToken cancellationToken = default)
    {
        Record(command, eventData.Duration, "scalar");
        return base.ScalarExecutedAsync(command, eventData, result, cancellationToken);
    }

    /// <summary>Records a command that threw, naming the exception's type and never its message, so a provider quoting the value that broke a constraint cannot put that value in the log.</summary>
    public override void CommandFailed(DbCommand command, CommandErrorEventData eventData)
    {
        // The exception type, not its message: a provider's message can quote
        // the value that broke the constraint.
        Record(command, eventData.Duration, "failed: " + eventData.Exception.GetType().Name);
        base.CommandFailed(command, eventData);
    }

    /// <summary>Records a command that threw on the asynchronous path, naming the type and not the message for the same reason.</summary>
    public override Task CommandFailedAsync(
        DbCommand command, CommandErrorEventData eventData, CancellationToken cancellationToken = default)
    {
        Record(command, eventData.Duration, "failed: " + eventData.Exception.GetType().Name);
        return base.CommandFailedAsync(command, eventData, cancellationToken);
    }
}

Live from api/TheYard.Infrastructure/Shared/Stores/SqlLogInterceptor.cs, region sql-interceptor, read from this build at 99df7a8.

Where it sits

The walkthrough centres on Infrastructure: SqlLogInterceptor subclasses EF Core's DbCommandInterceptor and writes into the ports and shapes in Application/SqlLog.cs, while the percentile helper sits in the host's RequestTimings.cs. Open/closed is the EF feature on show: the interceptor adds behaviour to the ORM through a hook EF publishes, with no change to EF or to any query. Its cost is an override per command kind to keep in step, and a type with no Value field that cannot show a value even when debugging wants one. A system with far more traffic than a five-hundred-entry ring would need a sketch or a metrics library for its percentiles.

Files

Enforced by

Not machine-checked. Held by review.

Store

The Yard, home

Steven StoutStaff .NET engineerRemote

Production .NET that stays up. Built with AI, measured on every version.

Steven Stout

Hi, I'm Steve. I build the systems that make delivery boring in the best way, then coach people inside them.

  • 200+

    production releases, none took the platform down

    Conway Investment Research, 2019 to 2024. Sole engineer for the first three years on a live financial advisory platform.

    See how
  • 50%

    shorter release cycle

    Storee Construction, 2024 to 2026. Four ASP.NET applications onto one .NET 10 platform on Azure, with a four-person team I hired and mentored.

    See how

01Verified

Steven Stout

A real person, and the work is mine.

  • Identity

    Checked by LinkedIn, not by me.

    LinkedIn verified my government ID.

  • Running system

    You are looking at it.

    Version 1.0.5.273 is live. Nothing ships unless it passes the automated gates first.

That's who I am. Here's how I work.

02Strengths

Ten strengths, each with the proof beside it. The numbers match my resume and LinkedIn, and the live ones are read from this site as you look.

  • 01

    Keeps production alive

    200+ releases on a live financial platform, and none took it down. Sole engineer for the first three years.

    See the Conway work

  • 02

    Simplifies messy systems

    Four ASP.NET applications onto one .NET 10 platform on Azure, and a release cycle 50% shorter.

    See the Storee work

  • 03

    Marries dev and infrastructure

    Blue-green releases at Storee that flipped in about 5 seconds with nobody signed out, and Azure Front Door at two employers.

    See this site's cloud

  • 04

    Designs data that holds up

    White-label clients on one shared database, the isolation built into the data, and no cross-client issues.

    See the Conway work

  • 05

    Keeps AI-written code honest

    15 quality numbers that may only improve: 273 releases in a row with none worse.

    See the quality numbers

  • 06

    Resourceful

    $30,000+ cut from Azure and vendor spend at Conway. This site's Azure bill is public, resource by resource.

    See the bill

  • 07

    Builds people up

    Hired and mentored a four-person team. 13 colleagues recommend me by name.

    Read the recommendations

  • 08

    Takes ideas to production

    This site: designed, built and run solo, with 352 versions measured through one gate.

    How it was built

  • 09

    Writes clearly

    Posts on real engineering problems, in plain words.

    Read the blog

  • 10

    Owns decisions

    153 decision records, each with its tradeoff and the call I made.

    See the decision records

Built with AI. Gated so quality never slides.

Steven Stout’s showcase: a used-vehicle auction on .NET and React, built and run by one engineer, live on Azure, with its decisions written down.

No quality number has gotten worse at any release since 1.0.5.1 on 10 November: 273 releases in a row.

One engineer, an AI agent and a gate that checks 15 quality numbers on every release. 352 versions measured, with every result public, the worst days included.

82 releases in the last 7 days, each through the same gate.

Async methods with no CancellationToken, may only fall

11091.0.3.1391.0.5.2731.0.4.115, the ratchet
Every number, on the Quality page

TheYard, right nowLive

Answering in

unread

02505007501,000

server time at p95, the usual five minutes of the last day.

Azure this month

unread

the bill, by resource, read from Azure. The Admin tab shows every line.

Since the last roll

unread

 

rolled in place by the pipeline, behind one gate.

People who have visited

unread

30 days agotoday

Scanners, my own tools' and my own reads left out.

03Start here

04Where teams are heading

How I see engineering with AI, and the setup on this site that backs it.

AI-augmented teams · Architecture and ownership

AI writes more of the code. Someone still has to own what ships.

Teams are going to be heavily AI-augmented. That moves the senior job toward architecture and technical ownership: deciding what to build in pieces small enough to verify, and owning what ships.

  • Task tracking will get automated too. Judgment stays human: seeing a design fail at scale before it does.
  • On this site the AI's first design held the whole catalogue in memory. I caught it when the App Service plan hit 82 per cent and moved the work to the store.

What the AI wrote, what I decided

07Tech stack

  •    
  •    
  •    

Read from the build, never typed by hand

What TheYard runs on

What we use, where it runs, its AWS twin, the version as built, and the file that proves it.

Cloud patterns, not one vendor: every Azure piece in this stack has a named AWS twin. Mapped, not yet run on AWS.

  • .NET 1114 projects
  • React 19.3TypeScript 7.0
  • Azure9 Bicep files
  • 11GitHub Actions workflows
The whole stack, with the file that proves each line

The last release the gate stopped was 1.0.5.258 on 2 December, at its browser 1 of 2 job.

08How it is built

09How it is run

10Who and why

Next step

11What has to work, where is it today, and what does success look like?

Book 20 minutes opens an email to me with those three questions in it, and I answer with a time.

Book 20 minutes

Your email app should have opened with this message. If it did not, copy it and send it from any mailbox.

Or message me on LinkedIn