views:

531

answers:

4

How does The JDK's Logger compare to Apache log4j?

Which one is better for new projects that target Java 6? How do they compare in terms of flexibility and configurability?

+4  A: 

I've never used the direct JDK logger, but for a new project I'd highly reccomend Logback, designed as a successor for log4j. Some of the very nice things you can do with it:

  • printf style parameter building, no more messy concatenating strings protected by if logger.isDebugEnabled() guards.

go from

if (log.isDebugEnabled())
 { 
    log.warn (i + "many ints,"+ l+"many longs");
}

to

log.debug("{} many ints, {} many longs", i, l);
  • very flexible config, including configurations that will print traces. The config is xml, but their site includes a utility that will generate an xml config from your log4j config to get you started.

Downside - lots of packages require log4j anyway, since it's so common, so your project may need to include 2 logging packages.

Steve B.
The existent log4j dependency makes me tempted to stick to it for such projects!
notnoop
+9  A: 

To my mind the only thing the JDK Logger has going for it is that it is part of the JDK, so it doesn't add an external dependency. If the choice is only between those two, I'd go with Log4j. It still has better support in terms of appenders, the number of people who know it (in my anecdotal observations), and a better API (that is subjective as well).

Starting a project today, the most tempting thing to do is go with slf4j and deffer the decision - you can always plug in a different framework underneath slf4j by just changing the classpath.

That being said there are other options (such as Log5j) that take advantage of the latest Java language features. I'd recommend taking a long look Logback (from one of the main programmers of Log4j, as is slf4j).

Yishai
After reviewing Logback, I think I'll use it for new projects without any library dependancies on log4j, and log4j otherwise.
notnoop
+2  A: 

For a new project I would strongly recommend the slf4j project which provides generic frontend to several logger frameworks.

The {}-syntax described by Steve B is present in slf4j too (same author) so you get all the benefits regardless of backend, and STILL get the backend independency. Also a log4j bridge is available so existing code transparently can use slf4j. It is really nice.

For actual backend, logback is nice but you may already have invested in log4j - this is easily leveragable.

Thorbjørn Ravn Andersen
A: 

I would recommend the JDK logging API. I have used it for many years, without any problem whatsoever. It's part of the JDK, so no extra jar is required. The distinctions between log4j and JDK logging are small, and, in my opinion, don't justify the use of log4j.

John O