Search code examples
javagoogle-app-enginestackdrivergoogle-cloud-logging

How to get trace ID from code?


I am running a Java application on Google App Engine standard environment.

Looking at the logs (in particular request_log), I can see a couple of interesting IDs such as trace_id and request_id for each request.

Couple of questions:

  • How are they different? Are they unique?
  • How to obtain them in application code (for the current request)? I would like to log them to a different Stackdriver dataset and be able to correlate the data

Solution

  • In the request handler you can access the headers and pull out X-Cloud-Trace-Context form the HttpServletRequest

    @WebServlet(name = "requests", description = "Requests: Trivial request", urlPatterns = "/requests")
    public class RequestsServlet extends HttpServlet {
      @Override
      public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getHeader("X-Cloud-Trace-Context")
      }
    }