Tooark.Observability 4.12.1

dotnet add package Tooark.Observability --version 4.12.1
                    
NuGet\Install-Package Tooark.Observability -Version 4.12.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tooark.Observability" Version="4.12.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tooark.Observability" Version="4.12.1" />
                    
Directory.Packages.props
<PackageReference Include="Tooark.Observability" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Tooark.Observability --version 4.12.1
                    
#r "nuget: Tooark.Observability, 4.12.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Tooark.Observability@4.12.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Tooark.Observability&version=4.12.1
                    
Install as a Cake Addin
#tool nuget:?package=Tooark.Observability&version=4.12.1
                    
Install as a Cake Tool

Tooark.Observability

Observability library for .NET applications, providing a simplified integration with OpenTelemetry to collect traces, metrics and logs, configured through appsettings.json with sensible defaults.

πŸ“– Docs: Tooark.Observability on the site Β· All packages Β· API reference

🌍 Languages: πŸ‡ΊπŸ‡Έ English (this file) Β· πŸ‡§πŸ‡· PortuguΓͺs


πŸ“‘ Contents


πŸ“¦ Package Contents

Configuration Classes (Options)

Class Description
ObservabilityOptions Main Observability settings
TracingOptions Tracing settings
MetricsOptions Metrics settings
LoggingOptions Logging settings
OtlpOptions OTLP exporter settings
OtlpBatchOptions Batch processor settings (OTLP)
OtlpOverrideOptions Per-signal OTLP overrides (Tracing/Metrics/Logging), inherit from the global
OtlpBatchOverrideOptions Per-signal Batch overrides, inherit from the global
DataSensitiveOptions Sensitive data sanitization settings for Tracing

Enumerations

Enum Description
EProtocolOtlp OTLP communication protocol (grpc, http)
EProcessorType Export processor type (batch, simple)

Dependency Injection Extensions

Method Description
AddTooarkOpenTelemetry() Configures OpenTelemetry with traces, metrics and logs
AddTooarkObservability() Alias of AddTooarkOpenTelemetry()

Both receive an IConfiguration and an optional Action<ObservabilityOptions>, and produce exactly the same registration β€” AddTooarkObservability delegates to AddTooarkOpenTelemetry. Use whichever reads better in your Program.cs.

Instrumentation

Class Description
TooarkInstrumentation Singleton with the ActivitySource and the Meter already registered, for the application's spans and metrics

Registered by AddTooarkOpenTelemetry even when Enabled = false (a source without a listener is a no-op), so injecting it never fails. It also exposes the resolved ServiceName and ServiceVersion. See Creating Custom Traces.


πŸ”§ Installation

dotnet add package Tooark.Observability

βš™οΈ Configuration

appsettings.json - Full Configuration

Example with every option available in the package:

{
  "Observability": {
    "Enabled": true,
    "ServiceName": "MyService",
    "ServiceVersion": "1.0.0",
    "ServiceInstanceId": "instance-001",
    "UseConsoleExporterInDevelopment": true,
    "AllowSensitiveData": false,
    "ResourceAttributes": {
      "provider.name": "aws",
      "provider.region": "us-east-1",
      "provider.cluster": "cluster-a",
      "tenant.id": "tenant-123"
    },
    "Tracing": {
      "Enabled": true,
      "SamplingRatio": 1.0,
      "Otlp": {
        "Endpoint": "http://localhost:4318",
        "Protocol": "http"
      },
      "IgnorePathPrefix": "/api",
      "IgnorePaths": ["/status"],
      "ActivitySourceName": "Tooark",
      "AdditionalSources": ["MyActivitySource", "OtherSource"],
      "DataSensitive": {
        "HideQueryParameters": true,
        "HideHeaders": true,
        "SensitiveRequestHeaders": ["x-tenant-secret"]
      }
    },
    "Metrics": {
      "Enabled": true,
      "ExportIntervalMilliseconds": 60000,
      "RuntimeMetricsEnabled": true,
      "ProcessMetricsEnabled": true,
      "MeterName": "Tooark",
      "AdditionalMeters": ["MyMeter", "OtherMeter"],
      "Otlp": {
        "Headers": "tenant-id=metrics-tenant"
      }
    },
    "Logging": {
      "Enabled": true,
      "IncludeFormattedMessage": true,
      "IncludeScopes": true,
      "ParseStateValues": true,
      "Otlp": {
        "Endpoint": "http://localhost:4320"
      }
    },
    "Otlp": {
      "Enabled": true,
      "Endpoint": "http://localhost:4317",
      "Protocol": "grpc",
      "ExportProcessorType": "batch",
      "ServerlessOptimized": false,
      "Headers": "api-key=your-api-key,tenant-id=tenant-123",
      "Batch": {
        "MaxQueueSize": 2048,
        "MaxExportBatchSize": 512,
        "ScheduledDelayMilliseconds": 5000,
        "ExporterTimeoutMilliseconds": 10000
      }
    }
  }
}

