The official Treblle SDK for .NET Core. Seamlessly integrate Treblle to monitor all your API endpoints, capture errors, and secure sensitive data — with zero-configuration auto-discovery.
Treblle with .NET Core
Requirements
| Requirement | Version |
|---|---|
| .NET | 6.0+ |
| ASP.NET Core | 6.0+ |
| C# | 10.0+ |
Supported Platforms:
- Windows, macOS, Linux
- Docker containers
- Azure, AWS, Google Cloud
- Any hosting platform supporting .NET 8+
Supported API Types:
- REST APIs with Controllers
- Minimal APIs
- Web APIs
- Mixed controller/minimal API applications
Dependencies:
Microsoft.AspNetCore.App(framework reference)System.Text.Json6.0+- No external dependencies required
Installation
Step 1 — Install the package:
dotnet add package Treblle.Net.CoreStep 2 — Get your credentials:
Get your SDK Token and API Key from the Treblle Dashboard .
Step 3 — Configure Treblle:
Treblle v2.0 supports automatic endpoint discovery, so you no longer need to manually add [Treblle] attributes. Choose from these configuration options:
Option A: Environment Variables (Recommended for Production)
export TREBLLE_SDK_TOKEN=your_sdk_token
export TREBLLE_API_KEY=your_api_keyThen use zero-configuration setup:
using Treblle.Net.Core;
// Register Treblle Services
builder.Services.AddTreblle();
// Build your application
var app = builder.Build();
// Enable the Treblle Middleware
app.UseTreblle();Note
Where to place this code:
- Program.cs (new minimal hosting model): Add
builder.Services.AddTreblle()beforebuilder.Build()andapp.UseTreblle()aftervar app = builder.Build() - Startup.cs (legacy): Add
services.AddTreblle()inConfigureServices()andapp.UseTreblle()inConfigure() - Web API templates: Place after authentication/authorization middleware but before routing
Using .env Files with DotNetEnv
For development environments, you can use .env files with the DotNetEnv package:
dotnet add package DotNetEnvCreate a .env file in your project root:
TREBLLE_SDK_TOKEN=your_sdk_token
TREBLLE_API_KEY=your_api_keyThen load the environment variables in your Program.cs:
using Treblle.Net.Core;
using DotNetEnv;
// Load environment variables from .env file
Env.Load();
// Register Treblle Services
builder.Services.AddTreblle();
var app = builder.Build();
app.UseTreblle();Note
The DotNetEnv package is only needed if you want to load variables from .env files. Standard environment variables work without any additional packages.
Option B: appsettings.json
{
"Treblle": {
"SdkToken": "your_sdk_token",
"ApiKey": "your_api_key"
}
}using Treblle.Net.Core;
builder.Services.AddTreblle();
var app = builder.Build();
app.UseTreblle();Option C: Manual Configuration
using Treblle.Net.Core;
builder.Services.AddTreblle("your_sdk_token", "your_api_key");
var app = builder.Build();
app.UseTreblle();That’s it! Treblle will now automatically track all your API endpoints.
Multi-Environment Configuration
For applications with multiple environments (Development, Staging, Production), use environment-specific appsettings.{Environment}.json files:
appsettings.Development.json:
{
"Treblle": {
"SdkToken": "dev_sdk_token",
"ApiKey": "dev_api_key"
}
}appsettings.Production.json:
{
"Treblle": {
"SdkToken": "prod_sdk_token",
"ApiKey": "prod_api_key"
}
}Program.cs (works for .NET 6, 8, and 9+):
using Treblle.Net.Core;
var builder = WebApplication.CreateBuilder(args);
// Auto-detects credentials from appsettings.{Environment}.json
builder.Services.AddTreblle();
// OR explicitly read from configuration
builder.Services.AddTreblle(
builder.Configuration["Treblle:SdkToken"]!,
builder.Configuration["Treblle:ApiKey"]!
);
var app = builder.Build();
app.UseTreblle();
app.Run();Legacy Startup.cs (still supported):
using Treblle.Net.Core;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Auto-detects credentials from appsettings.{Environment}.json
services.AddTreblle();
}
public void Configure(IApplicationBuilder app)
{
app.UseTreblle();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}Caution
Do NOT use app.config files. The SDK only reads from:
- Environment variables:
TREBLLE_SDK_TOKENandTREBLLE_API_KEY - appsettings.json:
Treblle:SdkTokenandTreblle:ApiKey - Manual configuration via
AddTreblle(sdkToken, apiKey)parameters
Configuration Options
Option
Default and Description
ExcludedPaths
null - Exclude specific paths or endpoints from Treblle
DebugMode
false - Enable detailed logging for troubleshooting
DisableMasking
false - Disable data masking if not needed
CustomIngressEndpoint
null - Custom endpoint URL for sending telemetry data
Example with all options:
using Treblle.Net.Core;
builder.Services.AddTreblle(options =>
{
options.ExcludedPaths = new[] { "/health", "/admin/*", "/swagger/*" };
options.DebugMode = true;
options.DisableMasking = false;
});
var app = builder.Build();
app.UseTreblle();Debug Mode
For troubleshooting and development purposes, you can enable debug mode to get detailed logging about SDK operations:
using Treblle.Net.Core;
// Option 1: Via AddTreblle parameter
builder.Services.AddTreblle("YOUR_SDK_TOKEN", "YOUR_API_KEY", null, disableMasking: false, debugMode: true);
// Option 2: Via configuration options
builder.Services.AddTreblle(options =>
{
options.DebugMode = true;
});
var app = builder.Build();
app.UseTreblle();All debug logs are prefixed with [TREBLLE]: and use LogDebug level. To see them in the console, add this to your appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Treblle.Net.Core": "Debug"
}
}
}Note
Debug mode should only be enabled in development or staging environments as it increases log verbosity.
Custom Ingress Endpoint
If you need to route data through a specific regional endpoint or a custom ingress URL:
Option A: Environment Variable
export TREBLLE_CUSTOM_INGRESS_ENDPOINT=https://ingress-eu.treblle.comOption B: appsettings.json
{
"Treblle": {
"SdkToken": "your_sdk_token",
"ApiKey": "your_api_key",
"CustomIngressEndpoint": "https://ingress-eu.treblle.com"
}
}Option C: Programmatic Configuration
using Treblle.Net.Core;
builder.Services.AddTreblle(options =>
{
options.CustomIngressEndpoint = "https://ingress-eu.treblle.com";
});
var app = builder.Build();
app.UseTreblle();Per-Endpoint API Key Override
If you need a specific controller or endpoint to report to a different Treblle project, pass an API key directly to the [Treblle] attribute.
Option A: Hardcoded API key
[Treblle("your_per_endpoint_api_key")]
public class OrdersController : ControllerBase { }Option B: Resolved from environment variable at startup
Useful when the key differs per environment (development, staging, production):
[Treblle(keyEnvVarName: "ORDERS_API_KEY")]
public class OrdersController : ControllerBase { }
[Treblle(keyEnvVarName: "PAYMENTS_API_KEY")]
public class PaymentsController : ControllerBase { }Set the corresponding variables in your .env file or as OS environment variables:
ORDERS_API_KEY=your_orders_project_id
PAYMENTS_API_KEY=your_payments_project_idNote
The environment variable is resolved once at application startup — there is no per-request overhead. If the variable is not set, the request falls back to the globally configured API key.
app.UseTreblle() must come after app.UseRouting() for this to work.
Excluding Endpoints or Paths
By default, Treblle automatically tracks all endpoints without requiring manual [Treblle] attributes. You can exclude specific paths using the ExcludedPaths configuration:
using Treblle.Net.Core;
builder.Services.AddTreblle("YOUR_SDK_TOKEN", "YOUR_API_KEY", options =>
{
options.ExcludedPaths = new[] { "/health", "/metrics", "/admin/*" };
});
var app = builder.Build();
app.UseTreblle();Advanced exclusion patterns:
builder.Services.AddTreblle("YOUR_SDK_TOKEN", "YOUR_API_KEY", options =>
{
options.ExcludedPaths = new[]
{
"/health", // Exact match
"/metrics", // Exact match
"/admin/*", // Wildcard: excludes /admin/users, /admin/settings, etc.
"/api/v*/internal", // Complex wildcard: excludes /api/v1/internal, /api/v2/internal, etc.
"/debug/*", // Wildcard: excludes all debug endpoints
"/_*" // Wildcard: excludes all endpoints starting with underscore
};
});Pattern matching is case-insensitive and supports * (any number of characters) and ? (exactly one character) wildcards with performance-optimized regex compilation and result caching.
Masking Data
Treblle automatically masks sensitive fields in request and response bodies. The following fields are masked by default:
password, pwd, secret, password_confirmation, passwordConfirmation, cc, card_number, cardNumber, ccv, ssn, credit_score, creditScore
To expand the list of masked fields, pass custom field names and maskers to AddTreblle:
using Treblle.Net.Core;
builder.Services.AddTreblle(
builder.Configuration["Treblle:SdkToken"],
builder.Configuration["Treblle:ApiKey"],
new Dictionary<string, string>()
{
{ "customercreditCard", "CreditCardMasker" },
{ "firstName", "DefaultStringMasker" }
}
);
var app = builder.Build();
app.UseTreblle();Available maskers:
// DefaultStringMasker
masker.Mask("Hello World"); // output: ***********
masker.Mask("1234-5678"); // output: **********
// CreditCardMasker
masker.Mask("1234-5678-1234-5678"); // output: ****-****-****-5678
masker.Mask("1234567812345678"); // output: ****-****-****-5678
// DateMasker
masker.Mask("24-12-2024"); // output: 24-12-****
// EmailMasker
masker.Mask("user123@example.com"); // output: *******@example.com
// PostalCodeMasker
masker.Mask("SW1A 1AA"); // output: SW1A ***
// SocialSecurityMasker
masker.Mask("123-45-6789"); // output: ***-**-6789You can also implement custom maskers by extending DefaultStringMasker and implementing IStringMasker.
Disabling Data Masking
For high-volume scenarios where data masking is not required, you can disable it entirely:
using Treblle.Net.Core;
// Option 1: Via AddTreblle parameter
builder.Services.AddTreblle("YOUR_SDK_TOKEN", "YOUR_API_KEY", null, disableMasking: true);
// Option 2: Via configuration options
builder.Services.AddTreblle(options =>
{
options.DisableMasking = true;
});
var app = builder.Build();
app.UseTreblle();Note
Disabling masking can reduce memory usage by up to 70% for large payloads, as it skips JSON parsing, object tree creation, and field processing operations. This is particularly beneficial for APIs handling large response bodies or high request volumes.
SQL Query Capture
The SDK automatically captures SQL queries executed during each API request and includes them in the telemetry payload sent to Treblle. This works out of the box with no configuration required.
Treblle listens to EF Core’s diagnostic events . When EF Core executes a database command, the SDK captures the SQL and execution time and associates them with the current HTTP request.
Each query entry in the data.queries array contains:
sql: The SQL query with?placeholders — parameter values are not capturedtime: Execution time in milliseconds
Exception Handling
By default, Treblle captures and reports exceptions that occur during request processing. To disable this behavior:
app.UseTreblle(useExceptionHandler: false);Caution
When the exception handler is disabled, requests that result in exceptions will not appear on your Treblle dashboard.
You may want to disable Treblle’s exception handler if you’re using a custom exception handling middleware or have specific exception handling requirements.
Disabling Default .NET HTTP Logging
You may see HTTP client logging messages like:
info: System.Net.Http.HttpClient.Treblle.LogicalHandler[100]
Start processing HTTP request POST https://rocknrolla.treblle.com/These are normal messages showing Treblle successfully sending data. To reduce their verbosity, configure logging in appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"System.Net.Http.HttpClient.Treblle": "Warning"
}
}
}Or in Program.cs:
builder.Logging.AddFilter("System.Net.Http.HttpClient.Treblle", LogLevel.Warning);Upgrading to v2.0
Treblle .NET Core v2.0 introduces major improvements with breaking changes.
What’s new in v2.0:
- Zero-Configuration Auto-Discovery — No more manual
[Treblle]attributes required - Auto-Configuration — Automatic credential detection from environment/config
- Smart Path Exclusions — Wildcard patterns like
/admin/*,/api/v*/internal - Enhanced Debug Mode — Comprehensive logging for troubleshooting
- Performance Optimizations — Cached pattern matching, memory improvements
Step 1: Update Package Reference
<PackageReference Include="Treblle.Net.Core" Version="2.0.0" />Step 2: Update SDK Initialization
// v1.x
builder.Services.AddTreblle(
builder.Configuration["Treblle:ApiKey"],
builder.Configuration["Treblle:ProjectId"]);
// v2.0
builder.Services.AddTreblle();Step 3: Update Naming Conventions
v1.x appsettings.json:
{
"Treblle": {
"ApiKey": "your_api_key",
"ProjectId": "your_project_id"
}
}v2.0 appsettings.json:
{
"Treblle": {
"SdkToken": "your_sdk_token",
"ApiKey": "your_api_key"
}
}Step 4: Remove Manual Attributes
// v1.x
[Treblle]
public class ProductsController : ControllerBase
{
[Treblle]
public IActionResult GetProducts() => Ok();
}
// v2.0 — no attributes needed, all endpoints are tracked automatically
public class ProductsController : ControllerBase
{
public IActionResult GetProducts() => Ok();
}Tip
If you have problems of any kind, feel free to reach out via email support@treblle.com and we’ll do our best to help you out.