Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continue log on same line in Java?

This is similar to this question, which is about a bash file.

We've created a log which outputs to the console while we're running our TestNG tests:

private Log log = LogFactory.getLog(xyz.class);

Later on, during the tests, the log is filled with details to let us know what exactly is being done:

log.info("Setting browser...");
this.browser = browser;
log.info("Completed.");

Right now it's printing out as you would expect:

Setting browser...
Completed.

I'd like to have this print out on the same line:

Setting browser...

and a few milliseconds later:

Setting browser...Completed.

Is this possible with the LogFactory?

like image 632
rishimaharaj Avatar asked Jun 25 '12 19:06

rishimaharaj


2 Answers

Without knowing precisely which logging library you are using, I would guess that the answer is almost certainly not unless you want to explicitly specify a newline character everywhere else.

The java.util.logging (and Log4J) frameworks allow you to plugin formatters to format your statements. You'd need to specify a format which did not end with a newline character. For example, in Log4J. they give an example pattern as

 %-5p [%t]: %m%n

So if you removed everything except the %m (the %n is the newline and the other stuff includes the time and log-level; %t and %p respectively, I think), newlines would not be automatically appended to each statement.

However, this means that everywhere else, your other log statements would have to look like this:

log.info("I want this on one line\n");
like image 133
oxbow_lakes Avatar answered Oct 07 '22 16:10

oxbow_lakes


Leave the log alone. If you want it more readable, post-process it.

Messing with the log file will lose information unless you are careful. Look at timestamps as an example. If your Setting browswer.. log statement has a timestamp included, putting the completed statement without its timestamp is a loss of information and having two timestamps on the same line does not seem natural.

like image 42
Colin D Avatar answered Oct 07 '22 16:10

Colin D