---
source_url: https://www.pubnub.com/docs/sdks/c-sharp/logging
title: Logging for C# SDK
updated_at: 2026-05-25T11:27:26.237Z
sdk_name: PubNub C# SDK
sdk_version: 8.2.0
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Logging for C# SDK

PubNub C# SDK, use the latest version: 8.2.0

Install:

```bash
dotnet add package PubNub@8.2.0
```

This page explains how to configure logging in the PubNub C# Software Development Kit (SDK) using log levels and custom loggers.

## Logging architecture

The C# SDK provides a flexible logging system. You can configure the logging system for different environments and use cases:

* Log levels control logging verbosity from detailed trace logs to errors only
* Built-in default logger automatically outputs to System.Diagnostics.Debug
* Custom loggers allow you to add custom logger implementations via the `SetLogger()` method
* Multiple logger support enables simultaneous logging to different destinations

The SDK sends all log entries to both the built-in default logger and any configured custom loggers simultaneously.

## Log levels

The SDK uses five log levels. Each level controls the amount of detail captured. Each level also includes messages from all higher severity levels.

| Level | Purpose |
| --- | --- |
| `PubnubLogLevel.Trace` | Internal operations: serialization, encryption, and detailed execution flow |
| `PubnubLogLevel.Debug` | User inputs, API (Application Programming Interface) parameters, HTTP (Hypertext Transfer Protocol) requests and responses, and configuration properties |
| `PubnubLogLevel.Info` | Significant events like successful initialization and configuration changes |
| `PubnubLogLevel.Warn` | Deprecation warnings, unusual conditions, and non-breaking validation warnings |
| `PubnubLogLevel.Error` | Errors, exceptions with stack traces, and failed operations |

Additional levels:

* `PubnubLogLevel.All` enables all log levels (equivalent to `Trace`)
* `PubnubLogLevel.None` disables logging (default)

The SDK logs all configuration properties at `Debug` level during initialization. Secret keys are masked.

## Enable logging

Set the `LogLevel` parameter during SDK initialization to enable logging:

```csharp
using PubnubApi;

var pubnubConfiguration = new PNConfiguration(new UserId("uniqueUserId"))
{
    SubscribeKey = "[yourSubscribeKey]",
    PublishKey = "[yourPublishKey]",
    LogLevel = PubnubLogLevel.Debug,
};
var pubnub = new Pubnub(pubnubConfiguration);

var customLogger = new PubnubConsoleLogger();
pubnub.SetLogger(customLogger);

// To remove the custom logger. Use RemoveLogger().
pubnub.RemoveLogger(customLogger);
```

:::note Required User ID
Always set the `UserId` to uniquely identify the user or device that connects to PubNub. This `UserId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `UserId`, you won't be able to connect to PubNub.
:::

## Custom loggers

Implement the `IPubnubLogger` interface to route logs to external monitoring services, databases, or analytics platforms. Custom loggers work alongside the built-in default logger.

### IPubnubLogger interface

The `IPubnubLogger` interface defines five methods:

```csharp
public interface IPubnubLogger
{
    void Trace(string logMessage);
    void Debug(string logMessage);
    void Info(string logMessage);
    void Warn(string logMessage);
    void Error(string logMessage);
}
```

The SDK calls only the methods that correspond to the configured log level and above. For example, if you set `LogLevel` to `PubnubLogLevel.Warn`, the SDK calls only the `Warn()` and `Error()` methods.

### Custom logger example

```csharp
using PubnubApi;

// A custom logger that logs information on console.
// Use can implement logger that can log information using log4Net or file etc.
public class PubnubConsoleLogger : IPubnubLogger
{
    public void Trace(string traceLog) =>
        Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [TRACE] {traceLog}");

    public void Debug(string debugLog) =>
        Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [DEBUG] {debugLog}");

    public void Info(string infoLog) =>
        Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [INFO] {infoLog}");

    public void Warn(string warningLog) => 
        Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [WARN] {warningLog}");

