---
title: Java agent logs in context
source: https://docs.newrelic.com/docs/logs/logs-context/java-configure-logs-context-all
---

With our Java APM agent, you can get **logs in context**, which lets you see your app logs in the context of your other New Relic data. For general information on this feature, see [APM logs in context](https://docs.newrelic.com/docs/apm/new-relic-apm/getting-started/get-started-logs-context).

> #### 💡 TIP
>
> Got lots of Java logs? Check out our [tutorial on how to optimize and manage them](https://docs.newrelic.com/docs/tutorial-large-logs/get-started-managing-large-logs/).

## Automatic logs in context options [#automatic]

If you are using a supported framework, you have two options to configure APM logs in context to send your app's logs and linking metadata automatically to New Relic. One option is to manually configure a log extension that will decorate your logs and then you can forward them to yourself. The other option is to have the Java agent automatically handle decorating and forwarding of your logs. Supported frameworks for automatic logs in context include:

-   Log4j1 1.2.17 or higher
-   Log4j2 2.6 or higher
-   Logback 1.1 or higher
-   JUL (java.util.logging) JDK 8+
-   JBoss Logging 1.3.0.Final to 2.x
-   Dropwizard Logging (captured via Logback instrumentation, see know issue below)

> #### ⚠️ IMPORTANT
>
> JBoss Logging
>
> JBoss Logging delegates the local decorating functionality to the JUL instrumentation and thus can be completely comtrolled by the following two instrumentation modules:
>
> ```yml
> class_transformer:
>   com.newrelic.instrumentation.java.logging-jdk8:
>     enabled: true
>
>   com.newrelic.instrumentation.jboss.logging:
>     enabled: true
> ```

> #### ⚠️ IMPORTANT
>
> Known Issue With Dropwizard Logging
>
> By default, Dropwizard uses Logback for its logging backend. It also routes all java.util.logging, Log4j, and Apache Commons Logging usage through Logback. This routing behavior can lead to duplicate logs being reported to New Relic if the Java agent instruments one of these other logging libraries in addition to instrumenting Logback.
>
> To avoid reporting duplicate logs when using Dropwizard logging, it is recommended that you disable all of the logging framework instrumentation except for Logback. You can do this in the `class_transformer` section in the agent configuration file:
>
> ```yml
> class_transformer:
>   com.newrelic.instrumentation.logback-classic-1.2:
>     enabled: true
>
>   com.newrelic.instrumentation.apache-log4j-1:
>     enabled: false
>
>   com.newrelic.instrumentation.apache-log4j-2:
>    enabled: false
>
>   com.newrelic.instrumentation.java.logging-jdk8:
>    enabled: false
>
>   com.newrelic.instrumentation.jboss.logging:
>    enabled: false
> ```

> #### ⚠️ IMPORTANT
>
> Agent releases 7.7.0 and higher have this feature enabled in the agent configuration file by default.
>
> Agent log forwarding will cause an increase in the consumption of data when a [supported framework](https://docs.newrelic.com/docs/logs/logs-context/java-configure-logs-context-all#automatic) is detected. The amount depends on the application and amount of logs it produces. This feature can be disabled. See [Disable automatic logging](https://docs.newrelic.com/docs/logs/logs-context/disable-automatic-logging/) for more information about your options.
>
> If you already have a log forwarding solution in place, you should disable this feature.

If you prefer to use your own log forwarder, rather than having the Java agent forward logs, then our [manual logs in context](#enable-logs-java) solution would be the right solution for decorating your logs with trace context metadata.

**Option 1 (recommended): Let the agent forward your logs.**

This is the simplest approach, and it's a great choice for developers who may not have the access or interest in setting up a log forwarder, or for accounts that want to see the power of logs and other linking metadata in context of their apps, without a lot of overhead.

Using this option, the agent adds `span.id`, `trace.id`, `hostname`, `entity.guid`, and `entity.name`. [Learn about log forwarding limitations.](https://docs.newrelic.com/docs/logs/logs-context/get-started-logs-context#forwarding-details)

This functionality is enabled by default.

All you need to do is install an agent version with log forwarding capabilities ([Java agent 7.6.0 or higher](https://docs.newrelic.com/docs/release-notes/agent-release-notes/java-release-notes/)). If forwarding is disabled, you can use this configuration:

Configuration file (`newrelic.yml`), indented 2 spaces under the common section:

````yml
application_logging:
  enabled: true
  forwarding:
    enabled: true
    max_samples_stored: 10000
  local_decorating:
    enabled: false
```

Environment variable:

```ini
NEW_RELIC_APPLICATION_LOGGING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_MAX_SAMPLES_STORED=10000
NEW_RELIC_APPLICATION_LOGGING_LOCAL_DECORATING_ENABLED=false
```

System property:

```ini
-Dnewrelic.config.application_logging.enabled=true
-Dnewrelic.config.application_logging.forwarding.enabled=true
-Dnewrelic.config.application_logging.forwarding.max_samples_stored=10000
-Dnewrelic.config.application_logging.local_decorating.enabled=false
```

<DNT>
  **Optional adjustments (`max_samples_stored`):**
</DNT>

Once this feature is enabled, you also have control over the maximum number of log lines sent to New Relic every minute. The default value is 10,000. If more than 10,000 log lines are seen by the agent in a 60-second window, your logs will begin to be sampled.

Set it to a higher number to receive more logs. Set it to a lower number to receive fewer logs. Any non-negative integer is valid.

<Callout variant="tip">
  This refers to the number of logs sent _per minute_. Setting `max_samples_stored` to a value less than 12 will have the effect of causing no logs to be sent.
</Callout>

Configuration file (`newrelic.yml`):

```yml
application_logging:
  enabled: true
  forwarding:
    enabled: true
    max_samples_stored: 10000
  local_decorating:
    enabled: false
```

Environment variable:

```ini
NEW_RELIC_APPLICATION_LOGGING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_MAX_SAMPLES_STORED=10000
NEW_RELIC_APPLICATION_LOGGING_LOCAL_DECORATING_ENABLED=false
```

System property:

```ini
-Dnewrelic.config.application_logging.enabled=true
-Dnewrelic.config.application_logging.forwarding.enabled=true
-Dnewrelic.config.application_logging.forwarding.max_samples_stored=10000
-Dnewrelic.config.application_logging.local_decorating.enabled=false
```

<Callout variant="important">
  If you have an existing log forwarding solution and are updating your agent to use automatic logs in context, be sure to <DNT>**disable your manual log forwarder**</DNT>. Otherwise, your app will be sending double log lines. Depending on your account, this could result in double billing. For more information, follow the procedures to disable your [specific log forwarder](/docs/logs/forward-logs/enable-log-management-new-relic#log-forwarding).
</Callout>

````

**Option 2: Use your own log forwarder.**

Already have a log forwarder you like? We've got you covered! The Java agent can decorate your logs with the linking metadata needed to provide access to automatic logs-in-context features, and you can send them to New Relic using your manual log forwarder.

> #### 💡 TIP
>
> This option replaces our [manual logs in context](#enable-logs-java) decorator.

> #### ⚠️ IMPORTANT
>
> This option should not be used with in-agent forwarding. Using an [external log forwarder](https://docs.newrelic.com/docs/logs/forward-logs/enable-log-management-new-relic#log-forwarding) to send logs to New Relic while in-agent forwarding is enabled will cause your logs to be sent up twice to New Relic. Depending on your account, this may result in double billing.

Update your agent's configuration to disable log forwarding and enable local decoration, then restart the agent to start decorating your logs.

Configuration file (`newrelic.yml`), indented 2 spaces under the common section:

````yml
application_logging:
  enabled: true
  local_decorating:
    enabled: true
  forwarding:
    enabled: false
```

Environment variable:

```ini
NEW_RELIC_APPLICATION_LOGGING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_LOCAL_DECORATING_ENABLED=true
NEW_RELIC_APPLICATION_LOGGING_FORWARDING_ENABLED=false
```

System property:

```ini
-Dnewrelic.config.application_logging.enabled=true
-Dnewrelic.config.application_logging.local_decorating.enabled=true
-Dnewrelic.config.application_logging.forwarding.enabled=false
```

Our decorator adds five attributes to every log message in your application log file: `entity.guid`, `hostname`, `trace.id`, `span.id` and `entity.name`. Example:

```
This is my log message. NR-LINKING|{entity.guid}|{hostname}|{trace.id}|{span.id}|{entity.name}|
```

If the log message is empty or blank, output message will also be empty. Example:

```
NR-LINKING|{entity.guid}|{hostname}|{trace.id}|{span.id}|{entity.name}|.
```
The output log message will be an empty string.

Some attributes may be empty if the log occurred outside a transaction or if they are not applicable to your application's context.

````

## Secure your data [#obfuscation]

Your logs may include sensitive information protected by HIPAA or other compliance protocols. By default we obfuscate number patterns that appear to be for items such as credit cards or Social Security numbers, but you may need to hash or mask additional information.

For more information, see our documentation about [obfuscation expressions and rules](https://docs.newrelic.com/docs/logs/ui-data/obfuscation-ui/). You can hash or mask your log data by using the New Relic UI or by using NerdGraph, our GraphQL API.

## Explore your data [#view-ui]

To make the most of your logging data:

-   On the [APM **Summary** page](https://docs.newrelic.com/docs/apm/apm-ui-pages/monitoring/apm-summary-page-view-transaction-apdex-usage-data), click your **Web transaction time** chart to view logs associated with a specific point in time.
-   Check your app's [**Errors inbox**](https://docs.newrelic.com/docs/errors-inbox/errors-inbox) to view the logs associated with your errors.
-   Use [distributed tracing](https://docs.newrelic.com/docs/distributed-tracing/ui-data/understand-use-distributed-tracing-ui) to see the logs associated with individual traces.
-   Explore more logging data across your platform with our [logs UI](https://docs.newrelic.com/docs/logs/log-management/ui-data/use-logs-ui/).
-   Set up [alerts](https://docs.newrelic.com/docs/alerts-applied-intelligence/new-relic-alerts/alert-conditions/create-alert-conditions/) based on log output and severity.
-   [Query your data](https://docs.newrelic.com/docs/logs/ui-data/query-syntax-logs/) using our specialized UI for logs data, and [create dashboards](https://docs.newrelic.com/docs/query-your-data/explore-query-data/dashboards/introduction-dashboards/) with the results.

## Troubleshooting tips [#troubleshooting]

Typically your logs will start to appear less than a minute after you enable APM logs in context. Check your app's **Triage > Logs** section. You will also start seeing [log patterns](https://docs.newrelic.com/docs/logs/ui-data/find-unusual-logs-log-patterns) related to the error there.

If you don't see any logs for errors or traces, there may not be any for your app. Try refreshing the UI page, or change the [selected time period](https://docs.newrelic.com/docs/new-relic-one/ui-data/basic-ui-features/#data-analysis).

## Disable automatic logging [#disable-automatic]

APM logs in context automatically forwards APM agent log data and is enabled by default. This can have a negative impact on your security, compliance, billing, or system performance. To disable automatic logs:

1.  From the [user menu](https://docs.newrelic.com/docs/accounts/accounts-billing/general-account-settings/intro-account-settings) in the New Relic UI, click **Manage your data > Log settings**.
2.  Click the ellipsis **...** menu at the right side of the account's row.
3.  Click the confirmation button to enable or disable and lock or unlock automatic logging (parent accounts) or enable or disable only (child accounts).

For more information, or if you need to adjust the default setting, follow the procedures to [disable automatic logging](https://docs.newrelic.com/docs/logs/logs-context/disable-automatic-logging).

## Manual logs in context option [#enable-logs-java]

Before language agents had the ability to forward and decorate logs, you could use our manual solutions to send linking metadata.

This option is still supported, but is no longer encouraged. Also, this method requires that you install a log forwarder before enabling logs in context. If you do not have a log forwarder, the New Relic UI will prompt you to use our [infrastructure agent](https://docs.newrelic.com/docs/logs/forward-logs/forward-your-logs-using-infrastructure-agent/).

If you decide to use your existing log forwarding solution and later decide to update your agent to use automatic logs in context, be sure to **disable your manual log forwarder**. Otherwise, your app will be sending double log lines. Depending on your account, this could result in double billing. For more information, follow the procedures to disable your [specific log forwarder](https://docs.newrelic.com/docs/logs/forward-logs/enable-log-management-new-relic#log-forwarding).

If you need to use the manual process to set up logs in context for Java, follow these steps:

1.  Make sure you have already [set up logging in New Relic](https://docs.newrelic.com/docs/logs/enable-log-management-new-relic/enable-log-monitoring-new-relic/enable-log-management-new-relic/). This includes configuring a supported log forwarder that collects your application logs and extends the metadata that is forwarded to New Relic.
2.  [Install](https://docs.newrelic.com/docs/agents/java-agent/installation/install-java-agent/) or [update](https://docs.newrelic.com/docs/agents/java-agent/installation/update-java-agent/) to the latest Java agent version. Use [Java agent version 5.6.0 or higher](https://docs.newrelic.com/docs/release-notes/agent-release-notes/java-release-notes/) for logs in context.
3.  Enable the [JVM argument `-javaagent`](https://docs.newrelic.com/docs/agents/java-agent/installation/include-java-agent-jvm-argument), and [enable distributed tracing](https://docs.newrelic.com/docs/distributed-tracing/enable-configure/quick-start/).
4.  Configure logs in context for Java to enrich your log data, using any of the following extensions as applicable. If you use Spring or Spring Boot and aren't sure which extension you need, see our [Spring](#spring) documentation.

**Dropwizard 1.3 or higher**

We offer a [Dropwizard](https://dropwizard.readthedocs.io/en/release-1.3.x/manual/core.html#logging) extension for logs in context with the Java agent. To get started, review the [code](https://github.com/newrelic/java-log-extensions/tree/main/dropwizard) and an [example application](https://github.com/newrelic/java-log-extensions/tree/main/examples/dropwizard-app) on GitHub.

To configure logs in context for your Java app with the DropWizard extension:

1.  Make sure you have the [Dropwizard 1.3 or higher](https://dropwizard.readthedocs.io/en/release-1.3.x/manual/core.html#logging) package installed and working on your application. Use the original Dropwizard appenders and logging factory installed and working on the application.

2.  Make sure you have the New Relic Java agent version 5.6.0 or higher installed on your application, and that you have enabled the [JVM argument `-javaagent`](https://docs.newrelic.com/docs/agents/java-agent/installation/include-java-agent-jvm-argument).

3.  Update your project's dependencies to include the Dropwizard 1.3 extension as applicable:

    **Gradle:** Add the following to your `build.gradle` file:

    ```groovy
    dependencies {
      implementation("com.newrelic.logging:dropwizard:2.0")
    }
    ```

    **Maven:** Add the following to your `pom.xml` file:

    ```xml
    <dependencies>
      <dependency>
        <groupId>com.newrelic.logging</groupId>
        <artifactId>dropwizard</artifactId>
        <version>2.0</version>
      </dependency>
    </dependencies>
    ```

4.  Update your Dropwizard `.yaml` configuration file with a `newrelic-json` layout, replacing the currently used `type: console` or `type: file` with either `type: newrelic-console` or `type: newrelic-file` as appropriate. For example:

    ```yml
    logging:
      appenders:
        - type: newrelic-console
          # Add the two lines below if you don't have a layout specified on the appender.
          # If you have a layout, remove all parameters to the layout and set the type.
          layout:
            type: newrelic-json
    ```

    The New Relic Dropwizard extension also supports a `log-format` layout type that uses the standard Dropwizard logging. For testing purposes, you can change the type of the layout with a one-line change:

    ```yml
    logging:
      appenders:
        - type: newrelic-file
          # This format will be ignored by the newrelic-json layout, but used by the log-format layout.
          logFormat: "%date{ISO8601} %c %-5p: %m trace.id=%mdc{trace.id} span.id=%mdc{span.id}%n"
          layout:
            # type: newrelic-json
            type: log-format
    ```

**java.util.logging**

We offer a [java.util.logging](https://docs.oracle.com/javase/7/docs/api/java/util/logging/package-summary.html) extension for logs in context with the Java agent. To get started, review the [code](https://github.com/newrelic/java-log-extensions/tree/main/jul) and an [example application](https://github.com/newrelic/java-log-extensions/tree/main/examples/jul-app) on GitHub.

To configure logs in context for your Java app with with the `java.util.logging` extension:

1.  Make sure you have the [`java.util.logging`](https://docs.oracle.com/javase/7/docs/api/java/util/logging/package-summary.html) package installed and working on the application.

2.  Make sure you have the New Relic Java agent version 5.6.0 or higher installed on your application, and that you have enabled the [JVM argument `-javaagent`](https://docs.newrelic.com/docs/agents/java-agent/installation/include-java-agent-jvm-argument).

3.  Update your project's dependencies to include the `java.util.logging` extension as applicable. If you can't edit these files, you can instead [add the jars directly to the application `classpath`](#java-adding-classpath).

    **Gradle:** Add the following to your `build.gradle` file:

    ```groovy
    dependencies {
      implementation("com.newrelic.logging:jul:2.0")
    }
    ```

    **Maven:** Add the following to your `pom.xml` file:

    ```xml
    <dependencies>
      <dependency>
        <groupId>com.newrelic.logging</groupId>
        <artifactId>jul</artifactId>
        <version>2.0</version>
      </dependency>
    </dependencies>
    ```

4.  Check if your logging file's `handlers` property is set to something other than `NewRelicMemoryHandler`. Look for a line listing the root logger's handlers, like this:

    ```ini
    handlers = java.util.logging.FileHandler
    ```

5.  Update your logging properties file to set the root logger's handler to `NewRelicMemoryHandler` so it intercepts messages destined for another handler:

    ```ini
    handlers = com.newrelic.logging.jul.NewRelicMemoryHandler
    ```

6.  Configure the `NewRelicMemoryHandler` by setting the target to the handler that was previously assigned to the root logger, so it captures data New Relic needs on the thread the log message is coming from:

    ```ini
    com.newrelic.logging.jul.NewRelicMemoryHandler.target = java.util.logging.FileHandler
    ```

7.  Use a `NewRelicFormatter` for the final handler. Update your logging properties file to set the `formatter` property like the following example. Make sure the handler where you set the formatter is the `target` handler from the previous step (`java.util.logging.FileHandler` in this example).

    ```ini
    java.util.logging.FileHandler.formatter = com.newrelic.logging.jul. NewRelicFormatter
    ```

    The New Relic log format is JSON with telemetry metadata we use to correlate transactions and logs together. Currently we do not support any customization of that format.

    Once complete, JSON is logged instead of text. The JSON should be formatted as single objects, one per line, and should contain fields like `log.level` and `thread.name`. The `trace.id`, which is required for logs in context, should only have a value for log messages that occur within a transaction.

**java.util.logging classpath additions**

The most direct way to get the logs-in-context extensions is to add these dependencies to Maven's `pom.xml` or Gradle's `build.gradle`. This allows the packaging tools to pick up the correct dependencies.

If you can't edit these files, you can instead add the jars directly to the application `classpath` for your logging framework's configuration.

Before you modify the classpath:

1.  Enable the [JVM argument `-javaagent`](https://docs.newrelic.com/docs/agents/java-agent/installation/include-java-agent-jvm-argument/) on your app's Java agent.
2.  Verify which logging framework the application is using.
3.  Make sure you are able to change your logging framework's configuration.
4.  Add the following three jars to the classpath if they aren't already present. Generally, we recommend taking the latest versions published on Maven Central.

-   Group ID `com.newrelic.logging` and Artifact ID: Select the artifact named after [your application's logging framework in Maven](https://search.maven.org/search?q=g:com.newrelic.logging).
-   Group ID `com.fasterxml.jackson.core` and Artifact ID: Use [`jackson-core`](https://search.maven.org/search?q=g:com.fasterxml.jackson.core%20a:jackson-core).
-   Group ID `com.newrelic.agent.java` and Artifact ID: Use [`newrelic-api`](https://search.maven.org/search?q=g:com.newrelic.agent.java%20a:newrelic-api).

**Log4j 1.x**

> #### 💡 TIP
>
> Take advantage of our [automatic logs in context](#automatic) solution for Java. No need to use this manual process!

We offer a [Log4j 1.x](https://logging.apache.org/log4j/1.2/) extension for manual logs in context with the Java agent. To get started, review the [code](https://github.com/newrelic/java-log-extensions/tree/main/log4j1) and an [example application](https://github.com/newrelic/java-log-extensions/tree/main/examples/log4j1-app) on GitHub.

To configure manual logs in context for your Java app with with the Log4j 1.x extension, you must configure the Log4j extension in code or via XML. Properties files are not supported because `AsyncAppender` instances can only be automatically configured via XML.

1.  Make sure you have the [Log4j 1.x](https://logging.apache.org/log4j/1.2/) package installed and working on the application.

2.  Make sure you have the New Relic Java agent version 5.6.0 or higher installed on your application, and that you have enabled the [JVM argument `-javaagent`](https://docs.newrelic.com/docs/agents/java-agent/installation/include-java-agent-jvm-argument).

3.  Update your project's dependencies to include the Log4j 1.x extension as applicable.

    **Gradle:** Add the following to your `build.gradle` file:

    ```groovy
    dependencies {
      implementation("com.newrelic.logging:log4j1:2.0")
    }
    ```

    **Maven:** Add the following to your `pom.xml` file:

    ```xml
    <dependencies>
      <dependency>
        <groupId>com.newrelic.logging</groupId>
        <artifactId>log4j1</artifactId>
        <version>2.0</version>
      </dependency>
    </dependencies>
    ```

4.  In your logging configuration XML file, update your `<appender>` element with a `NewRelicLayout`, adding `<layout class="com.newrelic.logging.log4j1.NewRelicLayout"/>`:

    ```xml
    <appender name="TypicalFile" class="org.apache.log4j.FileAppender">
      <param name="file" value="logs/log4j1-app.log"/>
      <param name="append" value="false"/>
      <layout class="com.newrelic.logging.log4j1.NewRelicLayout"/> <!-- only this line needs to be added -->
    </appender>
    ```

5.  Use `NewRelicAsyncAppender` to wrap any appenders that will target New Relic's log forwarder. For example:

    ```xml
    <appender name="NewRelicFile"
              class="com.newrelic.logging.log4j1.NewRelicAsyncAppender">
      <appender-ref ref="TypicalFile" />
    </appender>
    ```

6.  Use the async appender on the root logger. For example:

    ```xml
    <root>
      <appender-ref ref="NewRelicFile" />
    </root>
    ```

    **Example configuration file for the Log4j 1.x extension:**

    ```xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    <log4j:configuration debug="false">
      <appender name="TypicalFile" class="org.apache.log4j.FileAppender">
        <param name="file" value="logs/log4j1-app.log"/>
        <param name="append" value="false"/>
        <!-- layout has been replaced -->
        <layout class="com.newrelic.logging.log4j1.NewRelicLayout"/>
      </appender>

        <!-- this appender was added -->
      <appender name="NewRelicFile"
                class="com.newrelic.logging.log4j1.NewRelicAsyncAppender">
        <appender-ref ref="TypicalFile" />
      </appender>

      <appender name="TypicalConsole" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
      </appender>

      <root>        ​
        <!-- the new appender was used here -->​​
        <appender-ref ref="NewRelicFile" />
        <appender-ref ref="TypicalConsole" />
      </root>

    </log4j:configuration>
    ```

**Log4j 2.x**

> #### 💡 TIP
>
> Take advantage of our [automatic logs in context](#automatic) solution for Java. No need to use this manual process!

We offer a [Log4j 2.x](https://logging.apache.org/log4j/2.x/log4j-slf4j-impl.html) extension for logs in context with the Java agent. To get started, review the [code](https://github.com/newrelic/java-log-extensions/tree/main/log4j2) and an [example application](https://github.com/newrelic/java-log-extensions/tree/main/examples/log4j2-app) on GitHub.

To configure logs in context for your Java app with with the Log4j 2.x extension:

1.  Make sure you have the [Log4j 2.13.2 or higher](https://logging.apache.org/log4j/2.x/index.html) or [Logs4j 2 binding](https://logging.apache.org/log4j/2.x/log4j-slf4j-impl/) package installed and working on your application.

2.  Make sure you have the New Relic Java agent version 5.6.0 or higher installed on your application, and that you have enabled the [JVM argument `-javaagent`](https://docs.newrelic.com/docs/agents/java-agent/installation/include-java-agent-jvm-argument).

3.  Update your project's dependencies to include the Log4j 2.x extension as applicable:

    **Gradle:** Add the highlighted section to your `build.gradle` file:

    ```groovy
    dependencies {
      implementation("com.newrelic.logging:log4j2:2.0")
    }
    ```

    **Maven:** Add the highlighted section to your `pom.xml` file:

    ```xml
    <dependencies>
      <dependency>
        <groupId>com.newrelic.logging</groupId>
        <artifactId>log4j2</artifactId>
        <version>2.0</version>
      </dependency>
    </dependencies>
    ```

4.  In your logging configuration XML file, update your `<configuration>` element by adding the highlighted section:

    ```xml
    <Configuration xmlns="http://logging.apache.org/log4j/2.0/config"
          packages="com.newrelic.logging.log4j2"
    >
    ```

    If you're using a properties file, add `packages=com.newrelic.logging.log4j2`.

5.  Add `<NewRelicLayout/>` to use a `NewRelicLayout` element within one of the appenders. For example:

    ```xml
    <File name="MyFile" fileName="logs/app-log-file.log">
      <NewRelicLayout/>
    </File>
    ```

    If you're using a properties file, only change the `layout.type`:

    ```ini
    appender.console.type = Console
    appender.console.name = STDOUT
    appender.console.layout.type = NewRelicLayout
    ```

6.  If you only modified an existing appender, skip this step. If you added a new appender, add `<AppenderRef/>` within `<Root>` to use this appender. Use the `ref` attribute to refer to appender `name` you created in the previous step. For example:

    ```xml
    <Root level="info">
      <AppenderRef ref="MyFile"/>
    </Root>
    ```

    If you're using a properties file and added a new appender, add:

    ```ini
    rootLogger.level = info
    rootLogger.appenderRef.stdout.ref = STDOUT
    ```

**Logback version 1.2.0 or higher**

> #### 💡 TIP
>
> Take advantage of our [automatic logs in context](#automatic) solution for Java. No need to use this manual process!

We offer a [Logback](https://logback.qos.ch/documentation.html) extension for logs in context with the Java agent. To get started, review the [code](https://github.com/newrelic/java-log-extensions/tree/main/logback) and an [example application](https://github.com/newrelic/java-log-extensions/tree/main/examples/logback-app) on GitHub.

To configure logs in context for your Java app with Logback:

1.  Make sure you have [Logback version 1.2.0 or higher](https://logback.qos.ch/documentation.html) and the New Relic Java agent version 5.6.0 or higher installed and working on your application.

2.  Make sure you have the New Relic Java agent version 5.6.0 or higher installed on your application, and that you have enabled the [JVM argument `-javaagent`](https://docs.newrelic.com/docs/agents/java-agent/installation/include-java-agent-jvm-argument).

3.  Update your project's dependencies to include the Logback extension as applicable:

    **Gradle:** Add the highlighted section to your `build.gradle` file:

    ```groovy
    dependencies {
      implementation("com.newrelic.logging:logback:2.0")
    }
    ```

    **Maven:** Add the highlighted section to your `pom.xml` file:

    ```xml
    <dependencies>
      <dependency>
        <groupId>com.newrelic.logging</groupId>
        <artifactId>logback</artifactId>
        <version>2.0</version>
      </dependency>
    </dependencies>
    ```

4.  Update your logging configuration `xml` to replace any existing `<encoder>` element.

    If you're logging to the console (`stdout/stderr`), look for `ConsoleAppender` and replace:

    ```sml
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
      <encoder class="com.newrelic.logging.logback.NewRelicEncoder"/>
    </appender>
    ```

    If you're logging to a file, look for `FileAppender` and replace `<encoder>`:

    ```xml
    <appender name="LOG_FILE" class="ch.qos.logback.core.FileAppender">
      <file>logs/app-log-file.log</file>
      <encoder class="com.newrelic.logging.logback.NewRelicEncoder"/>
    </appender>
    ```

5.  Update your logging configuration `xml` with the `NewRelicAsyncAppender`. To ensure that `NewRelicAsyncAppender` wraps any appenders that will target New Relic's log forwarder, add the following section. Change `"LOG_FILE"` to the name of the appender you updated in the previous step.

    ```xml
    <appender name="ASYNC" class="com.newrelic.logging.logback.NewRelicAsyncAppender">
      <appender-ref ref="LOG_FILE" />
    </appender>
    ```

6.  Make sure `NewRelicAsyncAppender` is the first appender used in your logger. Replace your root logger’s appenders with the `ASYNC` appender created in the previous step. Then list any other appenders after the `NewRelicAsyncAppender` in the `<root>` list.

    ```xml
    <root>
      <appender-ref ref="ASYNC" />
    </root>
    ```

    Here are examples of an updated logging `.xml` file for the Logback extension. You can also see a [working example in GitHub](https://github.com/newrelic/java-log-extensions/blob/master/examples/logback-app/src/main/resources/logback.xml).

    **Single console appender example**

    Example configuration file after adding in the logging extension information:

    ```xml
    <configuration>
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">

        <!-- changed the encoder -->
        <encoder class="com.newrelic.logging.logback.NewRelicEncoder"/>

      </appender>

      <!-- added the ASYNC appender -->
      <appender name="ASYNC" class="com.newrelic.logging.logback.NewRelicAsyncAppender">
        <appender-ref ref="STDOUT" />
      </appender>

      <root level="debug">

        <!-- changed the root logger -->
        <appender-ref ref="ASYNC" />

      </root>
    </configuration>
    ```

    **Two console appenders example**

    This example sends New Relic logging to a file, but still sends standard logging to the console:

    ```xml
    <configuration>
      <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>myApp.log</file>
        <!-- encoder changed -->
        <encoder class="com.newrelic.logging.logback.NewRelicEncoder"/>
      </appender>

      <!-- this appender does normal console logging -->
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
          <pattern>%msg%n</pattern>
        </encoder>
      </appender>

      <!-- The required New Relic ASYNC appender wraps the FILE appender -->
      <appender name="ASYNC" class="com.newrelic.logging.logback.NewRelicAsyncAppender">
        <appender-ref ref="FILE" />
      </appender>

      <root level="debug">
        <!-- ASYNC is one of the main appenders -->
        <appender-ref ref="ASYNC" />

        <!-- Send every message to normal console logging, as well. -->
        <appender-ref ref="STDOUT" />
      </root>
    </configuration>
    ```

**Spring and Springboot**

We offer extensions for current versions of [Spring](https://spring.io/) and [Spring Boot](https://spring.io/projects/spring-boot). If you already know the logging library, you can skip directly to that documentation:

-   [java.util.logging](#java-util-logging)

-   [log4j 1](#java-log4j-1x)

-   [log4j 2](#java-log4j-2x)

-   [logback](#java-logback)

    The extensions support default configurations only on Spring Boot 2.0 and higher.

    **With Spring Boot:**

    Here are tips to determine which logging library you have:

-   If you have `spring-boot-starter-log4j2` in your dependencies, you're using **log4j 2.x**. Refer to the [Spring Boot log4j 2.x documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-configure-log4j-for-logging) for basic configuration, and the [New Relic log4j 2 extension](#java-log4j-2x) for customizing your configuration.

-   If you're using Spring Boot but **not** the `starter-log4j2`, you're using **logback** by default. Refer to [Spring Boot logback documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-configure-logback-for-logging) for basic configuration, and the [New Relic logback extension](#logback) for customizing your configuration.

    **With Spring (but not Spring Boot):**

    Spring 5 or higher:

    Spring implements a [bridge](https://docs.spring.io/spring/docs/current/javadoc-api/org/apache/commons/logging/LogFactory.html) to other logging libraries that will automatically find them. However, those individual libraries must be configured and explicitly included in your project dependencies.

    To identify your logging dependency, consult your [Gradle](https://docs.gradle.org/current/userguide/viewing_debugging_dependencies.html), [Maven](https://maven.apache.org/plugins/maven-dependency-plugin/examples/resolving-conflicts-using-the-dependency-tree.html), or other build tool's dependency tree. Then follow the procedures to configure logs in context for your Java app with that extension.

    Spring 4 or lower:

    Spring version 4 and lower uses [Apache Commons Logging](https://commons.apache.org/proper/commons-logging/guide.html) for its bridge. Refer to the [Spring documentation](https://docs.spring.io/spring/docs/4.3.12.RELEASE/spring-framework-reference/html/overview.html#overview-logging) for information on configuring its bridge.
