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

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
PNNoneLogLevelLogging disabled. Default setting.
PNTraceLogLevelInternal operations including method calls, state-machine transitions, and detailed execution flow.
PNDebugLogLevelUser inputs, API (Application Programming Interface) parameters, HTTP (Hypertext Transfer Protocol) requests and responses, and operation results.
PNInfoLogLevelSignificant events including successful initialization and configuration changes.
PNWarnLogLevelDeprecation warnings, unusual conditions, and non-breaking validation warnings.
PNErrorLogLevelErrors, exceptions, and configuration conflicts.

Each level automatically includes messages from all higher severity levels. The hierarchy is: ERROR → WARN → INFO → DEBUG → TRACE.

Logging sensitive information

The PNDebugLogLevel and PNTraceLogLevel settings may log sensitive information including API keys, user identifiers, message content, complete request URLs (with the Access Manager auth token attached as a query parameter), and the full token string returned by grantToken calls. PNDebugLogLevel already logs the complete request URL, not just PNTraceLogLevel. 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 identifierFormat: 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 levelThe severity level: TRACE, DEBUG, INFO, WARN, or ERROR.
LocationThe SDK component generating the log entry, such as "PubNub".
TimestampThe date and time when the SDK created the log entry.
MessageThe log content describing the operation or event.
Message typeThe data type:
  • PNTextLogMessageType (PNStringLogEntry)
  • PNObjectLogMessageType (PNDictionaryLogEntry)
  • PNErrorLogMessageType (PNErrorLogEntry)
  • PNNetworkRequestLogMessageType (PNNetworkRequestLogEntry)
  • PNNetworkResponseLogMessageType (PNNetworkResponseLogEntry)
OperationThe 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
messageThe log payload. Can be a string, dictionary, error, network request, or network response.
messageTypeThe message type indicating the data structure of the message property.
operationThe API operation such as subscribe, publish, or presence.
logLevelThe log level: trace, debug, info, warn, or error.
minimumLogLevelThe minimum log level configured for the client instance.
pubNubIdThe PubNub instance identifier.
locationThe SDK component generating the log entry.
timestampThe date and time when the SDK created the log entry.
detailsOptional additional context for the log entry.

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
ProductionPNErrorLogLevel to capture critical issues without performance impact.
StagingPNInfoLogLevel to monitor operational events.
DevelopmentPNDebugLogLevel to investigate issues and verify behavior.
Deep troubleshootingPNTraceLogLevel 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
  • Complete request URLs at DEBUG level, including the Access Manager auth token attached as a query parameter
  • The full token string returned by grantToken calls, since response bodies are logged in full at DEBUG

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 windowConnect 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 toolsConnect 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 SharingEnable 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 email to PubNub Support to help resolve issues faster.

Configuration reference​

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

Was this page useful?

Last updated on