The IgnorePaths and SensitiveRequestHeaders lists of the example add to the default lists: "/status" is ignored along with /health, /metrics and the others, and x-tenant-secret is marked along with authorization, cookie and the others. See Configuration Options.

Per-signal OTLP override

The settings in Observability:Otlp work as the base for Tracing, Metrics and Logging.

If you define Tracing:Otlp, Metrics:Otlp or Logging:Otlp, only the fields provided for that signal override the global OTLP. The others keep being inherited from the main block.

Since the overrides use nullable fields (OtlpOverrideOptions), any provided value is applied β€” including values equal to the defaults. For instance, "Tracing": { "Otlp": { "Enabled": false } } disables OTLP for tracing only, even with the global OTLP enabled.

Example: here Tracing reuses Enabled, Headers, Batch and the other fields of the global OTLP, changing only Endpoint and Protocol.

{
  "Observability": {
    "Otlp": {
      "Enabled": true,
      "Endpoint": "http://localhost:4317",
      "Headers": "api-key=global-key"
    },
    "Tracing": {
      "Otlp": {
        "Endpoint": "http://localhost:4318",
        "Protocol": "http"
      }
    }
  }
}

appsettings.json - Minimal Configuration

For most cases, a minimal configuration is enough to enable tracing, metrics and logging exported through OTLP:

{
  "Observability": {
    "ServiceName": "MyService",
    "Otlp": {
      "Enabled": true,
      "Endpoint": "http://localhost:4317"
    }
  }
}

or with a custom header:

{
  "Observability": {
    "ServiceName": "MyService",
    "Otlp": {
      "Enabled": true,
      "Endpoint": "http://localhost:4317",
      "Headers": "api-key=your-api-key"
    }
  }
}

appsettings.json - Serverless Configuration

For serverless environments (AWS ECS, GCP Cloud Run, Azure Container Apps) with scale-to-zero:

{
  "Observability": {
    "ServiceName": "MyService",
    "Otlp": {
      "Enabled": true,
      "Endpoint": "http://otel-collector:4317",
      "ServerlessOptimized": true
    }
  }
}

For AWS Lambda, GCP Cloud Functions or Azure Functions (immediate export):

{
  "Observability": {
    "ServiceName": "MyService",
    "Otlp": {
      "Enabled": true,
      "Endpoint": "http://otel-collector:4317",
      "ExportProcessorType": "simple"
    }
  }
}

Program.cs

using Tooark.Observability.Injections;

var builder = WebApplication.CreateBuilder(args);

// Adds OpenTelemetry with the appsettings.json settings
builder.Services.AddTooarkOpenTelemetry(builder.Configuration);

var app = builder.Build();

app.Run();

Programmatic Configuration

You can also configure programmatically or combine with appsettings.json:

using Tooark.Observability.Injections;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddTooarkOpenTelemetry(builder.Configuration, options =>
{
    // Overrides the appsettings.json settings
    options.ServiceName = "MyCustomService";
    options.Tracing.SamplingRatio = 0.5; // half of the traces that start in this application

    // Adds custom sources/meters
    options.Tracing.AdditionalSources = ["MyActivitySource"];
    options.Metrics.AdditionalMeters = ["MyMeter"];

    // Advanced configuration through callbacks
    options.ConfigureTracing = builder =>
    {
        // Add extra instrumentations
        // builder.AddSqlClientInstrumentation();
    };

    options.ConfigureMetrics = builder =>
    {
        // Extra metrics configuration
    };

    options.ConfigureLogging = loggerOptions =>
    {
        // Extra logging configuration
    };

    options.ConfigureResource = resource =>
    {
        // Resource detectors from the OpenTelemetry contrib packages (optional, see Default Behavior)
        // resource.AddContainerDetector();
    };
});

var app = builder.Build();

app.Run();

πŸ“Š Configuration Options

Each table gives the Tooark default and what the option is for; below it, the practical effect of the options that need more explanation. Lists (IgnorePaths, SensitiveRequestHeaders, AdditionalSources, AdditionalMeters) given in appsettings.json add to the defaults, they do not replace them. To replace a whole list, assign the array through the overload with Action<ObservabilityOptions>.

ObservabilityOptions

