boltZharp Docs
hexagonSDKs

.NET

The Zharp .NET SDK traces every request your ASP.NET Core, ASP.NET, worker or serverless .NET app handles, and sends its errors — with the code that ran — and failed queries, from one line.

info
Zharp 0.1.0

This SDK is new, and its API may still change before 1.0. Requires .NET 8, 10 or 11 — or .NET Framework 4.6.2 or later for classic ASP.NET.

NuGet packages built on OpenTelemetry .NET, with Zharp's settings and additions. Pick the one for your app; the framework and serverless packages bring Zharp, the core, with them.

PackageFor
Zharp.AspNetCoreASP.NET Core (.NET 8, 10, 11), including ASP.NET Core on Lambda.
ZharpAny .NET app: Generic Host workers, console apps, .NET/HTTP (logs and errors only). .NET 8+, .NET Framework 4.6.2+, .NET Standard 2.0.
Zharp.AspNetClassic ASP.NET on .NET Framework: MVC 5, WebForms.
Zharp.AspNet.WebApiASP.NET Web API 2 on .NET Framework (brings Zharp.AspNet).
Zharp.AwsLambda.NET on AWS Lambda.
Zharp.GoogleCloudFunctions.NET on Google Cloud Run functions (Cloud Functions).
Zharp.BuildOptional: uploads a source bundle for builds that don't embed their sources.

Install

For ASP.NET Core:

dotnet add package Zharp.AspNetCore

The other packages are below, with their app. Then add <EmbedAllSources> to the project, so errors show the code that ran — see The code that ran.

Initialize

ASP.NET Core

One line in Program.cs, and the app's key from its settings in Zharp:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddZharp();
// appsettings.json — or ZHARP_KEY, ZHARP_SERVICE… in the environment
"Zharp": {
  "Key": "zpk_…",
  "Service": "orders-api",
  "Environment": "production"
}

Requests are traced and named by route (GET /orders/{id}), and each failure is reported once — even when UseExceptionHandler or the developer exception page handled it. Without a key it sends nothing. The app's setup page in Zharp shows these steps with the key, service and environment filled in.

ASP.NET (classic, .NET Framework)

MVC 5 and WebForms, on .NET Framework 4.6.2 or later. In the Package Manager Console:

Install-Package Zharp.AspNet
<!-- Web.config -->
<appSettings>
  <add key="Zharp:Key" value="zpk_…" />
  <add key="Zharp:Service" value="orders-web" />
  <add key="Zharp:Environment" value="production" />
</appSettings>

The package registers its HTTP modules itself, so <modules> stays as it is. What reaches Application_Error is reported once.

ASP.NET Web API 2

Web API 2 handles its controllers' exceptions itself, before Application_Error. Use Zharp.AspNet.WebApi (it brings Zharp.AspNet) and add one line to WebApiConfig.Register:

Install-Package Zharp.AspNet.WebApi
// App_Start/WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
    config.AddZharp();
    // …your routes, as they are
}

.NET: workers and console apps

On the Generic Host, the same line with the Zharp package; the key goes in appsettings.json as above:

dotnet add package Zharp

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddZharp();

In a plain Main:

using var zharp = Zharp.ZharpSdk.Init(o => o.Key = "zpk_…");   // or ZHARP_KEY in the environment
using var loggerFactory = LoggerFactory.Create(b => b.AddConsole().AddZharp());

using (Zharp.ZharpSdk.StartSpan("import-orders"))
{
    // a job: its logs, queries and errors grouped as one trace
}

Unhandled exceptions are reported before the process ends, and disposing zharp sends what's waiting. Only what you wrap in StartSpan (and the HTTP calls and queries inside it) is traced outside a host.

.NET/HTTP: logs and errors only

using var zharp = Zharp.ZharpSdk.Init(o =>
{
    o.Key = "zpk_…";
    o.Tracing = false;
    o.Logs = true;
});

AWS Lambda

dotnet add package Zharp.AwsLambda
public class Function
{
    static readonly Func<Order, ILambdaContext, Task<Receipt>> Handle =
        Zharp.AwsLambda.ZharpLambda.Wrap<Order, Receipt>(PlaceAsync);

    public Task<Receipt> Handler(Order order, ILambdaContext context) => Handle(order, context);

    static async Task<Receipt> PlaceAsync(Order order, ILambdaContext context)
    {
        // your handler, as it is
    }
}

Set ZHARP_KEY in the function's environment. Each invocation is a span (the first marked faas.coldstart), what the handler throws is reported once, and everything is sent before the handler returns. ASP.NET Core on Lambda (AddAWSLambdaHosting) uses Zharp.AspNetCore and AddZharp() instead.

Google Cloud Functions

dotnet add package Zharp.GoogleCloudFunctions
[assembly: FunctionsStartup(typeof(Zharp.GoogleCloudFunctions.ZharpStartup))]
gcloud functions deploy orders --set-env-vars ZHARP_KEY=zpk_…,ZHARP_ENVIRONMENT=production

