'MapUtils with Logger

I am using MapUtils.verbosePrint(System.out, "", map) to dump the contents of a map in Java. They (management) do not like us using System.out.println().

We are using log4j. They made the logger into a variable "l" so we can say something like l.debug("This is going to the logfile in debug mode).

I would like to get the output buffer(s) from l so I could pass it into verbosePrint() instead of System.out. I looked at all the methods and members of the logger and did things like getAppenders() and tried all those elements but I could not find anything that helped.

Has anyone else done this? I know the logger may write to > 1 output.



Solution 1:[1]

You can use Log4j IOStreams to create PrintStreams that will send everything to a logger. This is mostly useful to log debug output from legacy APIs like JDBC or Java Mail that do not have a proper logging system. I wouldn't advise it in other cases, since your messages might be merged or split into several log messages.

I would rather use one of these approaches:

  • simply log the map using Logger#debug(Object). This will lazily create an ObjectMessage (only if debug is enabled), which is usually formatted using the map's toString() method. Some layouts might format it differently (like the JSON Template Layout).
  • eagerly create a MapMessage or StringMapMessage:
    if (l.isDebugEnabled()) {
        l.debug(new MapMessage(map));
    }
    
    This gives you more formatting options. For example the layout pattern %m{JSON} will format your message as JSON.
  • if your are set on the format provided by MapUtils#verbosePrint, you can extend ObjectMessage and overwrite its getFormattedMessage() and formatTo() methods.
    public String getFormattedMessage() {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        MapUtils.verbosePrint(new PrintStream(os), "", );
        return new String(os.toByteArray());
    }
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Piotr P. Karwasz