简体   繁体   中英

Returning debug information in HTTP response body - Java

I'm looking to return per request debug information in a JSON HTTP response body. This debug information would be collected throughout my application, including data such as DB queries and how long they took, external calls made, whether certain conditions were met, general messages showing application flow etc.

I've looked into Java logging frameworks and the Play Framework, which I am using, has a built in logger that works great for logging information to files. But I can't seem to find any that handle request level logging ie store debug messages for this particular HTTP request to be returned with this request and then destroyed.

I could of course create a Debug class, instantiate that and pass that around throughout my application for each request, but this doesn't seem like a nice way to handle this as I would need to be passing this into a lot of classes in my application.

Are there any better ways/design patterns/libraries out there that can do what I'm looking for without having to pass a Debug object round my entire application?

It is not a common usage, so I do not think that you will find a product implementing that. You have basically 2 possibilities :

  • fully implement a custom logger and use it throughout your application
  • use a well known local api (slf4j, apache commons logging) and implement a dedicated back-end

Either way, the backend part should :

  • initiate a buffer to collect logs at request reception (probably in a filter) and put it in a ThreadLocal variable
  • collects all logs during the request help to the ThreadLocal variable
  • release the ThreadLocal variable at the end of request (in same filter that allocates it)

And all servlets of controllers should be modified to add the logging content to the json response body.

我找到了一个解决方案,Play框架使用Http.Context.current().args为任意对象提供了请求级存储Http.Context.current().args我正在使用此HashMap来存储我的自定义调试存储类,以便可以在整个请求中的任何地方访问它应用。

Instead of passing Debug object from layer to layer, why don't you use Http.Context? It is defined at Controller class:

public abstract class Controller extends Results implements Status, HeaderNames {

    ...

    public static Context ctx() {
        return Http.Context.current();
    }

}

Usage:

ctx().args.put(key, value)
ctx().args.get(key);

You don't need to use a logging framework for it. The best approach to return your debug info in the json response is to use the same method you are using to return the rest of the json.

This way, you can setup it to work in debug mode via -Dsomevar=debug or via an HTTP request parameter like debug=true

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