Skip to content

Instantly share code, notes, and snippets.

@BadgerCode
Created November 20, 2025 23:10
Show Gist options
  • Select an option

  • Save BadgerCode/4f88fb3077910701ca35ea4bdad717d0 to your computer and use it in GitHub Desktop.

Select an option

Save BadgerCode/4f88fb3077910701ca35ea4bdad717d0 to your computer and use it in GitHub Desktop.
Application insights custom request tracking logs
// Allows logging custom entries to application insights' "request" log entries
// Includes duration, your operation name, success true/false, custom result codes, custom telemetry properties, exception tracking
// https://learn.microsoft.com/en-us/azure/azure-monitor/profiler/profiler-trackrequests
// Usage
/*
using var requestLog = new RequestLog(telemetryClient, "MyOperation");
try
{
requestLog.WithProperty("ImportantProperty", "example example");
requestLog.WithProperty("AnotherProperty", 1234.ToString());
requestLog.WithProperty("MyImportantID", Guid.NewGuid().ToString());
// Do some work...
requestLog.Complete();
}
catch (Exception e)
{
requestLog.Fail(e);
throw;
}
*/
public class RequestLog : IDisposable
{
private TelemetryClient _telemetryClient;
private IOperationHolder<RequestTelemetry> _operation;
public RequestLog(TelemetryClient telemetryClient, string operationName)
{
_telemetryClient = telemetryClient;
_operation = telemetryClient.StartOperation<RequestTelemetry>(operationName);
}
public RequestLog WithProperty(string key, string value)
{
_operation.Telemetry.Properties[key] = value;
return this;
}
public RequestLog Complete(string status = "Success")
{
_operation.Telemetry.Success = true;
_operation.Telemetry.ResponseCode = status;
return this;
}
public RequestLog Fail(string status)
{
_operation.Telemetry.Success = false;
_operation.Telemetry.ResponseCode = status;
return this;
}
public RequestLog Fail(Exception e)
{
Fail("Exception");
_operation.Telemetry.Properties["Exception"] = e.ToString();
return this;
}
public void Dispose()
{
_telemetryClient.StopOperation(_operation);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment