Search code examples
javaprimitive-types

String Format and Logging primative types - Java


I am trying to write a class that wraps around the logger class in Java. My logging functions are of the form below:

public static void LogInfo(String fmt, Object... args) {
    String callerClass = walker.getCallerClass().getName();
    logger.info(String.format("[INFO] [%s] " + fmt, callerClass, args));
}

The problem I am having is trying to log primative types, bool, int, double, etc. I have read a little about "Autoboxing" and thought this would work for me but its not. When I try to log, E.g.

int i = 123;
Log.LogInfo("log a number: %d", i);

The error I get is:

Exception in thread "main" java.util.IllegalFormatConversionException: d != [Ljava.lang.Object;

I'm not usually a Java programmer so not sure how to resolve this. Any help would be greatly appreciated! Thanks


Solution

  • Try

    String callerClass = walker.getCallerClass().getName();
    logger.info(String.format("[INFO] [%s] ", callerClass) + String.format(fmt, args));
    

    The problem is when calling String.format() with callerClass and args, Java Varargs creates a new array containing a string and an array, which cannot be displayed by String.format().