Advanced Usage
By default all ThreadContext
parameters are stored under the “Context Data” tab in sentry.io.
Copied
import org.apache.logging.log4j.ThreadContext;
void logWithExtras() {
// ThreadContext ("MDC") extras
ThreadContext.put("Environment", "Development");
ThreadContext.put("OS", "Linux");
// This sends an event where the Environment and OS ThreadContext values are set as Context Data entries
logger.error("This is a test");
}
Note that ThreadContext
manages data on a per-thread basis, and that a child thread does not automatically inherit ThreadContext
properties from its parent.
In Practice
Copied
import io.sentry.core.Sentry;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
public class MyClass {
private static final Logger logger = LogManager.getLogger(MyClass.class);
void logSimpleMessage() {
// This sends a simple event to Sentry
logger.error("This is a test");
}
void logWithBreadcrumbs() {
// Record a breadcrumb that will be sent with the next event(s),
// by default the last 100 breadcrumbs are kept.
Sentry.addBreadcrumb("User made an action");
// Log entries below `minimumEventLevel` and above or equal to `minimumBreadcrumbLevel`
// are recorded as breadcrumbs
logger.info("User made another action");
// This sends a simple event to Sentry
logger.error("This is a test");
}
void logWithExtras() {
// MDC extras
ThreadContext.put("extra_key", "extra_value");
// NDC extras are sent under 'log4j2-NDC'
ThreadContext.push("Extra_details");
// This sends an event with extra data to Sentry
logger.error("This is a test");
}
void logException() {
try {
unsafeMethod();
} catch (Exception e) {
// This sends an exception event to Sentry
logger.error("Exception caught", e);
}
}
void unsafeMethod() {
throw new UnsupportedOperationException("You shouldn't call this!");
}
}
Context Tags
Since Sentry 6.0.0, it is possible to define a list of MDC tags
that will show up as Tags
in the Sentry UI. MDC Tags
not in this list are shown as Context Data
in the UI, just like before.
To define such tags add a context-tags
attribute to the <Sentry>
tag in your log4j2.xml
with the tags as comma seperated items.
Copied
<Sentry name="Sentry"
dsn="https://examplePublicKey@o0.ingest.sentry.io/0"
contextTags="userId,requestId"
/>
When calling ThreadContext.push("userId", "myUserId")
with above Appender configuration in place, the userId
will show up as a Tag
on the event in the Sentry UI.
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) to suggesting an update ("yeah, this would be better").
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) to suggesting an update ("yeah, this would be better").
- Package:
- maven:io.sentry:sentry-log4j2
- Version:
- 6.17.0
- Repository:
- https://github.com/getsentry/sentry-java