Search code examples
javasentryraven

Add http request info to sentry from another thread


We're using a log4j appender to send errors to sentry from our tomcat webapp. This works great for errors that occur in the main thread of a request -- we get all the extra http info like url, request params, cookies, headers, etc.

But some of our requests spawn other threads to do stuff using org.springframework.core.task.TaskExecutor.execute(). When we log errors in these threads, we get very little information in sentry. Is there anyway to attach the context from the parent thread to the error?


Solution

  • You're probably using the MDC facility to add this extra information. The MDC information is stored in ThreadLocal storage, which means it is only available to the thread to which the storage is tied.

    One way of making sure the extra information is available is by making sure the MDC information of the thread that spawns the tasks is made available in the executor threads by passing the context map to the child threads.

    // This is the parent (main thread)
    final Map<String, String> contextMap = MDC.getCopyOfContextMap();
    
    executorService.execute(new Task(contextMap) {
        public final void run() {
            // This is run by the child.
            MDC.setContextMap(contextMap);
    
            ...
        }
    });