Property Type Default What it is for
Enabled bool true Turns OpenTelemetry on in the application; with false, no signal is collected
ServiceName string? null Service name (service.name); resolution order in the Resource section
ServiceVersion string? null Service version (service.version); resolution order in the Resource section
ServiceInstanceId string? null Replica identifier (service.instance.id); without a value, a GUID per startup
ResourceAttributes Dictionary<string,string> {} Extra Resource attributes (cloud, region, cluster), added to OTEL_RESOURCE_ATTRIBUTES
AllowSensitiveData bool false Turns off the span sanitization done by Tooark
UseConsoleExporterInDevelopment bool true In development, writes to the console the signals that do not go to OTLP
Tracing TracingOptions (new) Tracing settings
Metrics MetricsOptions (new) Metrics settings
Logging LoggingOptions (new) Logging settings
Otlp OtlpOptions (new) OTLP exporter shared by the three signals
  • Enabled: with false, no trace, metrics or logs provider is registered, whatever the other options say. TooarkInstrumentation stays registered, so code that creates spans and metrics through it works with nothing collected.
  • AllowSensitiveData: with true, the Tracing.DataSensitive options stop applying: the query string stays in spans and sensitive headers are not marked. Query values are still masked by the OpenTelemetry instrumentation itself (?token=Redacted), unless the application turns that masking off through the OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION and OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION variables. It does not affect logs, which Tooark never sanitizes.
  • UseConsoleExporterInDevelopment: applies when the environment (ASPNETCORE_ENVIRONMENT or DOTNET_ENVIRONMENT) is Development or Dev, signal by signal: a signal with OTLP off goes to the console, and one with OTLP on does not. In other environments, nothing is written to the console.

After registration, the container's IOptions<ObservabilityOptions> carries the resolved values: ServiceName, ServiceVersion, Tracing.ActivitySourceName and Metrics.MeterName are no longer null or the bare default when they were inferred.

Besides the options bindable from appsettings.json, ObservabilityOptions exposes four callbacks that can only be set programmatically, through the overload with Action<ObservabilityOptions>. Each one runs after the Tooark configuration:

Callback Type Use
ConfigureTracing Action<TracerProviderBuilder>? Extra trace instrumentations, processors and exporters
ConfigureMetrics Action<MeterProviderBuilder>? Extra metrics instrumentations, views and readers
ConfigureLogging Action<OpenTelemetryLoggerOptions>? Extra log processors and exporters
ConfigureResource Action<ResourceBuilder>? Resource detectors (cloud, container); runs last, after the others

TracingOptions

Property Type Default What it is for
Enabled bool true Turns tracing on; metrics and logs are not affected
SamplingRatio double 1.0 Fraction of new traces that is recorded (0.0 to 1.0)
IgnorePathPrefix string? null Base path put before each IgnorePaths item
IgnorePaths string[] probes, telemetry, icon Paths of incoming requests that produce no span
ActivitySourceName string Tooark Main ActivitySource; left at the default, it becomes the service name, with Tooark as fallback and always registered too
AdditionalSources string[] [] Other ActivitySources collected; a span from an unregistered source is not recorded
DataSensitive DataSensitiveOptions (defaults) Query string and sensitive headers in spans
Otlp OtlpOverrideOptions? null OTLP settings for traces only
  • SamplingRatio: decides only the traces that start in this application. A request that arrives with a traceparent follows the caller's decision: if the caller recorded, this application records; if it did not, this one does not either, whatever the ratio. With 0.25, about one in four new traces is recorded, chosen by TraceId; with 0.0, no new trace is recorded, but those that arrive marked as recorded still are. Out-of-range values become 0.0 or 1.0.

  • IgnorePaths: takes infrastructure calls out of tracing, since they are frequent and say nothing about how the application is used. Applies only to requests received by ASP.NET Core; metrics and logs of those requests remain. Matching is by the start of the path, case-insensitive: /health ignores /health and /health/live, and also /healthcare; /logs also ignores /logs-audit. A blank entry ignores every request. In v5 matching becomes by whole segment. Default:

    • health probes: /health, /healthz and /ready;
    • telemetry collection: /metrics, /traces and /logs;
    • icon requested by browsers: /favicon.ico.

    If the application has a business route that starts with one of these names (/logs-audit, for example), replace the whole list in code: through appsettings.json items only add up.

  • IgnorePathPrefix: for applications published under a base path. With "/api", the /health item ignores /api/health, and /health without the prefix is traced again. "api/" and "/api" have the same effect.

DataSensitiveOptions (Tracing)

Property Type Default What it is for
HideQueryParameters bool true Removes the query string (names and values) from span attributes
HideHeaders bool true Marks in spans that sensitive headers were present, without the value
SensitiveRequestHeaders string[] credentials and tokens (below) Request headers treated as sensitive by HideHeaders

All three apply to spans of incoming requests (ASP.NET Core) and outgoing ones (HttpClient). They do not apply to logs or metrics.

  • HideQueryParameters: with true, the url.query attribute leaves the spans of incoming requests and the query leaves url.full in outgoing ones; the legacy http.target, when present with a query, is rewritten with the path only (/api/users?token=xxx β†’ /api/users). With false, the query stays, with the parameter names and the values masked by the OpenTelemetry instrumentation (see AllowSensitiveData).
  • HideHeaders: with true, for each listed header present in the request, the span gets http.request.header.{name} with the value [REDACTED], so the trace shows the call carried a credential without exposing it. With false, nothing is recorded about those headers. Tooark never copies a header value into a span.
  • SensitiveRequestHeaders: compared case-insensitively. Only request headers are checked; response headers, such as set-cookie, are not. Default:
    • authorization, proxy-authorization and cookie;
    • x-api-key, api-key and apikey;
    • x-auth-token and x-access-token;
    • x-csrf-token and x-xsrf-token (anti-forgery tokens);
    • x-functions-key and ocp-apim-subscription-key (Azure Functions and API Management);
    • x-ms-token-aad-access-token and x-ms-token-aad-id-token (Azure App Service authentication) and x-azure-access-token;
    • x-amz-security-token, x-amzn-oidc-accesstoken and x-amzn-oidc-data (AWS and Application Load Balancer authentication);
    • x-goog-api-key, x-goog-iap-jwt-assertion and x-google-oauth-access-token (Google Cloud and Identity-Aware Proxy);
    • x-vault-token (HashiCorp Vault, used by Tooark.Secrets.Vault).

MetricsOptions

Property Type Default What it is for
Enabled bool true Turns metrics collection on; traces and logs are not affected
ExportIntervalMilliseconds int? null Interval between OTLP sends: 60000, or 5000 with ServerlessOptimized
RuntimeMetricsEnabled bool true .NET runtime metrics: garbage collections, managed memory, thread pool, JIT, exceptions and locks
ProcessMetricsEnabled bool true Process metrics as seen by the operating system: CPU, memory and threads
MeterName string Tooark Main Meter; left at the default, it becomes the service name, with Tooark as fallback and always registered too
AdditionalMeters string[] [] Other Meters collected; a metric from an unregistered Meter is not collected
Otlp OtlpOverrideOptions? null OTLP settings for metrics only
  • ExportIntervalMilliseconds: at each interval, the accumulated value of each metric is read and sent. Shorter keeps dashboards closer to real time and reduces what is lost on an unannounced shutdown, with more sends. Values less than or equal to zero apply the default. The Otlp:Batch options do not apply to metrics.
  • RuntimeMetricsEnabled and ProcessMetricsEnabled: turn off to reduce the number of series in the backend, for example when the platform (Kubernetes, ECS, Cloud Run) already measures the container.

LoggingOptions

Property Type Default What it is for
Enabled bool true Sends ILogger logs through OpenTelemetry, with TraceId and SpanId
IncludeFormattedMessage bool true Log body with the message already built, values in the text
IncludeScopes bool true Includes in logs the values of scopes opened with BeginScope
ParseStateValues bool true LogRecord.State always null, values only in the attributes
Otlp OtlpOverrideOptions? null OTLP settings for logs only
  • Enabled: OpenTelemetry joins as one more ILogger provider; the other providers remain. The level filters of the Logging section apply either way.
  • IncludeFormattedMessage: for logger.LogInformation("Order {OrderId} from customer {Customer}", 7, "Ana"), with true the body is Order 7 from customer Ana and the template goes in the {OriginalFormat} attribute; with false, the body is the template. Either way OrderId and Customer go as attributes: turning it off does not hide sensitive data. Turn it off when the log tool groups by body.
  • IncludeScopes: every log of a request carries RequestId, RequestPath, ConnectionId, TraceId, SpanId, ParentId and the application scopes, to filter all logs of a request or an order. It increases the size of each log. Over OTLP, a plain-text scope (BeginScope("order 7")) is not sent: use key/value pairs, with keys that do not repeat across nested scopes.
  • ParseStateValues: the exported attributes are the same with both values. With false, LogRecord.State holds the object passed to ILogger. Change it only if a processor of yours reads LogRecord.State.

Log content does not go through the DataSensitiveOptions sanitization: do not log secrets in messages or scopes.

OtlpOptions

