🔷 .NET / C# Integration Guide
Learn how to instrument your .NET and ASP.NET Core applications with TraceKit APM for OpenTelemetry-based distributed tracing.
OpenTelemetry-Native SDK!
TraceKit .NET SDK is built on OpenTelemetry 1.10.0 for maximum compatibility. Get distributed tracing, metrics, and code monitoring with zero-configuration middleware for ASP.NET Core!
Prerequisites
- • .NET 8.0 or higher
- • ASP.NET Core 8.0+ (for web applications)
- • An active TraceKit account
- • A generated API key from the API Keys page
🔍 What Gets Traced Automatically?
With TraceKit .NET SDK installed, these operations are traced automatically:
| Component | What's Captured | Auto-Traced? |
|---|---|---|
| HTTP Requests | Route, method, status, duration, headers | ✓ Yes |
| HttpClient Calls | Outbound HTTP requests with propagation | ✓ Yes |
| Exceptions | Type, message, stack trace, context | ✓ Yes |
| Custom Spans | Manual instrumentation (optional) | Manual |
📦 Installation
Install the TraceKit .NET SDK via NuGet:
For ASP.NET Core
dotnet add package TraceKit.AspNetCoreFor Vanilla .NET
dotnet add package TraceKit.Core⚡ ASP.NET Core Setup
Program.cs
Add TraceKit to your application in Program.cs:
using TraceKit.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
// Add TraceKit
builder.Services.AddTracekit(options =>
{
options.ApiKey = Environment.GetEnvironmentVariable("TRACEKIT_API_KEY");
options.ServiceName = "my-service";
options.Environment = "production";
options.EnableCodeMonitoring = true;
});
var app = builder.Build();
// Use TraceKit middleware
app.UseTracekit();
app.MapGet("/api/users", (TracekitSDK sdk) =>
{
var counter = sdk.Counter("http.requests.total");
counter.Inc();
return Results.Ok(new { message = "Hello" });
});
app.Run();That's It!
All HTTP requests and HttpClient calls are now automatically traced with distributed context propagation!
⚙️ Configuration
appsettings.json
Configure TraceKit in your appsettings.json:
{
"Tracekit": {
"Enabled": true,
"ApiKey": "ctxio_abc123...",
"ServiceName": "my-api",
"Environment": "production",
"Endpoint": "https://app.tracekit.dev",
"EnableCodeMonitoring": true
}
}Configuration Options
| Option | Type | Description |
|---|---|---|
| ApiKey | string | Your TraceKit API key (required) |
| ServiceName | string | Name of your service |
| Environment | string | Environment (dev, staging, prod) |
| Endpoint | string | TraceKit endpoint URL |
| EnableCodeMonitoring | bool | Enable live debugging snapshots |
📸 Code Monitoring (Live Debugging)
Production-Safe Live Debugging
Capture variable state, stack traces, and request context at any point in your code without redeployment. Perfect for debugging production issues!
→ Full Code Monitoring DocumentationCapture Snapshots
Use CaptureSnapshot to capture runtime state:
app.MapPost("/api/checkout", (CheckoutRequest request, TracekitSDK sdk) =>
{
// Capture snapshot with variable state
sdk.CaptureSnapshot("checkout-start", new()
{
["userId"] = request.UserId,
["amount"] = request.Amount,
["status"] = "processing"
});
// Your business logic here
var result = ProcessCheckout(request);
return Results.Ok(result);
});Automatic Security Scanning
TraceKit automatically detects and redacts sensitive data like credit cards, SSNs, API keys, and passwords before sending snapshots.
🖥️ Local Development UI
Automatic Local UI Detection
When developing locally, TraceKit automatically sends traces to localhost:5173 (TraceKit UI) if available.
Run the TraceKit UI locally to see traces in real-time without an API key!
🔧 Manual Instrumentation
For custom spans, use the injected TracekitSDK:
app.MapGet("/api/products/{id}", async (int id, TracekitSDK sdk) =>
{
using var span = sdk.StartSpan("fetch-product", new()
{
["product.id"] = id
});
try
{
var product = await GetProductFromDatabase(id);
span.SetAttribute("product.price", product.Price);
return Results.Ok(product);
}
catch (Exception ex)
{
span.RecordException(ex);
span.SetStatus("error");
throw;
}
});Automatic Context Propagation
TraceKit automatically propagates trace context through ASP.NET Core's dependency injection and async/await chains.
🌍 Environment Variables
You can also configure TraceKit using environment variables:
TRACEKIT_API_KEY=ctxio_your_generated_api_key_here
TRACEKIT_ENDPOINT=https://app.tracekit.dev
TRACEKIT_SERVICE_NAME=my-dotnet-app
TRACEKIT_ENVIRONMENT=production
TRACEKIT_CODE_MONITORING_ENABLED=true📝 Complete Example
Here's a complete example with custom spans, metrics, and code monitoring:
using TraceKit.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
// Add TraceKit
builder.Services.AddTracekit(options =>
{
options.ApiKey = Environment.GetEnvironmentVariable("TRACEKIT_API_KEY");
options.ServiceName = "express-api";
options.Environment = "production";
options.Endpoint = "https://app.tracekit.dev";
options.EnableCodeMonitoring = true;
});
var app = builder.Build();
app.UseTracekit();
// Routes - automatically traced!
app.MapGet("/api/users", (TracekitSDK sdk) =>
{
var users = new[]
{
new { Id = "1", Name = "Alice", Email = "[email protected]" },
new { Id = "2", Name = "Bob", Email = "[email protected]" }
};
return Results.Ok(users);
});
// Manual span example
app.MapPost("/api/users", async (UserRequest request, TracekitSDK sdk) =>
{
using var span = sdk.StartSpan("create-user", new()
{
["user.email"] = request.Email
});
try
{
// Simulate user creation
var user = new
{
Id = Guid.NewGuid().ToString(),
Name = request.Name,
Email = request.Email
};
// Simulate async operation
await Task.Delay(100);
span.SetAttribute("user.id", user.Id);
return Results.Created($"/api/users/{user.Id}", user);
}
catch (Exception ex)
{
span.RecordException(ex);
span.SetStatus("error");
return Results.Problem("Failed to create user");
}
});
app.Run();
record UserRequest(string Name, string Email);
record CheckoutRequest(string UserId, decimal Amount);📊 Custom Metrics
TraceKit provides a simple metrics API for tracking application performance:
Counter
For tracking cumulative values that only go up:
var sdk = TracekitSDK.Create(config);
// Create a counter with optional tags
var counter = sdk.Counter("http.requests.total",
new() { ["service"] = "api" });
// Increment by 1
counter.Inc();
// Add a specific value
counter.Add(5);Gauge
For tracking values that can go up or down:
// Create a gauge
var gauge = sdk.Gauge("http.connections.active");
// Set to specific value
gauge.Set(42);
// Increment/decrement
gauge.Inc();
gauge.Dec();Histogram
For tracking distributions of values:
// Create a histogram with tags
var histogram = sdk.Histogram("http.request.duration",
new() { ["unit"] = "ms" });
// Record values
histogram.Record(45.2);
histogram.Record(123.5);🔍 Troubleshooting
Traces not appearing?
- • Check that
app.UseTracekit()is called inProgram.cs - • Verify your API key is correct
- • Check your console for error messages
- • Ensure the endpoint URL is correct
Dependency injection not working?
- • Ensure
builder.Services.AddTracekit()is called before building the app - • Make sure you're injecting
TracekitSDKin your controllers/services
Performance concerns?
- • TraceKit uses OpenTelemetry's efficient batching
- • Overhead is typically <1ms per request
- • Consider reducing sampling rate for very high traffic services
🚀 Next Steps
Code Monitoring
Learn about live debugging with production-safe snapshots
Set Up Alerts
Configure alerts for errors, performance issues, and custom metrics
View Your Traces
Explore distributed traces and find performance bottlenecks
Create Dashboards
Build custom dashboards with metrics and visualizations