On this page

Logging for Objective-C SDK

This page explains how to configure logging in the PubNub Objective-C Software Development Kit (SDK) for iOS and macOS applications. 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 in pre-6.0.0 versions

This logging documentation applies to Objective-C SDK version 6.0.0 and later. Older versions used the legacy [PNLog enabled:YES] method, which is no longer supported.

Logging architecture

The Objective-C SDK provides a flexible logging system with the following features:

  • Built-in loggers: The SDK includes a console logger (PNConsoleLogger) that prints to Xcode console and a file logger (PNFileLogger) that writes to disk with automatic rotation.
  • Custom loggers: Implement the PNLogger protocol to route logs to external monitoring services, databases, or analytics platforms.
  • Multiple logger support: Use built-in and custom loggers simultaneously. All registered loggers receive the same log entries.
  • Structured log entries: Each log includes an instance identifier, timestamp, log level, operation type, and typed content.

Logging is disabled by default (PNNoneLogLevel) to optimize performance in production environments.

Log levels

The SDK uses standard log levels to control the amount of detail captured:

LevelPurpose
PNNoneLogLevel
Logging disabled. Default setting.
PNTraceLogLevel
Internal operations including method calls, state-machine transitions, and detailed execution flow.
PNDebugLogLevel
User inputs, API (Application Programming Interface) parameters, HTTP (Hypertext Transfer Protocol) requests and responses, and operation results.
PNInfoLogLevel
Significant events including successful initialization and configuration changes.
PNWarnLogLevel
Deprecation warnings, unusual conditions, and non-breaking validation warnings.
PNErrorLogLevel
Errors, exceptions, and configuration conflicts.

Each level automatically includes messages from all higher severity levels. The hierarchy is: ERRORWARNINFODEBUGTRACE.

Logging sensitive information

The PNDebugLogLevel and PNTraceLogLevel settings may log sensitive information including API 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 setting the logLevel property on the configuration object.

1PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
2 subscribeKey:@"demo"
3 userID:@"myUniqueUserID"];
4
5// Set log level to DEBUG
6configuration.logLevel = PNDebugLogLevel;
7
8PubNub *client = [PubNub clientWithConfiguration:configuration];

Change log level at runtime

Adjust the log level after initialization using the setLogLevel: method:

1// Increase detail for troubleshooting
2[self.client setLogLevel:PNTraceLogLevel];
3
4// Reduce detail after resolving issues
5[self.client setLogLevel:PNErrorLogLevel];
6
7// Disable logging
8[self.client setLogLevel:PNNoneLogLevel];

Logged information

The SDK logs information at various stages of operation:

API call parameters

The SDK logs all user-provided input data for each API call at the PNDebugLogLevel setting. These logs help identify mismatches between expected and actual parameters.

Example log:

[PubNub-a1b2c3] DEBUG - Manage push-enabled channels with parameters:
{
channels = ["channel-a", "channel-b"];
deviceToken = "<token-data>";
pushType = "APNS2";
}

Network requests and responses

The SDK logs complete HTTP transaction information at the PNDebugLogLevel setting.

Request logs

  • HTTP method: GET, POST, PATCH, or DELETE
  • Complete URL with query parameters
  • Request headers as key-value pairs
  • Request body content for POST, PUT, or PATCH requests
  • Timestamp with millisecond precision

Response logs

  • HTTP status code
  • Response body content
  • Request URL for correlation with the originating request
  • Timestamp when the SDK received the response

Operation results

The SDK logs success and failure messages for API operations at the PNDebugLogLevel setting.

Example success log:

[PubNub-a1b2c3] DEBUG - Manage push-enabled channels success.

Example failure log:

[PubNub-a1b2c3] ERROR - Failed to process request: Network connection lost

Errors and warnings

The SDK logs errors at the PNErrorLogLevel setting and warnings at the PNWarnLogLevel setting.

Example error log:

[PubNub-a1b2c3] ERROR - It is expected that only cipherKey or cryptoModule will be 
configured at once. PubNub client will use the configured cryptoModule.

Log entry structure

Each log entry includes:

ComponentDescription
Instance identifier
Format: PubNub-{shortId} where shortId represents the first 6 characters of the instance UUID (Universally Unique Identifier). Use this identifier to filter logs from multiple SDK instances.
Log level
The severity level: TRACE, DEBUG, INFO, WARN, or ERROR.
Location
The SDK component generating the log entry, such as "PubNub".
Timestamp
The date and time when the SDK created the log entry.
Message
The log content describing the operation or event.
Message type
The data type:
  • PNTextLogMessageType (PNStringLogEntry)
  • PNObjectLogMessageType (PNDictionaryLogEntry)
  • PNErrorLogMessageType (PNErrorLogEntry)
  • PNNetworkRequestLogMessageType (PNNetworkRequestLogEntry)
  • PNNetworkResponseLogMessageType (PNNetworkResponseLogEntry)
