Tuesday, December 2nd, 2008

Java Quick Tip: Parameterized Logging

By Doug Burns

I hate writing ugly, concatenated logging statements like this:

package com.arc90.example;
import java.util.logging.Logger;
public class LoggingExample1
{
public static void main(String[] args)
{
Logger logger = Logger.getLogger(LoggingExample1.class.getName());
String user = "dougb";
int logins = 17;
int purchases = 2;
logger.info("User " + user + " has logged in " + logins +
" times and made " + purchases + " purchases.");
}
}

Fortunately, the Java Logging API gives you the ability to parameterize your statements (similar to JDBC prepared statements) so that you can turn the above into something like this:

package com.arc90.example;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LoggingExample2
{
public static void main(String[] args)
{
Logger logger = Logger.getLogger(LoggingExample2.class.getName());
String user = "dougb";
int logins = 17;
int purchases = 2;
// Single parameter
logger.log(Level.INFO, "User {0} successfully logged in.", user);
// Multiple parameters
logger.log(Level.INFO, "User {0} has logged in {1} times and made {2} purchases.",
new Object[] {user, logins, purchases});
}
}

You’ll need to use the logger.log(…) method rather than the more convenient logger.fine(…), logger.info(…) (etc.) methods, but in the end it makes for much cleaner code.

One Response

  1. Joel Potischman said:

    Nice. Log4J and log4Net do the same thing, and I believe for efficiency that it doesn’t even attempt to build your string if the logger level is higher than your log statement’s.
    In a production environment where you’re probably not logging FINE/R/ST entries, the parameterized approach would thus save you a lot of string concatenation execution time.

Leave a Comment