Property Type Default What it is for
Enabled bool false Turns on sending traces, metrics and logs to an OTLP collector
Endpoint string? null Collector address; required with Enabled
Protocol EProtocolOtlp grpc grpc (port 4317) or http (port 4318, protobuf body)
ExportProcessorType EProcessorType batch batch (queue and background send) or simple (item by item)
ServerlessOptimized bool false Sends more often, to lose less on an abrupt shutdown
Headers string? null Headers of each send, usually the provider credential
Batch OtlpBatchOptions (defaults) Queue, batch and timeout of the batch send
  • Endpoint: this value is what counts; Tooark does not read the OTEL_EXPORTER_OTLP_ENDPOINT variable. A missing address, or one that is not an absolute URL, stops the application from starting (Options.Otlp.Endpoint.Invalid).
  • ExportProcessorType: with batch, the application request does not wait for the send. With simple, each span or log is sent as soon as it ends, on the thread that ended it, which waits for the collector's response: it is for debugging and makes requests slower in production. Applies to traces and logs; metrics follow their own interval.
  • ServerlessOptimized: for platforms that stop or freeze the instance without waiting for the send. The values applied are in Serverless Environments.
  • Headers: format key1=value1,key2=value2. Each pair is split at the first =, so the value may contain =, like Base64 padding (Authorization=Basic dXNlcjpzZW5oYQ==). Names accept letters, digits, ., _ and -; a pair without a name or a value, or with a line break, stops the application from starting. Keep the value in a secret store or an environment variable.

HTTP protocol and the signal path. With "Protocol": "http", each signal is sent to its own path: /v1/traces, /v1/metrics and /v1/logs. Give only the collector address (http://otel-collector:4318) or the provider base URL (https://.../otlp), in the global OTLP or in a signal's: the package appends the path. An address that already ends in one of those paths is used as is. With gRPC the address is never changed.

http/protobuf, as OpenTelemetry writes it, is accepted as http. A value that does not exist in Protocol or ExportProcessorType stops the application from starting, with Invalid.Parameter;{value}.

OtlpBatchOptions

They apply to traces and logs with ExportProcessorType batch. Spans and logs go into an in-memory queue, and a background thread sends them in batches.

Property Type Default What it is for
MaxQueueSize int 2048 How many items can wait in the queue; with the queue full, new ones are dropped
MaxExportBatchSize int 512 How many items go, at most, in each send (capped at MaxQueueSize)
ScheduledDelayMilliseconds int 5000 Interval between two sends; the queue also goes out when it holds a full batch
ExporterTimeoutMilliseconds int 10000 Maximum time of each send to the collector
  • MaxQueueSize: the queue fills up when the collector is slow or down. New items are dropped until there is room; the application neither waits nor fails. Increase it to absorb peaks, at the cost of more memory.
  • ScheduledDelayMilliseconds: shorter makes data show up sooner in the backend and reduces what is lost on an abrupt shutdown, with more sends.
  • ExporterTimeoutMilliseconds: once this time passes without the collector's response, the send is canceled and counts as a failure, and the items of that batch are not sent again. Increase it for a distant or slow collector; decrease it so the send thread is not stuck when the collector does not answer.

Values less than or equal to zero (less than zero, for ScheduledDelayMilliseconds) apply the default. With ServerlessOptimized, the fields not given follow the serverless values.

OtlpOverrideOptions and OtlpBatchOverrideOptions

Used in Tracing:Otlp, Metrics:Otlp and Logging:Otlp. They have the same fields as OtlpOptions and OtlpBatchOptions, but all nullable: fields not provided (null) inherit the value of the global OTLP; provided fields override the global one, even when equal to the defaults (e.g. Enabled: false disables OTLP for that signal only).


🎯 Default Behavior

Resource (Service Identification)

OpenTelemetry uses the Resource to identify the origin of the telemetry data. Each value comes from the first source in the row that is filled in; empty or whitespace-only values fall through to the next one:

Attribute Source
service.name ServiceName β†’ OTEL_SERVICE_NAME β†’ entry assembly name β†’ "unknown_service"
service.version ServiceVersion β†’ service.version in OTEL_RESOURCE_ATTRIBUTES β†’ AssemblyInformationalVersion without +commit β†’ AssemblyVersion β†’ "unknown_version"
service.instance.id ServiceInstanceId β†’ OTEL_SERVICE_INSTANCE_ID β†’ Guid.NewGuid()
deployment.environment.name ASPNETCORE_ENVIRONMENT β†’ DOTNET_ENVIRONMENT β†’ "unknown_environment"
deployment.environment Same value as above (legacy key, kept for compatibility)
host.name Environment.MachineName
process.pid Environment.ProcessId, as a number
process.runtime.* .NET runtime information

The informational version is the <Version> of the project (2.3.0, 2.3.0-beta.1); the +<commit> suffix the SDK appends is dropped. Without a <Version>, the SDK default yields 1.0.0.

Changed in 4.8.0: service.version was read from the four-part AssemblyVersion (2.3.0.0) and now comes from the informational version (2.3.0); process.pid was a string and is now a number; and OTEL_SERVICE_NAME was overridden by the assembly name and now wins over it. Review dashboard filters that depend on the old values.

Attributes from the environment (OTEL_*)

The standard OpenTelemetry variables are honored without any code. OTEL_RESOURCE_ATTRIBUTES takes a comma-separated key=value list and puts every pair into the Resource of traces, metrics and logs:

OTEL_SERVICE_NAME=orders-api
OTEL_RESOURCE_ATTRIBUTES=cloud.provider=aws,cloud.region=us-east-1,k8s.cluster.name=cluster-a,tenant.id=tenant-123

When the same key is also present in Observability:ResourceAttributes, the appsettings.json value wins. Prefer the keys of the OpenTelemetry semantic conventions (cloud.provider, cloud.region, k8s.cluster.name): backends recognize them, unlike free-form keys. A value that changes per request, such as a tenant in a multi-tenant deployment, is not a Resource attribute β€” put it on the span or in Baggage.

Resource detectors (ConfigureResource)

Automatic detection of cloud, container and host metadata lives in the OpenTelemetry contrib packages (OpenTelemetry.Resources.AWS, .Azure, .Gcp, .Container, .Host, .Process). They query the cloud metadata service at startup, and some are still in beta, so they are not dependencies of Tooark.Observability. Install only the ones you want and plug them in through the ConfigureResource callback, which runs last, after the Tooark attributes and ResourceAttributes:

// dotnet add package OpenTelemetry.Resources.AWS
// dotnet add package OpenTelemetry.Resources.Container
builder.Services.AddTooarkOpenTelemetry(builder.Configuration, options =>
{
    options.ConfigureResource = resource => resource
        .AddAWSECSDetector()       // OpenTelemetry.Resources.AWS
        .AddContainerDetector();   // OpenTelemetry.Resources.Container
});

The callback is optional: Tooark works the same without it and does not depend on those packages. The detector method names vary between versions of the contrib packages, so check the version you install. Tooark does not guarantee that the attributes added by third-party detectors are applied β€” that depends on the package version and on the environment the application runs in (a detector outside its cloud adds nothing).

Tracing

When enabled (Tracing.Enabled = true):

  • Sources: the ActivitySource named by ActivitySourceName (the service name when the default is kept) plus Tooark, always registered, plus AdditionalSources. A span from a source that is not registered is discarded silently.
  • ASP.NET Core Instrumentation: automatically captures traces of incoming HTTP requests
  • HTTP Client Instrumentation: captures traces of outgoing HTTP requests (HttpClient)
  • Ignored paths: incoming requests in IgnorePaths produce no span. Matching is by the start of the path: /health ignores /health/live and also /healthcare. The default list is under TracingOptions.
  • RecordException: exceptions are automatically recorded on the spans
  • Sampling: SamplingRatio decides the fraction of traces that start in this application; a request that arrives with a traceparent follows the caller's decision.

Sensitive Data Sanitization

When AllowSensitiveData = false (default):

  • Query string: removed from the attributes of the current semantic conventions β€” url.query (ASP.NET Core) and url.full (HttpClient); the legacy http.target attribute is rewritten when present with a query (e.g. /api/users?token=xxx β†’ /api/users)
  • Sensitive headers: the span gets http.request.header.{name} with [REDACTED] for each listed header present in the request; the value is never copied

With AllowSensitiveData = true, the Tracing.DataSensitive options stop applying. Sanitization applies to spans only: log content is not masked.

Metrics

When enabled (Metrics.Enabled = true):

  • Meters: the Meter named by MeterName (the service name when the default is kept) plus Tooark, always registered, plus AdditionalMeters. A measurement from a meter that is not registered is discarded silently.
  • ASP.NET Core Instrumentation: metrics of incoming HTTP requests
  • HTTP Client Instrumentation: metrics of outgoing HTTP calls
  • Runtime Instrumentation: .NET runtime metrics (GC, threads, etc.) when RuntimeMetricsEnabled = true
  • Process Instrumentation: process metrics (CPU, memory) when ProcessMetricsEnabled = true
  • Export interval: metrics are exported through OTLP every ExportIntervalMilliseconds (default: 60s; 5s when the effective OTLP has ServerlessOptimized enabled)

Logging

When enabled (Logging.Enabled = true):

  • Integrates with Microsoft.Extensions.Logging
  • Exports logs through OTLP together with traces and metrics
  • Automatically correlates logs with traces (TraceId/SpanId)

Exporters

Exporter Activation Type
OTLP Otlp.Enabled = true + Otlp.Endpoint configured Push
Console Development environment + UseConsoleExporterInDevelopment + OTLP disabled Push

Note: This package does not expose HTTP endpoints for metrics collection (such as Prometheus' /metrics). It uses the push model through OTLP only.


πŸ”Œ Collector Integration

OpenTelemetry Collector (gRPC)

{
  "Observability": {
    "ServiceName": "MyService",
    "Otlp": {
      "Enabled": true,
      "Endpoint": "http://otel-collector:4317",
      "Protocol": "grpc"
    }
  }
}

OpenTelemetry Collector (HTTP)

{
  "Observability": {
    "ServiceName": "MyService",
    "Otlp": {
      "Enabled": true,
      "Endpoint": "http://otel-collector:4318",
      "Protocol": "http"
    }
  }
}

Jaeger

{
  "Observability": {
    "ServiceName": "MyService",
    "Otlp": {
      "Enabled": true,
      "Endpoint": "http://jaeger:4317",
      "Protocol": "grpc"
    }
  }
}

Grafana Cloud / Tempo

{
  "Observability": {
    "ServiceName": "MyService",
    "Otlp": {
      "Enabled": true,
      "Endpoint": "https://otlp-gateway-prod-us-central-0.grafana.net/otlp",
      "Protocol": "http",
      "Headers": "Authorization=Basic <base64-encoded-credentials>"
    }
  }
}

Azure Monitor / Application Insights

For Azure Monitor, use the Azure.Monitor.OpenTelemetry.Exporter package and configure it through the callback:

builder.Services.AddTooarkOpenTelemetry(builder.Configuration, options =>
{
    options.ConfigureTracing = builder =>
    {
        builder.AddAzureMonitorTraceExporter(o =>
        {
            o.ConnectionString = "<connection-string>";
        });
    };

    options.ConfigureMetrics = builder =>
    {
        builder.AddAzureMonitorMetricExporter(o =>
        {
            o.ConnectionString = "<connection-string>";
        });
    };
});

πŸš€ Serverless Environments

Serverless containers can be shut down at any time (scale-to-zero), causing telemetry data loss if the shutdown happens before the buffer is flushed.

ServerlessOptimized

Automatically tunes the batch settings to minimize data loss:

Parameter Default Value Serverless Value Impact
ScheduledDelayMilliseconds 5000ms 1000ms Flush every second
MaxExportBatchSize 512 128 Smaller batches, more frequent exports
MaxQueueSize 2048 512 Less data at risk of loss
Metrics.ExportIntervalMilliseconds* 60000ms 5000ms Metrics exported more often

* Metrics use a periodic reader (not the Batch processor); the serverless interval is only applied when Metrics.ExportIntervalMilliseconds was not provided.

The serverless values are applied only to the batch fields not customized: any value explicitly set by the user is kept, even when equal to the standard default.

Recommendations by Environment

Scenario Recommended Configuration
Traditional servers (VMs, bare metal) Default (ServerlessOptimized: false)
Kubernetes with persistent pods Default (ServerlessOptimized: false)
AWS ECS (Fargate or EC2) ServerlessOptimized: true
GCP Cloud Run ServerlessOptimized: true
Azure Container Apps ServerlessOptimized: true
AWS Lambda ExportProcessorType: simple
GCP Cloud Functions ExportProcessorType: simple
Azure Functions ExportProcessorType: simple

Graceful Shutdown

The OpenTelemetry SDK does a ForceFlush automatically during shutdown. Configure enough time:

  • AWS ECS: stopTimeout in the task definition (default: 30s)
  • GCP Cloud Run: terminationGracePeriodSeconds (default: 10s)
  • Kubernetes: terminationGracePeriodSeconds in the Pod spec

πŸ“ Usage Examples

Full Example with an API

using Tooark.Observability.Injections;

var builder = WebApplication.CreateBuilder(args);

// Configures services
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Configures OpenTelemetry
builder.Services.AddTooarkOpenTelemetry(builder.Configuration);

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

With appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Observability": {
    "ServiceName": "MyAPI",
    "ServiceVersion": "1.0.0",
    "Otlp": {
      "Enabled": true,
      "Endpoint": "http://otel-collector:4317"
    }
  }
}

