Search code examples
javalog4jndc

log4j, nested diagnostic contexts


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? 
    }

}

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.