    public void Error(string errorLog) => 
        Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.InvariantCulture)}] [ERROR] {errorLog}");
}
```

Configure the SDK with your custom logger:

```csharp
var pubnubConfiguration = new PNConfiguration(new UserId("uniqueUserId"))
{
    SubscribeKey = "[yourSubscribeKey]",
    PublishKey = "[yourPublishKey]",
    LogLevel = PubnubLogLevel.Debug,
};
var pubnub = new Pubnub(pubnubConfiguration);

// Add custom logger
var customLogger = new PubnubConsoleLogger();
pubnub.SetLogger(customLogger);

// To remove the custom logger
pubnub.RemoveLogger(customLogger);
```

### Multiple custom loggers

You can add multiple custom loggers for different purposes:

```csharp
var pubnub = new Pubnub(pubnubConfiguration);

// Add multiple loggers
var consoleLogger = new PubnubConsoleLogger();
var fileLogger = new PubnubFileLogger();
var monitoringLogger = new PubnubMonitoringLogger();

pubnub.SetLogger(consoleLogger);
pubnub.SetLogger(fileLogger);
pubnub.SetLogger(monitoringLogger);
```

Each logger receives the same log entries based on the configured log level.

## Logged information

The C# SDK logs information at various stages of operation. This provides complete visibility into SDK behavior.

### Configuration at initialization

When you create a PubNub instance, the SDK logs all configuration properties. The SDK also logs any subsequent changes to these properties.

Each configuration log entry includes:

* Instance identifier (unique ID)
* SDK version information
* All configuration property names and values

:::note No secret keys in logs
Secret keys are never logged.
:::

### API call parameters

The SDK logs all user-provided input data for each API call. The SDK captures this information at the `Debug` level.

Logged parameters include:

* Channel names and channel groups
* Messages and metadata
* Timetoken values
* Filter expressions
* Custom query parameters

These logs help identify mismatches. You can compare expected input with actual data passed to endpoints.

### Network requests and responses

The SDK logs complete HTTP transaction information at the `Debug` level:

* HTTP method (GET, POST, PATCH, DELETE)
* Complete URL with query parameters
* Request headers as key-value pairs
* Request body content (for POST, PUT, or PATCH requests)
* Timestamp

Response logs include:

* HTTP status code
* Response body content
* Request URL for correlation

Network logs help troubleshoot connectivity issues. Network logs also show exactly what data flows between your application and PubNub servers.

## Log entry structure

Each log entry from the C# SDK includes these essential components:

| Component | Description |
| --- | --- |
| Timestamp | Human-readable date and time. |
| Instance identifier | Format like `PubNub-{instanceId}`. Distinguishes logs from multiple SDK instances. |
| Log level | `Trace`, `Debug`, `Info`, `Warn`, or `Error`. |
| Message | The log content describing the operation or event. |

### Filter logs from multiple instances

Your application may create multiple PubNub instances. Multiple sources may also write to the same log destination.

The instance-specific identifier helps you filter and differentiate logs. This simplifies troubleshooting and analysis in complex applications.

## Logging best practices

Use these recommendations for effective logging.

### Choose the right log level

| Environment | Recommended Log Level |
| --- | --- |
| Production | Enable `Error` and `Warn` to catch issues without performance impact. |
| Staging | Use `Info` to monitor operational events. |
| Development | Enable `Debug` when actively developing or investigating issues. |
| Deep troubleshooting | Use `Trace` only with guidance from PubNub support. |

### Protect sensitive data

Never enable `Debug` or `Trace` logging in production environments that handle sensitive information.

These levels may expose:

* API keys
* User identifiers
* Message content

### Provide complete context to support

When reporting issues to [PubNub support](https://support.pubnub.com/), provide complete logs:

* SDK initialization and configuration
* The complete sequence leading to the issue

### Monitor log volume

`Trace` and `Debug` levels generate significant output. Ensure your logging infrastructure can handle the volume. This is especially important in high-throughput applications.

### Disable logging when not needed

Turn off logging in production or set the log level to `Error` only. This optimizes performance and reduces storage costs.

For more information about configuration parameters, refer to [Configuration](https://www.pubnub.com/docs/sdks/c-sharp/api-reference/configuration).