Invocations are spans named by the function, and everything is sent before the response.

Logs

Off by default. Console lines written during a request end with its trace_id=… span_id=…, and where the Zharp agent reads your app's output, it brings those lines in and links each one to its request — one copy, nothing sent twice. ZHARP_LOG_CORRELATION=false turns the stamp off.

info: Orders.Controllers.OrdersController[0]
      Order 42 placed trace_id=4bf92f3577b34da6a3ce929d0e0e4736 span_id=00f067aa0ba902b7

To send ILogger records straight to Zharp instead, with their level, category and exception:

ZHARP_LOGS=true

Either way, exceptions logged at Error or above are reported as errors. Outside a host, loggers from ZharpSdk.LoggerFactory, or from a factory with .AddZharp(), are the ones that send.

Serilog

Add the ids to the output template for the same stamp:

.WriteTo.Console(outputTemplate:
    "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} trace_id={TraceId} span_id={SpanId}{NewLine}{Exception}")

With ZHARP_LOGS=true, let Serilog's events through to ILogger providers:

builder.Host.UseSerilog((context, config) => config.ReadFrom.Configuration(context.Configuration),
    writeToProviders: true);   // with ZHARP_LOGS=true, Serilog's events reach Zharp through ILogger

Logs only

If you only want logs, turn tracing off. Logs, errors, and the user and session they belong to are still sent; no spans are recorded and no trace headers are added to outgoing requests. A request from a Zharp front end is still read, so its logs keep the caller's user, session and trace ID.

using var zharp = Zharp.ZharpSdk.Init(o =>
{
    o.Key = "zpk_…";
    o.Service = "checkout-api";
    o.Tracing = false;
    o.Logs = true;   // ILogger records, sent straight to Zharp
});
using var loggerFactory = LoggerFactory.Create(b => b.AddConsole().AddZharp());

Or leave the code as it is and set ZHARP_TRACING=false ZHARP_LOGS=true in the environment.

The logs show on the Logs page under the service name, and on the app's Logs tab with the user and session of each line. The key comes from an app — see Get a key. To add tracing later, remove the option; nothing else changes.

Errors

A request that fails is reported once, with its stack — not again for every span the exception crossed, nor for the framework's log line about it. Unhandled exceptions are reported, and exceptions you log at Error are reported as handled. Report one yourself:

try
{
    await Charge(order);
}
catch (PaymentException e)
{
    Zharp.ZharpSdk.CaptureException(e);   // reported as handled, in this request's trace
}

Readable stack traces

Nothing to upload for the stack: .NET frames already name your types, methods, files and lines, and issues are grouped by them.

The code that ran: embedded sources

Errors also show the source around each of your frames. Add to the project file:

<!-- your .csproj -->
<PropertyGroup>
  <EmbedAllSources>true</EmbedAllSources>
</PropertyGroup>

The build then carries its .cs files inside the PDB, and the SDK reads the lines around each error from it on your own server and sends them: nothing to upload, and always the exact code that ran. Ship the .pdb files with the app (dotnet publish does by default). It needs a PDB, so not with <DebugType>none</DebugType>. On .NET Framework 4.7.2 and later the portable PDBs are read as they are; on 4.6.2–4.7.1 use <DebugType>full</DebugType>. ZHARP_CAPTURE_SOURCE_CONTEXT=false turns it off.

Builds that can't embed sources: Zharp.Build

Reference Zharp.Build, and each Release build uploads the project's .cs files under the ID of the PDB it wrote; errors carry that ID (zharp.build_id), so the code shown is that build's. A linked repository works too.

<!-- your .csproj -->
<ItemGroup>
  <PackageReference Include="Zharp.Build" Version="0.1.0" PrivateAssets="all" />
</ItemGroup>
<PropertyGroup>
  <ZharpAppId>123</ZharpAppId>   <!-- the application's ID in Zharp; or ZHARP_APP_ID -->
</PropertyGroup>

The upload needs a workspace API key with the artifacts:write scope in ZHARP_AUTH_TOKEN, set in CI — see The upload key. Without one the build only prints what it would upload. ZHARP_URL (or <ZharpUrl>) points at another Zharp; <ZharpUploadSources>false</ZharpUploadSources> turns it off. It needs a PDB as well.

Tracing

ASP.NET Core and classic ASP.NET requests, HttpClient calls, and EF Core, Npgsql, SqlClient, MySqlConnector and SQLite queries are traced. Each request continues the caller's trace, including the browser SDK's. Add your own spans with ZharpSdk.StartSpan.

Request and response headers

Every request and response header is recorded, so a failed request shows what was sent and what came back. Secret ones —Authorization, Cookie, API keys, tokens — are recorded as [Filtered]: you see one was sent, never its value. ZHARP_CAPTURE_HEADERS_REDACT adds more names; ZHARP_CAPTURE_HEADERS=false turns them off.

Database queries

