Good examples using java.util.logging [closed]
Asked Answered
A

3

299

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?

Acculturize answered 10/5, 2011 at 13:11 Comment(4)
You can start here: slf4j.org/manual.htmlOeflein
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.Promethium
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). slf4j.org logback.qos.cIde
I'd use minlog, personally. It's extremely simple, as the logging class is a few hundred lines of code.Duaneduarchy
M
379

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:

private static final Logger LOGGER = Logger.getLogger( ClassName.class.getName() );

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:

LOGGER.log( Level.FINE, "processing {0} entries in loop", list.size() );

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:

LOGGER.log( Level.FINER, "processing[{0}]: {1}", new Object[]{ i, list.get(i) } );

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:

try {
    ...something that can throw an ignorable exception
} catch( Exception ex ) {
    LOGGER.log( Level.SEVERE, ex.toString(), ex );
}

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.

Marseillaise answered 8/5, 2013 at 19:11 Comment(5)
Does this write to a file of some kind. I couldn't get it to work yet in my program. I have the initial line that you have but nothing has been worked so far.Immutable
How do you view the logs? A library I'm using initializes Logger objects and uses the .fine() method to log, but I can't seem to make the messages display...Bono
I've been programming in Java since 1998. I have always found logging in Java to be much more of a headache than it need be. This is by far the most straightforward explanation of how to log in Java that I've read. Concise too.Tamtam
It is interesting that no one has mentioned, where one can find the log files.Froggy
If you're wondering where the logs go, make sure you've set up a Handler for the Logger. To simply output logs to the console, use a new ConsoleHandler, and add this to your logger using the addHandler method. Make sure you call setLevel on both the logger and the handler.Arbuthnot
B
72

Should declare logger like this:

private final static Logger LOGGER = Logger.getLogger(MyClass.class.getName());

so if you refactor your class name it follows.

I wrote an article about java logger with examples here.

Blaineblainey answered 30/10, 2012 at 6:8 Comment(0)
C
58

There are many examples and also of different types for logging. Take a look at the java.util.logging package.

Example code:

import java.util.logging.Logger;

public class Main {

  private static Logger LOGGER = Logger.getLogger("InfoLogging");

  public static void main(String[] args) {
    LOGGER.info("Logging an INFO-level message");
  }
}

Without hard-coding the class name:

import java.util.logging.Logger;

public class Main {
  private static final Logger LOGGER = Logger.getLogger(
    Thread.currentThread().getStackTrace()[0].getClassName() );

  public static void main(String[] args) {
    LOGGER.info("Logging an INFO-level message");
  }
}
Chaussure answered 10/5, 2011 at 13:14 Comment(10)
Why not setting log name as Main.class.getSimpleName()? This way refactoring tool is going to change it properly if needed and yet, it's not as clunky as your second solution.Immingle
What does "clunky" mean, and why do you consider it clunky? The second solution will work with all refactoring tools (because the class name is derived). See also: https://mcmap.net/q/101867/-java-quot-self-quot-static-referenceKilkenny
Doing a stacktrace for a logger name is hack, slow and unorthodox. It will also break and give you weird names for AOP proxies or other byte coding extraordinaire.Cadman
-1 for the stacktrace business. It's slow and potentially prevents compiler optimizations.Thinking
Also -1 for the stack trace business, +1 for the MyClass.class.getName below.Holst
Why would the "slowness" matter at all when initializing the logger? Mentions of slowness are what most people would call premature optimization (Yes, the code does look a bit hackish).Dauphin
@Pius Why call Main.class.getSimpleName() at all if you already know the class name is "Main"? Is it to break type checking if someone changes the class name?Intercom
@AndrewMcKinlay In what situation does it break anything? If logger tag is supposed to be the same as the class name, it seems perfectly fine to do so. Refactoring tools are going to rename it automatically while, if it was a hard-coded string, refactoring tool may either skip it or say "Do you also want to rename this?".Immingle
@Plus Oh I see. Sorry, I didn't mean "type checking", I meant identifier resolution (or whatever). I see the point of your solution. Your solution doesn't avoid hard-coding, but it is amenable to automated refactoring assuming you are using an IDE or other tool.Intercom
I personally love the stacktrace solution. I am so sick of having to cut and paste the class name every time.Microgram

© 2022 - 2024 — McMap. All rights reserved.