Logging for JavaScript SDK
The PubNub JavaScript SDK writes log messages to a built-in console logger and to any custom loggers you register, and it filters them by the logLevel setting. PubNub SDK logging is disabled by default. Set logLevel when you create the PubNub instance to turn logging on.
1
For the other initialization settings, including userId, refer to Configuration. To use logs when you contact PubNub Support, refer to Troubleshooting.
Log levels
The SDK uses six log levels, from most to least verbose. A level records its own messages and the messages of every less verbose level listed after it.
| Level | Logs |
|---|---|
LogLevel.Trace | Every detail, including function calls, full payloads, internal variables, and state-machine transitions. The built-in console logger also prints request and response headers at this level. |
LogLevel.Debug | SDK logic, including inputs and outputs of public methods, HTTP (Hypertext Transfer Protocol) requests and responses, and configuration properties. |
LogLevel.Info | Significant events such as successful initialization and connection status changes. |
LogLevel.Warn | Non-fatal events, including deprecation warnings, request retries, and unusual conditions. |
LogLevel.Error | Errors, exceptions with stack traces, and HTTP failures. |
LogLevel.None | Nothing. Logging is disabled, which is the default. |
Console logger
The SDK always registers the built-in console logger alongside the loggers you pass in loggers, so every log entry reaches all of them. The console logger writes to the browser JavaScript console and to the Node.js console. It prints each entry as an ISO 8601 timestamp, PubNub- plus the instance identifier, the level, the location, and the message. It writes Trace entries with console.debug.
Custom loggers
Implement the Logger interface and pass instances in the loggers array to route logs to monitoring services, databases, or files. Custom loggers receive the same filtered entries as the console logger.
Logger interface
The Logger interface has one method for each log level.
1/**
2 * Custom logger interface
3 */
4interface Logger {
5 /**
6 * Process a trace-level message
7 * @param message - Structured log message
8 */
9 trace(message: LogMessage): void;
10
11 /**
12 * Process a debug-level message
13 * @param message - Structured log message
14 */
15 debug(message: LogMessage): void;
show all 34 linesThe SDK calls only the methods that correspond to the configured log level and above. For example, if you set logLevel to LogLevel.Warn, the SDK calls only warn() and error().
LogMessage fields
Each LogMessage object carries the following fields, which the BaseLogMessage interface defines.
| Field | Type | Description |
|---|---|---|
timestamp | Date | When the SDK created the log entry. |
pubNubId | string | PubNub instance identifier (a hash of the instance ID). |
level | LogLevel | Log level of this entry. |
minimumLevel | LogLevel | Minimum configured log level. Use it to print more detail only when the configured level is low. |
location | string | Source class or method that generated the entry, when available. |
messageType | string | Type of the message content: 'text', 'object', 'error', 'network-request', or 'network-response'. |
message | depends on messageType | The log content. |
Custom logger example
The following logger sends errors and failed requests to a monitoring service. In TypeScript, narrowing on messageType gives you autocomplete for the type-specific fields. The example assumes that monitoringService and analyticsService are objects in your application.
1
Multiple custom loggers
Pass several loggers in the loggers array to handle entries for different purposes.
1
Write logs to a file in Node.js
Implement a custom logger to write entries to a file. Implement log rotation yourself, because the stream appends to the file without limit.
1
Log message types
The SDK generates five types of log messages, and each type has its own TypeScript interface. The examples show the shape of the object that a logger receives.
Text messages (TextLogMessage)
The message field contains a string.
{
timestamp: Date,
pubNubId: 'pn-abc123',
level: LogLevel.Info,
minimumLevel: LogLevel.Debug,
location: 'PubNub',
messageType: 'text',
message: 'PubNub client initialized successfully'
}
Object messages (ObjectLogMessage)
The message field contains an object, an array, or another value. The optional details field describes the object, and the optional ignoredKeys field lists keys, or a function that selects keys, to leave out of the serialized object.
{
timestamp: Date,
pubNubId: 'pn-abc123',
level: LogLevel.Debug,
minimumLevel: LogLevel.Debug,
location: 'Configuration',
messageType: 'object',
message: { subscribeKey: 'sub-c-...', ssl: true, ... },
details: 'Client configuration:'
}
Error messages (ErrorLogMessage)
The message field contains a PubNubError object with error details and optional status information.
{
timestamp: Date,
pubNubId: 'pn-abc123',
level: LogLevel.Error,
minimumLevel: LogLevel.Debug,
location: 'PublishRequest',
messageType: 'error',
message: {
name: 'PubNubError',
message: 'Publish failed',
stack: '...',
status: { category: 'PNNetworkIssuesCategory', ... }
}
}
Network request messages (NetworkRequestLogMessage)
The message field contains a TransportRequest object. The optional details, canceled, and failed fields describe the request status.
{
timestamp: Date,
pubNubId: 'pn-abc123',
level: LogLevel.Debug,
minimumLevel: LogLevel.Debug,
location: 'PublishRequest',
messageType: 'network-request',
message: {
method: 'POST',
origin: 'https://ps.pndsn.com',
path: '/publish/...',
headers: { 'Content-Type': 'application/json' },
body: '{"message":"Hello"}',
queryParameters: { uuid: 'myUserId' }
},
show all 18 linesNetwork response messages (NetworkResponseLogMessage)
The message field contains a TransportResponse object with the status code, headers, and response body.
{
timestamp: Date,
pubNubId: 'pn-abc123',
level: LogLevel.Debug,
minimumLevel: LogLevel.Debug,
location: 'PublishRequest',
messageType: 'network-response',
message: {
status: 200,
url: 'https://ps.pndsn.com/publish/...',
headers: { 'content-type': 'application/json' },
body: ArrayBuffer // here, the bytes of [1,"Sent","15234567890123456"]
}
}
On Node.js, network-response log messages also carry a details field with a best-effort hint about the negotiated transport protocol, for example Negotiated protocol: h2 or Negotiated protocol: unknown. The SDK reads this value from the TLS ALPN result of the most recently connected socket. Under connection pooling or concurrent requests to different origins, it may reflect a different socket than the one that served this response. The value is unknown when the request went through an HTTP proxy dispatcher, or over plain HTTP without TLS. Treat it as an informational hint, not an authoritative per-request value.
The details field is not present in browser or React Native network-response logs, because ALPN observation only happens in the Node.js transport. For configuration details, refer to HTTP/2.
Sensitive data in logs
Do not enable Debug or Trace logging in production environments that handle sensitive information. These levels can expose:
- Complete request and response bodies, including the full token string that
grantTokencalls return. - Complete request URLs, including the Access Manager
signature,auth, andtimestampquery parameters of signed requests. - API keys and authentication tokens.
- Message content and metadata.
The ignoredKeys field filters keys only in object log messages. It does not redact the URLs or bodies that the SDK logs for network requests and responses, so it does not hide tokens or signatures that appear there.
Deprecated logVerbosity
The logVerbosity boolean setting is deprecated. When you set it to true, the SDK sets logLevel to LogLevel.Debug, ignoring any logLevel you pass, and logs a deprecation warning. Use logLevel instead.
Related tasks
- Configuration. Set
logLevel,loggers, and the other initialization settings. - Status events. Look up the status categories that appear in logged errors.
- Troubleshooting. Match a symptom to a cause and a fix.