I want to use logs in my program. I heard about java.util.logging, but I don't know how to begin.
Are there any examples of what can I do with logging? How would I use logging in my own program?
I want to use logs in my program. I heard about java.util.logging, but I don't know how to begin.
Are there any examples of what can I do with logging? How would I use logging in my own program?
I'd use minlog, personally. It's extremely simple, as the logging class is a few hundred lines of code.
I would suggest that you use Apache's commons logging utility. It is highly scalable and supports separate log files for different loggers. See here.
Should declare logger like this:
so if you refactor your class name it follows.
I wrote an article about java logger with examples here.
SLF4J is a better logging facade than Apache Commons Logging (ACL). It has bridges to other logging frameworks, making direct calls to ACL, Log4J, or Java Util Logging go through SLF4J, so that you can direct all output to one log file if you wish, with just one log configuration file. Why would your application use multiple logging frameworks? Because 3rd-party libraries you use, especially older ones, probably do.
SLF4J supports various logging implementations. It can output everything to standard-out, use Log4J, or Logback (recommended over Log4J).
http://www.slf4j.org/
http://logback.qos.ch/
There are many examples and also of different types for logging. Take a look at the java.util.logging package.
Example code:
Without hard-coding the class name:
java.util.logging
keeps you from having to tote one more jar file around with your application, and it works well with a good Formatter.In general, at the top of every class, you should have:
Then, you can just use various facilities of the Logger class.
Use
Level.FINE
for anything that is debugging at the top level of execution flow:Use
Level.FINER
/Level.FINEST
inside of loops and in places where you may not always need to see that much detail when debugging basic flow issues:Use the parameterized versions of the logging facilities to keep from generating tons of String concatenation garbage that GC will have to keep up with.
Object[]
as above is cheap, on the stack allocation usually.With exception handling, always log the complete exception details:
I always pass
ex.toString()
as the message here, because then when I "grep -n
" for "Exception
" in log files, I can see the message too. Otherwise, it is going to be on the next line of output generated by the stack dump, and you have to have a more advanced RegEx to match that line too, which often gets you more output than you need to look through.