Question

I have a MySession object (a generic Session, not web) that runs in its thread. I want to use NDC class in order to include some data taken from fields of my MySession: user that has created it, starting time etc. etc. I'd like to "render" fields into a message. Is it possible or is it supported only for messages? Thanks in advance

public class MySession {
    String userName;
    Date startTime;

    public void doSomething() {
        NDC.push(this);                                    //cannot do something like this?
        NDC.push(this.userName 
                  + " " + startTime.toString());          //or should I do this? 
    }

}
Was it helpful?

Solution

A NDC just adds a "context" (freeform string) to all log messages (which may or may not be output depending on the logging format). The nested part means that NDC.pop() returns to the previous (next layer up) context.

Still, at any given point the context is a single freeform string - so you're right that you'd have to push something like this.username + '.' + this.startTime.toString(), as in your second example. You can see from the API that push takes a String argument; this context is only used in terms of being part of a logging message (implicitly a String), so there would be no benefit in accepting arbitrary objects of a different type.

OTHER TIPS

You can put practically whatever text (or the textual representation of whatever object) you want into an NDC. Rendering objects into the NDC is not supported, as toString() is (or at least should) almost always enough. Too much and/or complex stuff in the NDC would make the logs harder to read, so it is advisable to restrict NDC content to the minimum necessary.

E.g. in your case, putting the sesion start time into each log message would be overkill (and potentially ambiguous too). It would be better to push only some sort of unique session id into the NDC (if you have such a thing, that is), and log any other session details, such as username, startup time in dedicated message(s) right after setting the NDC. This still allows you to retrieve all the necessary session data from your logs, and to identify the corresponding session for any specific log message.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top