Yuvi
Yuvi

Reputation: 41

Multiple loggings in the same line as well as in different lines in same file in java

I am new to using Log4j logger,I wanted to print some of the logging statements to be in the same line.

Example :

log.debug(root.data);
    if(root.left!=null)
        log.debug("("+root.left.data);
    else if(root.left==null)
        log.debug("null");
    if(root.right!=null)
        log(root.right.data+")");
    else if(root.right!=null)
        log.debug("null)");  

It will print like this (3,

                null)

But i wanted to print like this (3,null).

But i have other log statements which should be printed in normal behaviour

Example:

void function()
{
log.debug("Entered First Function");
}
public static void Main()
{
log.debug("In Main Method");
}

In Main Method

Entered First Function

Upvotes: 0

Views: 1522

Answers (2)

František Hartman
František Hartman

Reputation: 15086

Correct log4j idiom (1.2 version) would be

if (log.isDebugEnabled()) {
  log.debug("(" + root.left.data + "," + root.right.data + ")");
}

It will take care of the nulls correctly. The condition will prevent any performance hit in case debug level is disabled.

You might want to use some more modern logging api, like slf4j, logback or log4j 2. The readability would be much better:

log.debug("({},{})", root.left.data, root.right.data);

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

You could use String.format(String, Object...) and a pair of ternaries. Something like,

log.debug(String.format("(%s, %s)", //
        root.left == null ? "null" : root.left.data, //
        root.right == null ? "null" : root.right.data));

or without the ternaries like

if (root.right == null || root.left == null) {
    if (root.left == null) {
        if (root.right == null) {
            log.debug("(null, null)");
        } else {
            log.debug(String.format("(null, %s)", root.right.data);
        }
    } else {
        log.debug(String.format("(%s, null)", root.left.data);
    }
} else {
    log.debug(String.format("(%s, %s)", root.left.data, root.right.data);
}

Upvotes: 1

Related Questions