Creating Custom Traces

Inject TooarkInstrumentation: its ActivitySource is already registered under the resolved name (the service name, orders-api for instance), so the spans show up in the backend under the service, not under Tooark, and the application never repeats the string:

using System.Diagnostics;
using Tooark.Observability;

public class OrderService
{
    private readonly ActivitySource _activitySource;

    public OrderService(TooarkInstrumentation telemetry)
    {
        _activitySource = telemetry.ActivitySource;   // name: "orders-api"
    }

    public async Task ProcessOrder(int orderId)
    {
        using var activity = _activitySource.StartActivity("ProcessOrder");
        activity?.SetTag("order.id", orderId);

        try
        {
            // Processing logic...
            activity?.SetTag("order.status", "success");
        }
        catch (Exception ex)
        {
            activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
            activity?.RecordException(ex);
            throw;
        }
    }
}

A static new ActivitySource("Tooark"), as in earlier versions, keeps working: the Tooark source is always registered. A static source with any other name has to be listed in Tracing.AdditionalSources, or its spans are discarded without any error.

Creating Custom Metrics

The same singleton exposes the Meter, registered under the resolved MeterName:

using System.Diagnostics;
using System.Diagnostics.Metrics;
using Tooark.Observability;

public class OrderService
{
    private readonly Counter<long> _ordersProcessed;
    private readonly Histogram<double> _processingTime;

