Hi,

I'm using log4j 1.2beta3 with my color add-on but it should work with
other releases as well.

The idea comes from the logging framework of xmlBlaster.org. Once you get
used to colored logs on the console, you won't miss it.

As far as I know (means I haven't tested further on) it works only with
the ConsoleAppender. On the other hand: where else does it make really
sense? And: I only tested it on Linux in xterms.

The Attachment contains a png-image 'log4jColorDemo.png' showing the
demo/test on a Linux-xterm.

The example of Anders Kristensen, which shows how to extend PatternParser
and PatternLayout was my example which I extended to get colored output.

See the code in this eMail.

The properties how it works for me look like follows:

excerpt from my log4j.properties:
---- 8< ----
log4j.rootCategory = INFO, myRoot
log4j.appender.myRoot = org.apache.log4j.ConsoleAppender
log4j.appender.umtsRoot.layout = org.umts.helper.MyPatternLayout
log4j.appender.umtsRoot.layout.ConversionPattern = [%d{HH:mm:ss} %P %F.%M] %m%n
---- 8< ----

Basicly it's all the same except the '%P' pattern is for colored
Loglevels.




---- 8< ----
/*------------------------------------------------------------------------------"
Name:      MyPatternParser.java
Comment:   extends the pattern parser of log4j
Author:    Heinrich Goetzger
-------------------------------------------------------------------------------*/
/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software
 * License version 1.1, a copy of which has been included with this
 * distribution in the LICENSE.APL file.  */

import org.apache.log4j.*;
import org.apache.log4j.helpers.FormattingInfo;
import org.apache.log4j.helpers.PatternConverter;
import org.apache.log4j.helpers.PatternParser;
import org.apache.log4j.spi.LoggingEvent;

/*
  Example showing how to extend PatternParser to recognize additional
  conversion characters.  The examples shows that minimum and maximum
  width and alignment settings apply for "extension" conversion
  characters just as they do for PatternLayout recognized characters.

  In this case MyPatternParser recognizes %# and outputs the value
  of an internal counter which is also incremented at each call.

  It also shows a way how to colorize the priorities for all log levels.

  See <a href=doc-files/MyPatternParser.java><b>source</b></a> code
  for more details.

  @see org.apache.log4j.examples.MyPatternLayout
  @see org.apache.log4j.helpers.PatternParser
  @see org.apache.log4j.PatternLayout

  @author Anders Kristensen
  @author Heinrich Go&uml;tzger
*/


/**
   <p>
   Extends the default pattern parser by two pattern.
   </p>

   <p>
   <code>%#</code> outputs the value of an internal counter which is
   incremented at each call.
   </p>

   <p>
   <code>%</code>P outputs the log level in a colored way, it works just as 
<code>%</code>p.
   </p>

   @author <a href="mailto:[EMAIL PROTECTED]";>Heinrich G&ouml;tzger</a>
   @see <a href="http://jakarta.apache.org/log4j/docs/index.html";>Log4j Project</a>

 */
public class MyPatternParser extends PatternParser {

   // colors foreground/background (for xterm)
   private static final String ESC          = "\033[0m"; // Reset color to original 
values
   private static final String BOLD         = "\033[1m";

   private static final String RED_BLACK    = "\033[31;40m";
   private static final String GREEN_BLACK  = "\033[32;40m";
   private static final String YELLOW_BLACK = "\033[33;40m";
   private static final String BLUE_BLACK   = "\033[34;40m";
   private static final String PINK_BLACK   = "\033[35;40m";
   private static final String LTGREEN_BLACK= "\033[36;40m";
   private static final String WHITE_BLACK  = "\033[37;40m";

   private static final String WHITE_RED    = "\033[37;41m";
   private static final String BLACK_RED    = "\033[30;41m";
   private static final String BLACK_GREEN  = "\033[40;42m";
   private static final String BLACK_PINK   = "\033[40;45m";
   private static final String BLACK_LTGREEN= "\033[40;46m";

   //private static final String callE  = new String(BLUE_BLACK    + "CALL " + ESC);
   //private static final String timeE  = new String(LTGREEN_BLACK + "TIME " + ESC);
   //private static final String dumpE  = new String(PINK_BLACK    + "DUMP " + ESC);
   //private static final String plainE = new String(WHITE_BLACK   + "     " + ESC);

   private static final String debugE = new String(       PINK_BLACK   + "DEBUG" + 
ESC);
   private static final String infoE  = new String(       GREEN_BLACK  + "INFO " + 
ESC);
   private static final String warnE  = new String(       YELLOW_BLACK + "WARN " + 
ESC);
   private static final String errorE = new String(       RED_BLACK    + "ERROR" + 
ESC);
   private static final String fatalE = new String(BOLD + WHITE_RED    + "FATAL" + 
ESC);

   int counter = 0;

   /**
   Creates a new pattern parser by calling the inherited constructer.

   @param pattern The pattern which gives the layout of the log message.
   */
   public MyPatternParser(String pattern) {
      super(pattern);
   }

   /**
   Extension of the default parser for the two additional pattern
   <code>#</code> and <code>P</code>

   @param c pattern to parse
   */
   public void finalizeConverter(char c) {
      switch(c) {
      case '#':
         addConverter(new UserDirPatternConverter(formattingInfo));
         currentLiteral.setLength(0);
         break;
      case 'P':
         addConverter(new UserDirPriorityColorizer(formattingInfo));
         break;
      default:
         super.finalizeConverter(c);
      }
   }

   /**
   Pattern converter, implements the action which has to be done for pattern 
<code>#</code>.

   */
   private class UserDirPatternConverter extends PatternConverter {

   /**
   Constructs a Converter using the supplied formatting information.

   @param formattingInfo
   */
      UserDirPatternConverter(FormattingInfo formattingInfo) {
         super(formattingInfo);
        }

   /**
   increments the internal counter at each call.

   @param event the logging event
   @return the actual value of the counter
   */
      public String convert(LoggingEvent event) {
         return String.valueOf(++counter);
      }
   } // end of inner class

   /**
   Pattern converter, implements the action which has to be done for pattern 
<code>P</code>.

   */
   private class UserDirPriorityColorizer extends PatternConverter {

   /**
   Constructs a Converter using the supplied formatting information.

   @param formattingInfo
   */
      UserDirPriorityColorizer(FormattingInfo formattingInfo) {
         super(formattingInfo);
      }

   /**
   increments the internal counter at each call.

   @param event the logging event
   @return the colored name of the logging event
   */
      public String convert(LoggingEvent event) {
         String ret = null;

         if( event.priority.toString().equalsIgnoreCase("DEBUG") )
            ret = debugE;

         if( event.priority.toString().equalsIgnoreCase("INFO") )
            ret = infoE;

         if( event.priority.toString().equalsIgnoreCase("WARN") )
            ret = warnE;

         if( event.priority.toString().equalsIgnoreCase("ERROR") )
            ret = errorE;

         if( event.priority.toString().equalsIgnoreCase("FATAL") )
            ret = fatalE;

         return ret;
      }
   } // end of inner class
} // end of class
---- 8< ----


---- 8< ----
/*------------------------------------------------------------------------------"
Name:      MyPatternLayout.java
Comment:   extends the pattern layout of log4j
Author:    Heinrich Goetzger
-------------------------------------------------------------------------------*/
/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software
 * License version 1.1, a copy of which has been included with this
 * distribution in the LICENSE.APL file.  */

import org.apache.log4j.*;
import org.apache.log4j.helpers.PatternParser;

/*

  Example showing how to extend PatternLayout to recognize additional
  conversion characters.

  In this case MyPatternLayout recognizes %# conversion pattern. It
  outputs the value of an internal counter which is also incremented
  at each call.

  It also shows a way how to colorize the priorities for all log levels.

  See <a href=doc-files/MyPatternLayout.java><b>source</b></a> code
  for more details.

  @see MyPatternParser
  @see org.apache.log4j.PatternLayout
  @author Anders Kristensen
  @author Heinrich G$ouml;tzger
*/

/**
   <p>
      Extends the default pattern layout by two pattern.
   </p>

   <p>
      <code>%</code># outputs the value of an internal counter which is
      incremented at each call.
   </p>

   <p>
      <code>%</code>P outputs the log level in a colored way, it works just as 
<code>%</code>p.
   </p>

   @author <a href="mailto:[EMAIL PROTECTED]";>Heinrich G&ouml;tzger</a>
   @see <a href="http://jakarta.apache.org/log4j/docs/index.html";>Log4j Project</a>

 */
public class MyPatternLayout extends PatternLayout {

   /**
   Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN.
   */
  public MyPatternLayout() {
    this(DEFAULT_CONVERSION_PATTERN);
  }

   /**
   Constructs a PatternLayout using the supplied conversion pattern.

   @param pattern The pattern which gives the layout of the log message.
   */
  public MyPatternLayout(String pattern) {
    super(pattern);
  }

   /**
   Returns PatternParser used to parse the conversion string.

   @param pattern the pattern of the log message
   @return The PatternParser which has been instanciated with the given pattern
   */
  public PatternParser createPatternParser(String pattern) {
    return new MyPatternParser(pattern == null ? DEFAULT_CONVERSION_PATTERN : pattern);
  }

   /**
   For testing only.
   <p>
      Call:
      <pre>java MyPatternLayout</pre>
   </p>

      This gives you a output similar to:  <br />
      (it's colored in origin ;-)
   <pre>
      [15:26:29 INFO  main] (MyPatternLayout.java:main) &lt;counter=1&gt; - Using 
pattern: '[<code>%</code>d{HH:mm:ss} <code>%</code>P <code>%</code>t] 
(<code>%</code>F:<code>%</code>M) &lt;counter=<code>%</code>.10#&gt; - 
<code>%</code>m<code>%</code>n'
      [15:26:29 DEBUG main] (MyPatternLayout.java:main) &lt;counter=2&gt; - Hello 
debug...
      [15:26:29 INFO  main] (MyPatternLayout.java:main) &lt;counter=3&gt; - Hello 
info...
      [15:26:29 WARN  main] (MyPatternLayout.java:main) &lt;counter=4&gt; - Hello 
warn...
      [15:26:29 ERROR main] (MyPatternLayout.java:main) &lt;counter=5&gt; - Hello 
error...
      [15:26:29 FATAL main] (MyPatternLayout.java:main) &lt;counter=6&gt; - Hello 
fatal...
   </pre>

   @param args The arguments given from commandline.
   */
   public static void main(String[] args) {
      String pattern1 = "[%d{HH:mm:ss} %P %t] (%F:%M) <counter=%.10#> - %m%n";

      // Layout layout = new MyPatternLayout("%r [counter=%.10#] %-5p %P - %m%n");
      // Layout layout = new MyPatternLayout("[%d{MMM dd, yyyy HH:mm:ss,SSS} %P %t] 
(%F:%M{%L}) <%l> - %m%n");

      Layout layout = new MyPatternLayout(pattern1);
      Category cat = Category.getInstance("some.cat");

      cat.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT));
      cat.info("Using pattern: '" + pattern1 + "'");
      cat.debug("Hello debug...");
      cat.info("Hello info...");
      cat.warn("Hello warn...");
      cat.error("Hello error...");
      cat.fatal("Hello fatal...");
   }

} // end of class
---- 8< ----


best regards, enjoy

Heinrich
--
http://www.xmlBlaster.org

PS: I'm out of town until comming sunday, if you have further question.

Attachment: log4jColorDemo.png
Description: log4jColorDemo.png

--
To unsubscribe, e-mail:   <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>

Reply via email to