简体   繁体   中英

logging id in quarkus vertx reactive

how to logging with a id in quarkus vertx reactive? I want to see processing steps from request to response with the same id in the log. Although each component is a different thread.

I'm afraid there's no built-in concept of a request ID, and you'll have to generate your IDs yourself. One solution could be that you use an AtomicLong instance to generate a request ID for each request.

Then, to store and access the ID, you basically have two options.

First option : you can store that ID in the request's context by having

@Inject
CurrentVertxRequest request;
(...)
request.getCurrent().put("requestId", id);

And then various components that produce logs can access the ID by

request.getCurrent().get("requestId");

and add that to the log message.

Second option : if you want to avoid the mess of having to append the ID in each log message manually, you can add it to the Mapped Diagnostic Context (MDC). The problem with this is that the MDC context is not propagated by default, so to make sure that each thread sees the ID, you'll need a custom ThreadContextProvider like this:

public class MdcContextProvider implements ThreadContextProvider {

    @Override
    public ThreadContextSnapshot currentContext(Map<String, String> props) {
        Map<String, String> propagate = MDC.getCopyOfContextMap();
        return () -> {
            Map<String, String> old = MDC.getCopyOfContextMap();
            MDC.setContextMap(propagate);
            return () -> {
                MDC.setContextMap(old);
            };
        };
    }

    @Override
    public ThreadContextSnapshot clearedContext(Map<String, String> props) {
        return () -> {
            Map<String, String> old = MDC.getCopyOfContextMap();
            MDC.clear();
            return () -> {
                MDC.setContextMap(old);
            };
        };
    }

    @Override
    public String getThreadContextType() {
        return "MDC";
    }
}

and add a META-INF/services/org.eclipse.microprofile.context.spi.ThreadContextProvider file containing the qualified name of that class. Then, store the request ID in the MDC using

MDC.put("rid", requestId);

And change the formatting string of your logs (for example, the quarkus.log.console.format property) to contain a reference to it, which would be %X{rid} , to make sure that this value is added to each log. With this option you should probably also make sure that the MDC entry gets cleared when the request processing is done. So this option is unfortunately much more complicated, but will potentially help keep your code cleaner, because you won't have to append the ID to each log.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM