---
source_url: https://www.pubnub.com/docs/sdks/java/logging
title: Logging for Java SDK
updated_at: 2026-06-17T11:39:36.183Z
sdk_name: PubNub Java SDK
sdk_version: 6.4.5
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Logging for Java SDK

PubNub Java SDK, use the latest version: 6.4.5

Install:

```bash
Add PubNub dependency to your build@6.4.5
```

This page explains how to configure logging in the PubNub Java Software Development Kit (SDK) using SLF4J and custom loggers.

## Logging architecture

You can configure logging for different environments and use cases:

* SLF4J integration: All logs route through SLF4J, allowing you to use any SLF4J-compatible backend (`logback`, `log4j`, `slf4j-simple`, `commons-logging`, `java.util.logging`)
* Custom loggers: Optionally add custom logger implementations via the `customLoggers` configuration parameter. Use it if your `slf4j` implementation doesn't meet your needs.

The SDK sends all log entries to both `slf4j` and any configured custom loggers simultaneously.

## Log levels

SLF4J uses standard log levels:

| Level | Purpose |
| --- | --- |
| `TRACE` | Internal operations: serialization, encryption, subscription lifecycle, and detailed execution flow |
| `DEBUG` | User inputs, API parameters, HTTP requests and responses, and configuration properties |
| `INFO` | Significant events like successful initialization and configuration changes |
| `WARN` | Deprecation warnings, unusual conditions, and non-breaking validation warnings |
| `ERROR` | Errors, exceptions with stack traces, and failed operations |

The SDK logs all configuration properties at `DEBUG` level during initialization. Secret keys are masked.

## Custom loggers

You can implement the `CustomLogger` interface to implement your specific logging requirements, for example, route logs to external monitoring services, databases, or analytics platforms.

### CustomLogger interface

The `CustomLogger` interface supports string messages and structured `LogMessage` objects:

```java
public interface CustomLogger {
    String getName();
    
    // String-based logging methods
    void trace(String message);
    void debug(String message);
    void info(String message);
    void warn(String message);
    void error(String message);
    
    // Structured logging methods
    void trace(LogMessage logMessage);
    void debug(LogMessage logMessage);
    void info(LogMessage logMessage);
    void warn(LogMessage logMessage);
    void error(LogMessage logMessage);
}
```

The SDK calls both overloads for each log entry:

* String version - a simplified, human-readable message
* LogMessage version - structured data including instance ID, timestamp, location, and typed content

All methods have default no-op implementations, so you only need to override the ones you plan to use.

### Structured logging with LogMessage

`LogMessage` provides structured information for each log entry:

| Field | Description |
| --- | --- |
| `message` | The log content (one of: Text, Object, Error, NetworkRequest, or NetworkResponse) |
| `details` | Optional additional context |
| `type` | Automatically inferred from message content (TEXT, OBJECT, ERROR, NETWORK_REQUEST, NETWORK_RESPONSE) |
| `location` | Source class or method generating the log |
| `pubNubId` | PubNub instance identifier |
| `logLevel` | The SLF4J log level (`TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`) |
| `timestamp` | When the log was created with millisecond precision (format: `HH:mm:ss.SSS`) |

#### Custom logger example

```java
import com.pubnub.api.logging.CustomLogger;
import com.pubnub.api.logging.LogMessage;
import com.pubnub.api.logging.LogMessageContent;
import com.pubnub.api.logging.LogMessageType;

public class MonitoringLogger implements CustomLogger {

    private final MonitoringService monitoringService = new MonitoringService();
    private final AnalyticsService analyticsService =  new AnalyticsService();

    @Override
    public String getName() {
        return "MonitoringLogger";
    }

    @Override
    public void error(LogMessage logMessage) {
        // Access structured data
        String instanceId = logMessage.getPubNubId();
        String timestamp = logMessage.getTimestamp();
        String location = logMessage.getLocation();

        // Handle different message types
        if (logMessage.getMessage() instanceof LogMessageContent.Error) {
            LogMessageContent.Error errorContent = (LogMessageContent.Error) logMessage.getMessage();

            monitoringService.reportError(
                    errorContent.getMessage(),
                    errorContent.getStack(),
                    errorContent.getType(),
                    instanceId,
                    timestamp,
                    location
            );
        } else if (logMessage.getMessage() instanceof LogMessageContent.NetworkRequest) {
            LogMessageContent.NetworkRequest requestContent =
                    (LogMessageContent.NetworkRequest) logMessage.getMessage();

            if (requestContent.getCanceled() || requestContent.getFailed()) {
                monitoringService.reportNetworkFailure(
                        requestContent.getOrigin() + requestContent.getPath(),
                        requestContent.getMethod().getValue(),
                        instanceId
                );
            }
        }
    }

    @Override
    public void warn(String message) {
        // Simple string-based warning for deprecations
        if (message != null) {
            monitoringService.logWarning(message);
        }
    }

    @Override
    public void debug(LogMessage logMessage) {
        // Log configuration changes
        if (logMessage.getType() == LogMessageType.OBJECT) {
            LogMessageContent.Object content = (LogMessageContent.Object) logMessage.getMessage();
            String operation = content.getOperation();

            if (operation != null && operation.contains("Configuration")) {
                analyticsService.trackConfigChange(
                        logMessage.getPubNubId(),
                        content.getArguments()
                );
            }
        }
    }

    // Other methods use default no-op implementation
}
```

Configure the SDK with your custom logger:

```java
// Configure SDK with custom logger
PNConfiguration config = PNConfiguration.builder(new UserId("demoUserId"), "subscribeKey")
        .customLoggers(Collections.singletonList(new MonitoringLogger()))
        .build();

PubNub pubnub = PubNub.create(config);
```

## Enable logging

Logging is automatically enabled when you create a PubNub instance. The SDK logs configuration details at the `DEBUG` level during initialization. SLF4J routes all logs to your configured backend.

```java
// import com.pubnub.api.java.v2.PNConfiguration;

PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
PubNub pubNub = PubNub.create(configBuilder.build());
```

The SDK automatically logs the complete configuration at initialization, including:

* User ID and subscribe key
* Publish key (if set)
* Secret key status (masked as "set: *****" if configured)
* Connection timeouts and retry settings
* Presence and heartbeat configuration
* Custom logger count (if configured)
* Instance identifier

:::note Secret keys are masked
Secret keys and authentication tokens are never logged in plain text. The SDK logs only "set: *****" to indicate they are configured.
:::

## Logged information

The Java 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 at the `DEBUG` level. 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
* Masked sensitive values (secret keys, authentication tokens)

### API call parameters

The SDK logs user-provided input data for each API call at the `DEBUG` level.

Logged parameters include:

* Channel names and channel groups
* Messages and metadata
* Timetoken values
* Filter expressions
* Custom query parameters
* Operation-specific 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:

#### Request logs include

* HTTP method (GET, POST, PATCH, DELETE)
* Complete URL with origin and path
* Query parameters as key-value pairs
* Request headers
* Request body content (for POST, PUT, or PATCH requests)
* Request identifier (if configured)

#### Response logs include

* HTTP status code
* Response headers
* 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.

### Errors and exceptions

The SDK logs errors and exceptions at the `ERROR` level with:

* Error type (exception class name)
* Error message
* Stack trace (up to 10 frames)
* Duration before failure (for network errors)
* Request details for failed operations

## SLF4J backend configuration

The following sections explain how to configure different SLF4J backends. Choose the backend that best fits your environment and logging requirements.