A query that fails is reported with its statement, the database and its error code, with a named type — Postgres's UniqueViolation, SQL Server's UniqueKeyViolation. Row values are never sent. ZHARP_CAPTURE_QUERY_ERRORS=false turns it off.

User context

Requests from the Zharp browser and mobile SDKs carry the user and session; the SDK puts them on every span, error and log of the request. When the server knows better, set it per request:

// Program.cs, after app.UseAuthentication()
app.Use(async (context, next) =>
{
    if (context.User.Identity?.IsAuthenticated == true)
        Zharp.ZharpSdk.SetUser(
            context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value,
            context.User.FindFirst(ClaimTypes.Email)?.Value);
    await next();
});

The rest of the API:

Zharp.ZharpSdk.SetUser(id, email, name);       // this request's user (the whole process outside requests)
Zharp.ZharpSdk.ClearUser();                    // sign-out
Zharp.ZharpSdk.SetTag("region", "eu-west-1");  // on every error and request from now on
Zharp.ZharpSdk.CaptureException(e);            // a handled exception
using (Zharp.ZharpSdk.StartSpan("rebuild-index")) { … }
Zharp.ZharpSdk.Flush();                        // before a short-lived process exits

Nothing here throws into your app.

Options

Code (AddZharp(o => …), ZharpSdk.Init(o => …)) wins, then the environment, then the "Zharp" section of the configuration (appsettings.json, or Zharp: keys in <appSettings>).

builder.Services.AddZharp(o =>
{
    o.Environment = "staging";
    o.CaptureBodies = "errors";
    o.RedactHeaders.Add("x-internal-token");
});
OptionEnvironmentDefault
KeyZHARP_KEY, ZHARP_API_KEY— (nothing is sent)
ServiceZHARP_SERVICE, OTEL_SERVICE_NAMEthe entry assembly's name
EnvironmentZHARP_ENVIRONMENT, ZHARP_ENV, ASPNETCORE_ENVIRONMENT, DOTNET_ENVIRONMENT—
ReleaseZHARP_RELEASEthe informational version (1.4.0+3f2c9ab…, commit included)
EndpointZHARP_ENDPOINThttps://api.zharp.io/api/v1/otlp
LogsZHARP_LOGSoff: the Zharp agent collects your output. See Logs.
TracingZHARP_TRACINGon; off is logs only
LogCorrelationZHARP_LOG_CORRELATIONon: trace_id=… span_id=… on console lines
CaptureHeaders, RedactHeadersZHARP_CAPTURE_HEADERS, ZHARP_CAPTURE_HEADERS_REDACTon
CaptureBodiesZHARP_CAPTURE_BODIES (errors, all)off
CaptureQueryErrorsZHARP_CAPTURE_QUERY_ERRORSon
CaptureSourceContextZHARP_CAPTURE_SOURCE_CONTEXTon: the code that ran, from the PDB
SampleRateZHARP_SAMPLE_RATE1 (errors are always sent)
DisabledZHARP_DISABLEDoff

Supported: .NET 8, 10 and 11; .NET Framework 4.6.2 or later for classic ASP.NET; .NET Standard 2.0 for the core.

Troubleshooting

Nothing arrives

On the app's setup page (Applications → the app → settings → Setup instructions), the verify step shows the first event as soon as it lands, and Send a test event checks the key on its own. If the test event arrives but your app's don't, the SDK isn't starting or isn't reaching Zharp:

  • Is init called, and before the code you expect to see? Without a key, the SDK starts nothing and says so once.
  • Does the service name match? With an app key everything goes to that app whatever it says; with a workspace key, service decides the app — see Keys.
  • Data is sent in batches every few seconds. A process that exits straight away should call flush first.
  • Logs and errors arrive but no traces? Check that tracing isn't turned off — see Logs only.
  • Is AddZharp() (or ZharpSdk.Init) reached, and is the key where the app reads it? The environment wins over appsettings.json, and appsettings.Development.json over both files in development.

401 or 403

Ingest answers 401 when the key is missing, mistyped, revoked or rolled, and 403 when the request comes from an origin or IP address the key doesn't allow. Neither is retried: the SDK warns once and drops what was refused, and it never throws into your code. Copy the key again from the app's settings.

A Release stack ends in lambda_method… with no frame of my code

In Release builds the JIT inlines small methods into their callers. A short controller action or minimal API handler can be inlined into the delegate ASP.NET Core compiles to call it (lambda_method12(Closure, Object, Object[])), so the stack has no frame of yours and no code to show. The error is still grouped and counted as usual. A Debug build shows the method, and a linked repository (or source bundle) still shows the code of any of your frames that remain. Nothing needs changing in your code.

No code shown with errors

  • Does the project set <EmbedAllSources>true</EmbedAllSources>, and do its .pdb files ship with the app?
  • A build with <DebugType>none</DebugType> has no PDB to read: turn PDBs back on (portable is the default).
  • On .NET Framework 4.6.2–4.7.1, use <DebugType>full</DebugType>.