Removing Static File traces from ASP.NET Core

When you’re adding tracing into your ASP.NET applications, one important thing to consider is effective management of the volume of spans you’re producing, as the more you output the more it will cost to store it, or query it. The first port of call for most people is to looking at Sampling, however, you can do some thing before that which are really low effort.

One of the things we get out of the box with ASP.NET Core is the ability to serve static pages. The handler here has little logic, and therefore most of the benefit we get from tracing is lost. This is especially true if you’re fronting your site with CDN or web accelerator type technology.

When we’re using tracing locally in a Observability-driven development (ODD) mode, they’re next to useless, and make it harder to see the true request when looking at our traces.

Lucky for us, with .NET Core, Microsoft have added extension points everywhere. On such extension point is in StaticFileOptions. This is a class that manages how the static files are served and includes options like where the files should be sourced from and the paths etc. The other thing it allows us to do, is to access the response before it’s sent to the client. This ability also allows us to do things with the Span that’s created too.

The option we’re looking for is OnPrepareResponse. What we’re going to do is couple that with a property within Activity that will stop the activity being sent to the exporter. IsDataRequested is a property on each Activity that OpenTelemetry uses determine whether to forward that property on, therefore by us setting this, we can stop it from making it to the exporter.

Here’s the code you can add to configure the options. For bonus points, you could tweak this by environment if it is important in production, but not in development.

builder.Services.Configure<StaticFileOptions>(o => {
    o.OnPrepareResponse = (ctx) => {
        if (Activity.Current != null)
            Activity.Current.IsAllDataRequested = false;
    };
});

Setting this property on the ambient Activity will ensure that it’s not output to the OpenTelemetry Exporters, and that leaves you with the important information being available in your Observability Backend.

Conclusion

Think about whether having spans for your static files is going to be providing value, and if it isn’t, then kill it and save the volume. Think about whether you can monitor these things separately in your CDN, or you load balancer logs, I did a post for Honeycomb about ingesting load balancer logs from AppService which could be a better fit for that kind of monitoring.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Website Built with WordPress.com.

Up ↑

%d bloggers like this: