简体   繁体   中英

How to log request and response in Vertx framework for Java Application

I tried this one https://github.com/zalando/logbook but it only works in spring based application. Does someone knows how to log request and response in Vertx framework?

This is a bit of a broad question, but let me try to answer it in a couple of segments.

First, I assume you are looking for a logger library. Vertx provides something like that, but it is deprecated and they encourage you to use third-party libs like Log4J or SLF4J. To use it, you need to add it as a dependency to your pom.xml like this (assuming you use maven):

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.32</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.32</version>
</dependency>

After that, you can instantiate a logger like this:

final static Logger logger = LoggerFactory.getLogger("loggerName");

and use it like this:

logger.info("Logging this message!")

As to where to log HTTP request, you have to go where you handle your HTTP routes and define and register a handler. For response, that is something you send so you easily log (with logger) in the place in the code where you create it. This is how you would handle HTTP request logging:

final Handler<RoutingContext> loggingHandler = routingContext -> {
    // here you access properties of routingContext.request() and log what you want
}
router.route().handler(loggingHandler);

As for response, somewhere in your code you create response like this: HttpServerResponse response = context.response().setStatusCode(status); and then send it with response.end(content) . Before calling .end() you can log what you need by accessing properties of response .

Add the following handler to your router and log to your needs

private fun loggingHandler(routingContext: RoutingContext) {
    routingContext.addHeadersEndHandler {
      // log context.request() and context.response() as required
    }
    routingContext.next()
}

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