Operation
The API operation associated with the log, such as subscribe, publish, or presence.

Filter logs from multiple instances

Applications that create multiple PubNub instances can filter logs using the instance identifier.

1// First instance
2PubNub *client1 = [PubNub clientWithConfiguration:config1];
3// Log entries display: [PubNub-a1b2c3] ...
4
5// Second instance
6PubNub *client2 = [PubNub clientWithConfiguration:config2];
7// Log entries display: [PubNub-d4e5f6] ...

Filter the Xcode console by entering the specific instance identifier in the search field.

Built-in loggers

Console logger

The PNConsoleLogger prints log entries to the Xcode console. The SDK enables this logger by default when you set a log level other than PNNoneLogLevel.

To disable the console logger:

1PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
2 subscribeKey:@"demo"
3 userID:@"myUniqueUserID"];
4configuration.logLevel = PNDebugLogLevel;
5configuration.enableDefaultConsoleLogger = NO; // Disable default logger output to the Xcode console
6
7PubNub *client = [PubNub clientWithConfiguration:configuration];

File logger

The PNFileLogger writes log entries to disk with automatic rotation. Use this logger for production environments where console output is not available.

1#import <PubNub/PNFileLogger.h>
2
3// Specify log directory path
4NSString *logsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
5 NSUserDomainMask,
6 YES).firstObject
7 stringByAppendingPathComponent:@"PubNubLogs"];
8
9// Create file logger
10PNFileLogger *fileLogger = [PNFileLogger loggerWithLogsDirectoryPath:logsPath];
11
12// Configure rotation settings
13fileLogger.maximumLogFileSize = 5 * 1024 * 1024; // 5 MB per file
14fileLogger.maximumNumberOfLogFiles = 10; // Keep 10 files
15fileLogger.logFilesDiskQuota = 50 * 1024 * 1024; // 50 MB total
show all 24 lines

File logger properties

PropertyDescription
maximumLogFileSize
Default:
1 MB
Maximum single log file size in bytes. The logger creates a new file when this limit is reached.
maximumNumberOfLogFiles
Default:
5
Maximum number of log files to retain after rotation. The logger deletes the oldest files when this limit is exceeded.
logFilesDiskQuota
Default:
20 MB
Maximum total size of the logs directory in bytes. The logger removes old files to maintain this quota.

Custom loggers

Create custom loggers to route log entries to external monitoring services, databases, or analytics platforms. Custom loggers must implement the PNLogger protocol.

PNLogger protocol

The PNLogger protocol defines five methods:

1@protocol PNLogger <NSObject>
2
3- (void)traceWithMessage:(PNLogEntry *)message;
4- (void)debugWithMessage:(PNLogEntry *)message;
5- (void)infoWithMessage:(PNLogEntry *)message;
6- (void)warnWithMessage:(PNLogEntry *)message;
7- (void)errorWithMessage:(PNLogEntry *)message;
8
9@end

Each method receives a PNLogEntry object with the following properties:

PropertyDescription
message
The log payload. Can be a string, dictionary, error, network request, or network response.
messageType
The message type:
  • PNTextLogMessageType (PNStringLogEntry)
  • PNObjectLogMessageType (PNDictionaryLogEntry)
  • PNErrorLogMessageType (PNErrorLogEntry)
  • PNNetworkRequestLogMessageType (PNNetworkRequestLogEntry)
  • PNNetworkResponseLogMessageType (PNNetworkResponseLogEntry)
operation
The API operation such as subscribe, publish, or presence.
logLevel
The log level: trace, debug, info, warn, or error.
minimumLogLevel
The minimum log level configured for the client instance.
pubNubId
The PubNub instance identifier.
location
The SDK component generating the log entry.
timestamp
The date and time when the SDK created the log entry.
details
Optional additional context for the log entry.

PNLogEntry subclasses

PNLogEntry is the base class containing the common properties shown in the table above. Each messageType value corresponds to a specific subclass that inherits from PNLogEntry and may include additional type-specific properties:

messageType ValueSubclassAdditional Properties
PNTextLogMessageType
PNStringLogEntry
message property returns NSString *
PNObjectLogMessageType
PNDictionaryLogEntry
message property returns NSDictionary *
ignoredKeys property of type NSArray<NSString *> * or block for filtering sensitive data
PNErrorLogMessageType
PNErrorLogEntry
message property returns NSError * with error details and optional status information
PNNetworkRequestLogMessageType
PNNetworkRequestLogEntry
message property returns PNNetworkRequest *
canceled property indicates if request was canceled
failed property indicates if request failed
PNNetworkResponseLogMessageType
PNNetworkResponseLogEntry
message property returns PNNetworkResponse * with status code, headers, and response body

Use type checking and casting to access subclass-specific properties:

1- (void)errorWithMessage:(PNLogEntry *)logEntry {
2 if (logEntry.messageType == PNErrorLogMessageType) {
3 // Cast to subclass to access type-specific properties
4 PNErrorLogEntry *errorEntry = (PNErrorLogEntry *)logEntry;
5 NSError *error = errorEntry.message;
6
7 // Access NSError properties
8 NSLog(@"Error: %@ (code: %ld)", error.localizedDescription, (long)error.code);
9 } else if (logEntry.messageType == PNNetworkRequestLogMessageType) {
10 // Cast to access network request-specific properties
11 PNNetworkRequestLogEntry *requestEntry = (PNNetworkRequestLogEntry *)logEntry;
12
13 if (requestEntry.canceled || requestEntry.failed) {
14 PNNetworkRequest *request = requestEntry.message;
15 NSLog(@"Request failed: %@ %@", request.method, request.URL);
show all 18 lines

Custom logger example

1#import <PubNub/PubNub.h>
2
3@interface MonitoringLogger : NSObject <PNLogger>
4@end
5
6@implementation MonitoringLogger
7
8- (void)errorWithMessage:(PNLogEntry *)message {
9 // Handle errors
10 if (message.messageType == PNErrorLogMessageType) {
11 NSError *error = (NSError *)message.message;
12
13 // Send to monitoring service
14 [self.monitoringService reportError:error.localizedDescription
15 instanceId:message.pubNubId
show all 58 lines

Use multiple loggers

Use the built-in console logger and custom loggers simultaneously:

1MonitoringLogger *customLogger = [[MonitoringLogger alloc] init];
2
3PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
4 subscribeKey:@"demo"
5 userID:@"myUniqueUserID"];
6configuration.logLevel = PNDebugLogLevel;
7configuration.loggers = @[customLogger]; // Add custom logger
8
9PubNub *client = [PubNub clientWithConfiguration:configuration];

The SDK sends every log entry that meets the minimum log level threshold to all registered loggers.

Logging best practices

Choose the appropriate log level

EnvironmentRecommended Log Level
Production
PNErrorLogLevel to capture critical issues without performance impact.
Staging
PNInfoLogLevel to monitor operational events.
Development
PNDebugLogLevel to investigate issues and verify behavior.
Deep troubleshooting
PNTraceLogLevel when working with PubNub support on complex issues.

Protect sensitive data

Never enable PNDebugLogLevel or PNTraceLogLevel 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

Filter logs by instance identifier

Use the instance identifier to filter logs when debugging applications with multiple PubNub clients. Enter the instance identifier in the Xcode console search field to view logs from a specific instance.

Use file logger in production

Use PNFileLogger instead of console logging in production environments:

1PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:publishKey
2 subscribeKey:subscribeKey
3 userID:userID];
4configuration.logLevel = PNErrorLogLevel; // Capture errors only
5configuration.enableDefaultConsoleLogger = NO; // Disable default logger output to the Xcode console
6configuration.loggers = @[[PNFileLogger loggerWithLogsDirectoryPath:logsPath]];
7
8PubNub *client = [PubNub clientWithConfiguration:configuration];

Optimize logging performance

Disable logging or limit it to errors in production environments. This optimizes performance and reduces storage costs.

1// Capture errors only
2configuration.logLevel = PNErrorLogLevel;
3
4// Disable logging completely
5configuration.logLevel = PNNoneLogLevel;

Provide logs to support

When reporting issues to PubNub support, include complete logs:

  1. Set the log level to PNDebugLogLevel or PNTraceLogLevel.
  2. Reproduce the issue.
  3. Collect logs from initialization through the problem occurrence.
  4. Include the PubNub SDK version. Access the version using [PubNub information].

Collect device logs and crash reports

Gather crash reports and device logs from the App Store, TestFlight, and directly from devices in addition to PubNub SDK logs.

Access crash reports and device logs

For comprehensive debugging information, refer to Apple documentation:

Retrieve log files from devices

Retrieve log files created by PNFileLogger using one of these methods:

MethodSteps
Xcode Devices window
Connect the device to your computer. Open Xcode and select Window → Devices and Simulators. Select the device and application. Download the app container. Navigate to the logs directory. The default location is Documents/PubNubLogs.
Third-party file management tools
Connect the device to your computer. Open a tool such as iExplorer or similar applications. Browse to YourApp/Documents/PubNubLogs. Copy the log files to your computer.
File Sharing
Enable file sharing in the application Info.plist file. Access the files through iTunes on macOS Mojave or earlier, or through Finder on macOS Catalina and later.

Include log files in your support tickets to help resolve issues faster.

Configuration reference

For complete details on all configuration options, see Configuration API.

Last updated on