Logging for Go SDK
This page explains how to configure logging in the PubNub Go Software Development Kit (SDK). Logging helps you monitor SDK activity, troubleshoot issues, and maintain audit trails during development and production.
For general logging concepts and best practices applicable to all PubNub SDKs, see Logging.
Logging architecture
The Go SDK provides a flexible logging system with the following features:
- Structured logging: Log entries include typed content for different contexts (simple messages, network requests/responses, errors, user input).
- Custom loggers: Implement the
PNLoggerinterface to route logs to external monitoring services, databases, or analytics platforms. - Multiple logger support: Register multiple loggers simultaneously. All loggers receive the same log entries.
- Built-in default logger: The SDK includes a
DefaultLoggerthat outputs formatted logs to console or anyio.Writer. - Per-logger log levels: Each logger can set its own minimum log level threshold.
Logging is disabled by default to optimize performance in production environments.
Log levels
The SDK uses standard log levels to control the amount of detail captured:
| Level | Purpose |
|---|---|
PNLogLevelTrace | Internal operations including detailed execution flow, method calls, and state transitions. |
PNLogLevelDebug | User inputs, API (Application Programming Interface) parameters, HTTP (Hypertext Transfer Protocol) requests and responses, and operation results. |
PNLogLevelInfo | Significant events including successful initialization, SDK version, and configuration summary. |
PNLogLevelWarn | Configuration validation warnings, deprecations, and non-breaking issues. |
PNLogLevelError | Errors, exceptions, and failed operations. |
PNLogLevelNone | Logging disabled. |
Each level automatically includes messages from all higher severity levels. The hierarchy is: ERROR → WARN → INFO → DEBUG → TRACE.
Logging sensitive information
The PNLogLevelDebug and PNLogLevelTrace settings may log sensitive information including API (Application Programming Interface) keys, user identifiers, and message content. Use these levels only in development environments. Never enable DEBUG or TRACE logging in production environments with sensitive data.
Enable logging
Configure logging when creating your PubNub client by adding loggers to the Loggers slice in the configuration.
Use the default logger
The SDK provides a DefaultLogger that outputs to console:
1
The SDK automatically logs the complete configuration at initialization, including:
- SDK version and Go runtime information
- User ID and subscribe key
- Publish key (if set)
- Configuration parameters (sensitive fields like
SecretKeyandCipherKeyare masked with***) - Number of registered loggers
Write logs to a file
Use NewDefaultLoggerWithWriter to direct logs to a file:
1
Backward compatibility with log.Logger
The SDK maintains backward compatibility with the deprecated Log *log.Logger field. When you set config.Log, the SDK automatically creates a DefaultLogger with PNLogLevelDebug and bridges it to the new logging system. The Log field will be removed in a future major version. Use the Loggers []PNLogger field for enhanced logging capabilities.
Logged information
The SDK logs information at various stages of operation.
SDK initialization
The SDK logs initialization details at the INFO level, including:
- PubNub Go SDK version
- Go runtime version and platform (operating system (OS) and architecture)
- Complete configuration with sensitive fields masked
Example log:
02/01/2024 14:23:45.123 PubNub-a1b2c3d4 Info PubNub Go SDK v8.0.0 initialized
Go: go1.21.0 darwin/arm64
Config{
PublishKey: demo
SubscribeKey: demo
SecretKey: ***
...
}
Configuration validation warnings
The SDK logs validation warnings at the WARN level during initialization when it detects configuration issues:
02/01/2024 14:23:45.124 PubNub-a1b2c3d4 Warn Config validation: PresenceTimeout value 15 is less than the min recommended value of 20, adjusting to 20
API call parameters
The SDK logs user-provided input data for each API (Application Programming Interface) call at the DEBUG level. These logs help identify mismatches between expected and actual parameters.
02/01/2024 14:23:45.234 PubNub-a1b2c3d4 Debug PNPublishOperation with parameters:
Channel: demo-channel
Message: Hello World
Meta: map[sender:user123]
Network requests and responses
The SDK logs complete HTTP (Hypertext Transfer Protocol) transaction information at the DEBUG level:
Request logs include
- HTTP method (GET, POST, PATCH, DELETE)
- Complete URL with query parameters
- Request headers as key-value pairs
- Request body content (for POST or PATCH requests)
- File location where the request was initiated
Response logs include
- HTTP status code
- Response body content
- Request URL for correlation
- File location where the response was received
Example request log:
02/01/2024 14:23:45.235 PubNub-a1b2c3d4 Debug request.go:193 Sending HTTP request POST https://ps.pndsn.com/publish/demo/demo/0/demo-channel/0/%7B%22text%22%3A%22Hello%22%7D with headers: map[Content-Type:application/json] body: {"text":"Hello"}
Example response log:
02/01/2024 14:23:45.456 PubNub-a1b2c3d4 Debug request.go:245 Received response with 200 content [1,\"Sent\",\"16891234567890123\"] for request url https://ps.pndsn.com/publish/demo/demo/0/demo-channel/0/%7B%22text%22%3A%22Hello%22%7D
Network logs help troubleshoot connectivity issues. Network logs also show exactly what data flows between your application and PubNub servers.
Errors and exceptions
The SDK logs errors at the ERROR level with contextual information:
- Error description
- Error name or type
- Associated API operation (if applicable)
- File location where the error occurred
Example error log:
02/01/2024 14:23:45.789 PubNub-a1b2c3d4 Error request.go:151 Error CreateRequestFailed in PNPublishOperation: invalid character 'x' looking for beginning of value
Log entry structure
Each log entry includes the following components:
| Component | Description |
|---|---|
| Timestamp | Date and time when the SDK created the log entry in format DD/MM/YYYY HH:MM:SS.mmm. |
| Instance identifier | Format: PubNub-{instanceId} where instanceId is an 8-character random alphanumeric string. Use this identifier to filter logs from multiple SDK instances. |
| Log level | The severity level: Trace, Debug, Info, Warn, or Error. |
| Callsite | Optional. The file name and line number where the log was generated (e.g., request.go:193). Included for some debug-level logs and errors. |
| Message | The log content describing the operation or event. |
Custom loggers
Create custom loggers to route log entries to external monitoring services, databases, or analytics platforms. Custom loggers must implement the PNLogger interface.
PNLogger interface
The PNLogger interface defines two methods:
1type PNLogger interface {
2 // Log outputs a log message
3 Log(logMsg LogMessage)
4 // GetMinLogLevel returns the minimum log level for this logger
5 GetMinLogLevel() PNLogLevel
6}
Custom logger example
This example shows a custom logger that outputs structured logs with type-specific information:
1
Use multiple loggers
Use the built-in default logger and custom loggers simultaneously:
1
The SDK sends every log entry that meets each logger's minimum level threshold to all registered loggers. In this example:
- Console logger receives only messages at
ERRORlevel - File logger receives all messages at
DEBUGlevel and above
Logging best practices
Choose the appropriate log level
| Environment | Recommended Log Level |
|---|---|
| Production | PNLogLevelError to capture critical issues without performance impact. |
| Staging | PNLogLevelInfo to monitor operational events. |
| Development | PNLogLevelDebug to investigate issues and verify behavior. |
| Deep troubleshooting | PNLogLevelTrace when working with PubNub support on complex issues. |
Protect sensitive data
Never enable PNLogLevelDebug or PNLogLevelTrace in production environments that handle sensitive information.
These levels may expose:
- API keys and authentication tokens
- User identifiers and personal information
- Message content and metadata
- Request and response payloads
The SDK automatically masks sensitive configuration fields (SecretKey, CipherKey) in configuration logs, but DEBUG and TRACE levels may expose sensitive data in network requests and API parameters.
Use custom loggers for production
Implement custom loggers that integrate with your monitoring and observability infrastructure. Use multiple loggers to send different log levels to different destinations. For example, send errors and warnings to your monitoring service while logging all information to a file for debugging.
Optimize logging performance
Minimize logging overhead in production:
- Set minimum log level to
PNLogLevelWarnorPNLogLevelError - Use custom loggers that buffer and batch log entries
- Avoid expensive operations in custom logger implementations
1// Minimal logging for production
2config.Loggers = []pubnub.PNLogger{
3 pubnub.NewDefaultLogger(pubnub.PNLogLevelError),
4}
5
6// Disable logging completely (empty slice)
7config.Loggers = []pubnub.PNLogger{}
Provide logs to support
When reporting issues to PubNub support, include complete logs:
- Set the log level to
PNLogLevelDebugorPNLogLevelTrace - Reproduce the issue
- Collect logs from initialization through the problem occurrence
- Include the PubNub SDK version (visible in initialization logs)
Configuration reference
For complete details on all configuration options, see the Configuration reference.