For more information about configuration parameters, refer to [Configuration](https://www.pubnub.com/docs/sdks/java/api-reference/configuration#configuration).

## Implement logging using log4j

To implement logging using `log4j` you need to add the following references to the project. Using `log4j` you can log to console or a file or both.

* [log4j-slf4j2](https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j2-impl) file which acts as a bridge between `slf4j` and `log4j`.
* [log4j-api](https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api) file, which provides the underlying logging framework.
* [log4j-core](https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core) file.

Configure the `log4j2.xml` file:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console"/>
        </Root>
        <!-- Set PubNub logging level -->
        <Logger name="com.pubnub" level="trace" additivity="false">
            <AppenderRef ref="Console"/>
            <!-- <AppenderRef ref="YourCustomAppender"/>-->
        </Logger>
    </Loggers>
</Configuration>
```

See this example:

```java
import com.pubnub.api.PubNubException;
import com.pubnub.api.UserId;
import com.pubnub.api.java.PubNub;
import com.pubnub.api.java.v2.PNConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingLog4j2App {
    // Get a Log4j2 logger instance (named after the class)
    private static final Logger logger = LoggerFactory.getLogger(LoggingLog4j2App.class);

    public static void main(String[] args) throws PubNubException {
        // Configure PubNub with logging enabled
        logger.info("Initializing PubNub with Log4j2 logging enabled");

        PNConfiguration.Builder configBuilder = PNConfiguration.builder(
                new UserId("log4j2DemoUser"),
                "demo" // Replace with your Subscribe Key from the PubNub Admin Portal
        );

        // Add publish key (only required if publishing)
        configBuilder.publishKey("demo"); // Replace with your Publish Key from the PubNub Admin Portal

        // Initialize PubNub with the configuration
        PubNub pubnub = PubNub.create(configBuilder.build());

        logger.info("PubNub client initialized with Log4j2 logging");

        // Perform some operations to generate logs
        // Get time operation
        logger.info("Executing time operation");
        pubnub.time().sync();
        logger.info("Time operation completed");

        // Publish a message
        logger.info("Publishing a message");
        pubnub.channel("log4j2-demo-channel")
                .publish("Hello from Log4j2 Example")
                .sync();
        logger.info("Message published successfully");

        logger.info("Log4j2 example complete - check the log file for details");
    }
}
```

## Implement logging using slf4j-simple

To implement logging using `slf4j-simple` you need to add the following references to the project:

* `slf4j-simple jar` file (for example, [slf4j-simple-2.0.17.jar](https://mvnrepository.com/artifact/org.slf4j/slf4j-simple/2.0.17) or the latest version) which provides the underlying logging framework.
* Along with these references you need to add the `simplelogger.properties` file in the `CLASSPATH`.

Example of `simplelogger.properties`:

```bash
# Set default logging level
org.slf4j.simpleLogger.defaultLogLevel=debug

# Configure PubNub logging
org.slf4j.simpleLogger.log.com.pubnub=debug

# Show date-time in logs
org.slf4j.simpleLogger.showDateTime=true
org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss.SSS

# Show thread name
org.slf4j.simpleLogger.showThreadName=true

# Show log name
org.slf4j.simpleLogger.showLogName=true

# Show short log name (package path will be shortened)
org.slf4j.simpleLogger.showShortLogName=false

# Configure log level for specific packages (optional examples)
#org.slf4j.simpleLogger.log.com.your.path=debug
```

#### Example usage of slf4j-simple

```java
import com.pubnub.api.PubNubException;
import com.pubnub.api.UserId;
import com.pubnub.api.java.PubNub;
import com.pubnub.api.java.v2.PNConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingSlf4jSimpleApp {
    // Get an SLF4J logger instance (named after the class)
    private static final Logger logger = LoggerFactory.getLogger(LoggingSlf4jSimpleApp.class);

    public static void main(String[] args) throws PubNubException {
        // Configure PubNub with logging enabled
        logger.info("Initializing PubNub with logging enabled");

        PNConfiguration.Builder configBuilder = PNConfiguration.builder(
                new UserId("slf4jSimpleDemoUser"),
                "demo" // Replace with your Subscribe Key from the PubNub Admin Portal
        );

        // Add publish key (only required if publishing)
        configBuilder.publishKey("demo"); // Replace with your Publish Key from the PubNub Admin Portal

        // Initialize PubNub with the configuration
        PubNub pubnub = PubNub.create(configBuilder.build());

        logger.info("PubNub client initialized with BODY level logging");

        // Perform some operations to generate logs
        // Get time operation
        logger.info("Executing time operation");
        pubnub.time().sync();
        logger.info("Time operation completed");

        // Publish a message
        logger.info("Publishing a message");
        pubnub.channel("slf4j-simple-demo-channel")
                .publish("Hello from SLF4J Simple Example")
                .sync();
        logger.info("Message published successfully");

        logger.info("SLF4J Simple example complete - check the console output for details");
    }
}
```

## Implement logging using logback

To implement logging using logback, you need to add the following references to the project:

* [logback-classic](https://mvnrepository.com/artifact/ch.qos.logback/logback-classic) and [logback-core](https://mvnrepository.com/artifact/ch.qos.logback/logback-core) jar files which provide the underlying logging framework.

See this example:

```java
import com.pubnub.api.PubNubException;
import com.pubnub.api.UserId;
import com.pubnub.api.java.PubNub;
import com.pubnub.api.java.v2.PNConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingLogbackApp {
    // Get an SLF4j logger instance (named after the class)
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggingLogbackApp.class);

    public static void main(String[] args) throws PubNubException {
        LOGGER.info("Starting PubNub logging example...");

        // Configure PubNub
        PNConfiguration.Builder configBuilder = PNConfiguration.builder(
                new UserId("loggingDemoUser"),
                "demo" // Replace with your Subscribe Key from the PubNub Admin Portal
        );

        // Add publish key (only required if publishing)
        configBuilder.publishKey("demo"); // Replace with your Publish Key from the PubNub Admin Portal

        // Other optional configurations
        configBuilder.secure(true);

        // Initialize PubNub with the configuration
        PubNub pubnub = PubNub.create(configBuilder.build());

        LOGGER.info("PubNub client initialized");

        // Perform some operations to generate logs
        // Get time operation will generate logs
        LOGGER.info("Executing time operation...");
        pubnub.time().sync();
        LOGGER.info("Time operation executed - check logs for details");

        LOGGER.info("Publishing message...");
        pubnub.channel("logging-demo-channel")
                .publish("Hello from Logging Example")
                .sync();
        LOGGER.info("Message published - check logs for details");

        LOGGER.info("Logging example complete - detailed logs should be visible according to your logging configuration");
    }
}
```

Example of the `logback.xml` file:

```xml
<configuration>
    <!-- Console appender -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!-- Format: timestamp [thread] level logger - message -->
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- Set the default logging level for all loggers -->
    <root level="INFO">
        <appender-ref ref="CONSOLE" />
    </root>

    <!-- Configure PubNub calls logging -->
    <logger name="com.pubnub" level="TRACE" additivity="false">
        <appender-ref ref="CONSOLE"/>
    </logger>