    public OrderService(TooarkInstrumentation telemetry)
    {
        _ordersProcessed = telemetry.Meter.CreateCounter<long>("orders.processed");
        _processingTime = telemetry.Meter.CreateHistogram<double>("orders.time_ms");
    }

    public async Task ProcessOrder(int orderId)
    {
        var sw = Stopwatch.StartNew();

        // Processing logic...

        sw.Stop();
        _ordersProcessed.Add(1, new KeyValuePair<string, object?>("type", "new"));
        _processingTime.Record(sw.ElapsedMilliseconds);
    }
}

Instruments are created once per meter name, so keep them in fields of a singleton or create them in the constructor, as above, instead of on every call. A static new Meter("Tooark") keeps working as well.


πŸ“‹ Dependencies

Package Description
Tooark.Exceptions Custom exceptions
OpenTelemetry OpenTelemetry base SDK
OpenTelemetry.Exporter.Console Console exporter (development)
OpenTelemetry.Exporter.OpenTelemetryProtocol OTLP exporter (gRPC/HTTP)
OpenTelemetry.Extensions.Hosting Integration with the .NET Host
OpenTelemetry.Instrumentation.AspNetCore Automatic ASP.NET Core instrumentation
OpenTelemetry.Instrumentation.Http Automatic HttpClient instrumentation
OpenTelemetry.Instrumentation.Process Automatic Process instrumentation
OpenTelemetry.Instrumentation.Runtime .NET runtime metrics

OpenTelemetry.Instrumentation.Process is only published as a pre-release (rc) by the OpenTelemetry project. This package pins it to the rc that matches the OpenTelemetry line in use, which is why NuGet shows a pre-release dependency on a stable package (warning NU5104). It is the only pre-release dependency in the Tooark family.


⚠️ Important Notes

  1. Lifecycle managed by the host: OpenTelemetry is registered through services.AddOpenTelemetry(), ensuring proper management of TracerProvider, MeterProvider and graceful shutdown.

  2. No silent break: If no exporter is configured, the application keeps working normally, just without exporting telemetry.

  3. Console Exporter in Development: Enabled automatically when UseConsoleExporterInDevelopment = true and OTLP is not configured.

  4. No /metrics endpoint: This package uses the push model (OTLP). It does not expose HTTP endpoints for Prometheus-style scraping.

  5. ResourceAttributes normalization: Keys are normalized automatically: lowercase, spaces β†’ ., invalid characters β†’ _. The pairs in OTEL_RESOURCE_ATTRIBUTES are also applied; on the same key, appsettings.json wins.

  6. Callbacks for customization: Use ConfigureTracing, ConfigureMetrics and ConfigureLogging to add instrumentations or advanced settings, and ConfigureResource for the resource detectors of the contrib packages.

  7. Source and meter names: with ActivitySourceName and MeterName left at the default, the main source and meter take the service name, and Tooark stays registered as well. TooarkInstrumentation hands both to the application already registered.


🀝 Contributing

Contributions are welcome! Start with CONTRIBUTING.md β€” it covers the development workflow, the coding and commit conventions and the pull request checklist. Bugs and feature requests go through the issue templates of the Tooark repository.

By participating you agree to the Code of Conduct.


πŸ†˜ Help & Security

  • ❓ Questions, bugs, feature ideas β€” see SUPPORT.md for the right channel
  • πŸ”’ Security vulnerabilities β€” do not open a public issue; follow SECURITY.md

πŸ’– Support

If Tooark helps your projects, consider supporting its development:

Every contribution helps keep the project maintained and improving. Thank you! πŸ™


πŸ“„ License

This project is licensed under the BSD 3-Clause License.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Tooark.Observability:

Package Downloads
Tooark

Package with all Tooark resources for .NET applications.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.12.1 0 11/30/2026
4.12.0 68 11/29/2026
4.11.0 184 11/21/2026
4.10.0 128 11/18/2026
4.9.0 115 11/16/2026
4.8.0 141 11/15/2026
4.7.3 102 11/11/2026
4.7.2 108 11/3/2026
4.7.1 213 10/17/2026
4.7.0 471 9/30/2026
4.6.0 145 9/29/2026
4.5.0 106 9/29/2026
4.4.0 99 9/28/2026
4.3.0 109 9/26/2026
4.2.1 105 9/25/2026
4.2.0 126 9/20/2026
3.3.7 69 11/15/2026
3.3.6 92 9/18/2026
2.3.6 68 11/15/2026
2.3.5 94 9/18/2026
Loading failed