[Workshop Alert] Mastering Observability with OpenTelemetry Fundamentals - Register Now!

Back to All Integrations

.NET Logging .NET Logging

Last Updated: Jul. 07, 2024

Logging data generated by .NET (C#) applications can be submitted directly to the Coralogix platform using the OpenTelemetry logging SDK within your application.

We recommend using our standard OpenTelemetry integrations to ensure full enrichment of records with appropriate metadata. If it is not possible, use this direct option to submit your application logs. If needed, you can also submit these logs to a local OTEL agent for processing and enrichment . To achieve this, leave out the CX_DOMAIN or CX_PRIVATE_KEY and set the OtlpExporterOptions.Endpoint, accordingly. By default, it’s set to http://localhost:4317

Prerequisites

  • Application using ILogger framework for logging.
  • Unrestricted egress to Coralogix ingress endpoint from application deployment location.
  • .NET 8 (other releases are supported as well, but only the current LTS was tested).

Installation

Install these packages:

dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
dotnet add package OpenTelemetry.Exporter.Console

Code Example

using Microsoft.Extensions.Logging;
using OpenTelemetry.Resources;
using OpenTelemetry.Logs;
using OpenTelemetry.Exporter;

var consoleDebug = true;

var loggerFactory = LoggerFactory.Create(builder =>
{
    // Load the default OTEL configuration from the environment variables
    var resourceBuilder = ResourceBuilder.CreateDefault();

    // // Uncomment to configure Attributes manually in code if desired, can be used
    // // in conjunction with the OTEL_RESOURCE_ATTRIBUTES environment variable but
    // // will override attributes of the same name.
    // resourceBuilder.AddAttributes(new List<KeyValuePair<string, object>> {
    //     new KeyValuePair<string, object>("cx.application.name", "dotnet-application"),
    //     new KeyValuePair<string, object>("cx.subsystem.name", "dotnet-subsystem")
    // });
    
    // // Uncomment to configure Service Name manually in code if desired
    // resourceBuilder.AddService("dotnet-service");
    
    var cxDomain = Environment.GetEnvironmentVariable("CX_DOMAIN");
    var cxPrivateKey = Environment.GetEnvironmentVariable("CX_PRIVATE_KEY");

    // If the environment variables are not set, configure the exporter to localhost
    if (string.IsNullOrEmpty(cxDomain) || string.IsNullOrEmpty(cxPrivateKey))
    {
        Console.WriteLine("CX_DOMAIN or CX_PRIVATE_KEY unset configuring localhost target.");
        builder.AddOpenTelemetry(logging =>
        {
            logging.SetResourceBuilder(resourceBuilder).AddOtlpExporter(OtlpExporterOptions =>
            {
                OtlpExporterOptions.Endpoint = new Uri($"http://localhost:4317");
            });
            if (consoleDebug)
            {   
                Console.WriteLine("consoleDebug is set, adding console exporter.");
                logging.AddConsoleExporter();
            }
        });
    }
    // If the environment variables are set, configure the exporter to the specified domain
    else
    {
        builder.AddOpenTelemetry(logging =>
        {
            logging.SetResourceBuilder(resourceBuilder).AddOtlpExporter(OtlpExporterOptions =>
            {
                OtlpExporterOptions.Endpoint = new Uri($"https://{cxDomain}:443");
                OtlpExporterOptions.Headers = $"Authorization=Bearer {cxPrivateKey}";
            });
            if (consoleDebug)
            {
                Console.WriteLine("consoleDebug is set, adding console exporter.");
                logging.AddConsoleExporter();
            }
        });
    }
});

ILogger logger = loggerFactory.CreateLogger("OTEL-Logger");

logger.LogInformation("Testing logging instrumentation with OpenTelemetry.");

// Make sure you Dispose the loggerFactory to ensure all logs are flushed
loggerFactory.Dispose();

Example Components

Variables

Two important variables must be set: CX_DOMAIN and CX_PRIVATE_KEY. Populate these strings using any mechanism you need for privacy/security, but they are used for configuring the OTLP Exporter. If you use this example code, and do not set CX_DOMAIN or CX_PRIVATE_KEY, the payloads are submitted to http://localhost:4317 by default.

ResourceBuilder

This variable configures the metadata reported by the Opentelemetry SDK. This is done using environment variables set prior to execution, as well as any AddAttributes or AddService method calls.

Resource Environment Variables with Examples

OTEL_SERVICE_NAME=”dotnet-service”

OTEL_RESOURCE_ATTRIBUTES=”cx.application.name=dotnet-application,cx.subsystem.name=logging-test”

ILogger Logger

This variable provides access to the logger used to submit log messages with different severity to the pipeline. This is a standard .NET feature.

Disposal

The ILogger framework is asynchronous. As a result, it does not submit all log messages during application termination. To ensure all logs are submitted, verify that you Dispose() the LoggerFactory while handling errors or performing shutdown.

Need help? We love to assist our customers, simply reach out via our in-app chat, and we will walk you through, step by step.

On this page