</configuration>
```

## Implement logging using java.util.logging

To implement logging using `java.util.logging` you need to add the following reference to the project:

* `slf4j-jdk14 jar` file which acts as a bridge between `slf4j` and `java`.

JVM runtime provides the underlying logging framework.

## Implement logging using commons-logging

To implement logging using `commons-logging` you need to add the following reference to the project:

* `slf4j-jcl jar` file (for example, [slf4j-jcl-1.7.36.jar](https://mvnrepository.com/artifact/org.slf4j/slf4j-jcl/1.7.36) or the latest version) which acts as a bridge between `slf4j` and [common-logging](https://mvnrepository.com/artifact/commons-logging/commons-logging/1.3.5)
* `common-logging.jar` file which acts as an abstraction layer.

The underlying logging framework is chosen dynamically by `commons-logging`.

## No logging

To implement no logging, add a reference to `slf4j-nop jar` file (for example, [slf4j-nop-1.7.5.jar](https://mvnrepository.com/artifact/org.slf4j/slf4j-nop/1.7.5) or the latest version).

## Logging best practices

Use these recommendations for effective logging.

### Choose the right log level for your backend

| Environment | Recommended SLF4J Level |
| --- | --- |
| Production | `WARN` or `ERROR` to capture issues without performance impact. |
| Staging | `INFO` to monitor operational events. |
| Development | `DEBUG` when actively developing or investigating issues. |
| Deep troubleshooting | `TRACE` only when working with PubNub support on complex issues. |

Configure your SLF4J backend (log4j, logback, etc.) to set the appropriate level for the `com.pubnub` logger:

```xml
<!-- Example logback.xml configuration -->
<logger name="com.pubnub" level="INFO" additivity="false">
    <appender-ref ref="CONSOLE"/>
</logger>
```

### Protect sensitive data

Never enable `DEBUG` or `TRACE` logging in production environments that handle sensitive information.

These levels may expose:

* API keys (publish and subscribe keys are visible in requests)
* User identifiers
* Message content
* Authentication tokens (masked as "set: *****" in configuration, but visible in network requests)

### Use custom loggers for monitoring

Implement `CustomLogger` to route critical errors and metrics to external monitoring services without affecting SLF4J logging:

```java
configBuilder.customLoggers(List.of(
    new MonitoringLogger(),  // Send errors to monitoring service
    new MetricsLogger()      // Track usage patterns
));
```

Custom loggers receive structured `LogMessage` objects that are easier to parse than string-based logs.

### 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.

Network request and response logging at `DEBUG` level can be particularly verbose for applications with many API calls.

### Optimize performance in production

Set your SLF4J backend to `WARN` or `ERROR` level for the `com.pubnub` logger. This optimizes performance and reduces storage costs:

```xml
<!-- Production logback.xml configuration -->
<logger name="com.pubnub" level="WARN" additivity="false">
    <appender-ref ref="CONSOLE"/>
</logger>
```

### Provide complete logs to support

When reporting issues to [PubNub support](https://support.pubnub.com/), provide complete logs:

1. Set your SLF4J backend to `DEBUG` or `TRACE` level for `com.pubnub`
2. Reproduce the issue
3. Collect logs from SDK initialization through the problem occurrence
4. Include the PubNub SDK version and Java version

The configuration is automatically logged at initialization, which helps support diagnose issues faster.