How to handle ScopedLoggingContext for new Threads / ThreadPools?
brainbytes42 opened this issue · 1 comments
Is there any best practice to derive a ScopedLoggingContext for an application creating new threads (for the same context) or using a ThreadPool? I have applications that are running for several topics in parallel, but for each topic there will be multiple threads to calculate data, etc. - I'd like to have all threads refer to their respective topic...
Log4j provides / promotes some kind of mechanism (while not really that concise): Log4J Docs, see third listing in this section
Is there anything similar available for Flogger? Otherwise I'd like to propose a shortcut like the one sketched below to kind of inherit a context more easily:
ExecutorService executorService = Executors.newCachedThreadPool();
try (ScopedLoggingContext.LoggingContextCloseable ctx = ScopedLoggingContexts.newContext()
.withTags(Tags.of("Answer", 42))
.install()) {
// current solution
Tags tags = ContextDataProvider.getInstance().getTags();
executorService.submit(ScopedLoggingContexts.newContext().withTags(tags).wrap(() -> log.atInfo().log("Hello Pool!")));
// this would be nice
executorService.submit(ctx.inheritContext().wrap(() -> log.atInfo().log("Hello Pool!")));
(In the sketched version of ctx.inheritContext()
the inherited context should be able to be Closeable as the outer context, or use the wrapper-shortcut, which is really nice.)
Bonus-Question: Is there any mechanism to support this inheritance without explicitly propagating the context for the sub-threads? Some parts of my app are using plugins, which might call threads but maybe are not complying to inherit the logging context...
Thanks for any thoughts on this topic.
Edit: One more related question, thinking scopes and unified logging (for example using ELK-Stack): Ist there a way to set Tags or MetaData, so that they will be added to every log message, e.g. to track which process or machine the log originates from?
// this would be nice executorService.submit(ctx.inheritContext().wrap(() -> log.atInfo().log("Hello Pool!")));
Doesn't this already exist as newContext()
?
executorService.submit(ctx.newContext().wrap(() -> log.atInfo().log("Hello Pool!")));