For AI agents: this page in Markdown: https://www.pubnub.com/docs/sdks/c-sharp/logging.md. Documentation index: https://www.pubnub.com/llms-full.txt.

Logging for C# SDK

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.

LevelPurpose
PubnubLogLevel.TraceInternal operations: serialization, encryption, and detailed execution flow
PubnubLogLevel.DebugUser inputs, API (Application Programming Interface) parameters, HTTP (Hypertext Transfer Protocol) requests and responses, and configuration properties
PubnubLogLevel.InfoSignificant events like successful initialization and configuration changes
PubnubLogLevel.WarnDeprecation warnings, unusual conditions, and non-breaking validation warnings
PubnubLogLevel.ErrorErrors, 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:

1

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:

1public interface IPubnubLogger
2{
3 void Trace(string logMessage);
4 void Debug(string logMessage);
5 void Info(string logMessage);
6 void Warn(string logMessage);
7 void Error(string logMessage);
8}

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​

1

Configure the SDK with your custom logger:

1var pubnubConfiguration = new PNConfiguration(new UserId("uniqueUserId"))
2{
3 SubscribeKey = "[yourSubscribeKey]",
4 PublishKey = "[yourPublishKey]",
5 LogLevel = PubnubLogLevel.Debug,
6};
7var pubnub = new Pubnub(pubnubConfiguration);
8
9// Add custom logger
10var customLogger = new PubnubConsoleLogger();
11pubnub.SetLogger(customLogger);
12
13// To remove the custom logger
14pubnub.RemoveLogger(customLogger);

Multiple custom loggers​

You can add multiple custom loggers for different purposes:

1var pubnub = new Pubnub(pubnubConfiguration);
2
3// Add multiple loggers
4var consoleLogger = new PubnubConsoleLogger();
5var fileLogger = new PubnubFileLogger();
6var monitoringLogger = new PubnubMonitoringLogger();
7
8pubnub.SetLogger(consoleLogger);
9pubnub.SetLogger(fileLogger);
10pubnub.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
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:

ComponentDescription
TimestampHuman-readable date and time.
Instance identifierFormat like PubNub-{instanceId}. Distinguishes logs from multiple SDK instances.
Log levelTrace, Debug, Info, Warn, or Error.
MessageThe 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​

EnvironmentRecommended Log Level
ProductionEnable Error and Warn to catch issues without performance impact.
StagingUse Info to monitor operational events.
DevelopmentEnable Debug when actively developing or investigating issues.
Deep troubleshootingUse 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
  • Complete request and response URLs at Debug level, including Access Manager signature and auth token query parameters used for signed requests (for example, when calling GrantToken)

Provide complete context to support​

When reporting issues to PubNub support, 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.

Was this page useful?

Last updated on