I'm working on a project that uses forkjoinpool for multi-threading and log4j for logging. In our project there are multiple 'jobs' running in concurrency, and each job is only handled by one thread.
The problem with logging is within main flow of the jobs we are able to prefix the job id to logger so that corresponding log entries will have job id info. However along the processing of each job there are a lot of utility APIs called and logging entries coming from within such APIs don't have job information. log4j does print thread id so that's a way to differentiate logs for different jobs, but I'm wondering what's the easiest/best way to add job id to the utility API logs?
I'm having roughly two thoughts that I'm not sure if I'm on the right direction,
Please advise, thanks.
For something like this, the mapped diagnostic context is a great way to track your job ID. You set it (and remove it in a finally
clause) on a per-thread basis, and you can reference it much like a thread name in a pattern layout.
@Override
protected void compute() {
MDC.put("job-id", jobId);
try {
/* Do your task */
} finally {
MDC.remove("job-id");
}
}