12

I'm using the Java default logger, and right now it's printing a lot of useless trash to the output, here is a example, this line of code:

log.info("Logging pointless information...")

Will output all of this:

Oct 26, 2011 9:37:57 PM java.util.logging.LogManager$RootLogger log
INFO: Logging pointless information...

I don't need to know anything except that second line. How can I remove this trash? All I want is simple text logging.

Chris Dolan
  • 8,905
  • 2
  • 35
  • 73
James T
  • 3,292
  • 8
  • 40
  • 70
  • 2
    FWIW, that "useless information" is very useful in a program of any size or duration. – Dave Newton Oct 27 '11 at 02:58
  • 2
    @DaveNewton - Personally, I'm a fan of logging tersely to console and verbosely to file (with an XML formatter). So I think both forms have great merit – Chris Dolan Oct 27 '11 at 03:02

3 Answers3

15

Maybe this was added later, but at least with Java 7, java.util.logging.SimpleFormatter supports getting its format from a system property. This JVM argument will print just the second line:

-Djava.util.logging.SimpleFormatter.format='%4$s: %5$s%6$s%n'

Personally, I like to keep all the date/source info, but get rid of the newline (and use a more compact, international date format):

-Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
Trevor Robinson
  • 15,694
  • 5
  • 73
  • 72
  • 2
    You seriously have no idea how much better you just made my life. This saved me at least 5 hours of work, on account of not familiar with java. – rlpowell Aug 13 '13 at 00:11
  • 1
    Thousands of little babies and little kittens and little baby kittens have been saved due to your answer here today. Thankful appreciation is in order. – Andrew Aug 24 '17 at 17:29
5

You need to create a a different Formatter and use it instead.

public class BriefFormatter extends Formatter 
{   
    public BriefFormatter() { super(); }

    @Override 
    public String format(final LogRecord record) 
    {
        return record.getMessage();
    }   
}
  • This approach logs the entire raw record, including XML. Actually much more verbose than SimpleFormatter. – Alicia Sep 05 '18 at 19:25
3

These are asking pretty much the same question:

Here's an example of how to implement Jarrod Roberson's suggestion: http://www.javalobby.org/java/forums/t18515.html

In general, to apply a formatter you create a file, usually called logging.properties. In it put a line like this:

java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

or whatever your formatter class is. Then add a JVM arg like this:

-Djava.util.logging.config.file=logging.properties

Or use a more powerful logging system, like Logback or Log4j, which have prebuilt formatters to save you some coding.

Community
  • 1
  • 1
Chris Dolan
  • 8,905
  • 2
  • 35
  • 73