My thoughts as an enterprise Java developer.

Tuesday, October 13, 2009

[JavaSpecialists 177] - Logging Part 3 of 3

[JavaSpecialists 177] - Logging Part 3 of 3: "For example, here is a Layout for Log4J that can be used to collapse lines with '|>>' instead of a newline character. For readability, it is trivial to then replace those characters with \n again."

import org.apache.log4j.*; import org.apache.log4j.spi.*;  import java.io.*;  public class MultipleLineLayout extends Layout {   public String format(LoggingEvent event) {     Object o = event.getMessage();     if (o instanceof Throwable) {       return format((Throwable) o);     }     return format(String.valueOf(event.getMessage()));   }    private String format(Throwable t) {     StringWriter out = new StringWriter();     PrintWriter pw = new PrintWriter(out);     t.printStackTrace(pw);     pw.close();     return format(out.toString());   }    private String format(String s) {     return s.         replaceAll("\r", ""). // remove Windows carriage returns         replaceAll("\n*$", ""). // remove trailing newline chars         replaceAll("\n", " |>> ") // replace newline with |>>         + "\n";   }    public boolean ignoresThrowable() {     return false;   }    public void activateOptions() {     // not necessary   } }

No comments: