Index: lutinutil/src/java/org/codelutin/util/LoggingPatternFormatter.java diff -u /dev/null lutinutil/src/java/org/codelutin/util/LoggingPatternFormatter.java:1.1 --- /dev/null Wed Aug 4 10:01:52 2004 +++ lutinutil/src/java/org/codelutin/util/LoggingPatternFormatter.java Wed Aug 4 10:01:47 2004 @@ -0,0 +1,418 @@ +/**##%% +* Copyright (C) 2002, 2003 Code Lutin +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software +* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*##%%**/ + +/** +* PatternFormatter.java +* +* Created: Sat Apr 20 2002 +* +* @author POUSSIN Benjamin +* Copyright Code Lutin +* @version $Revision: 1.1 $ +* +* Mise a jour: $Date: 2004/08/04 10:01:47 $ +* par : $Author: bpoussin $ +*/ + +package org.codelutin.logging; + +import java.util.logging.Formatter; +import java.util.logging.LogRecord; +import java.util.logging.LogManager; +import java.util.Date; +import java.text.SimpleDateFormat; +import java.util.HashMap; +import java.util.Iterator; +import java.util.ArrayList; + +/** +* Classe org.codelutin.logging.PatternFormatter. +* +* +* +* +* +* Date follow the same pattern as DateFormat. +* +* +* +* Sized element support justify pattern. +* {[+|-][:]}. +* '+' is +* left justify, '-' rigth justify, size the prefered size for the element if it is not bigger. +* If maxPos option is present blanc is not add if it go up to maxPos. +* +*
    SubString +*
  • M: method name
  • +*
+* +* L'element SubString a les memes possibilites que le pattern justify, +* et permet en plus de suprimer une sous chaine, +* cela permet de supprimer le debut du nom d'une classe. +* Syntaxe : +* {*<substring>|[+|-]<size>[:<maxPos>]} +* {<substring>*|[+|-]<size>[:<maxPos>]} +* L'etoile represente le texte qui restera. +*/ +public class LoggingPatternFormatter extends Formatter { // PatternFormatter + + private static final String DEFAULT_PATTERN = + "%d{yyyy-MM-dd HH:mm:ss} [free:%o{-7}|total:%O{-7}][%t][%p{7}] %c{org.codelutin.*|25} %M{15:105}: %m%n"; + + protected HashMap arguments = null; + protected ArrayList compile = null; + protected String pattern = null; + + public LoggingPatternFormatter() { + try{ + arguments = new HashMap(); + initArguments(); + LogManager manager = LogManager.getLogManager(); + String cname = this.getClass().getName(); + pattern = manager.getProperty(cname + ".pattern"); + if ( pattern == null ) + pattern = DEFAULT_PATTERN; + compilePattern(pattern); + }catch(Exception eee){ + System.err.println("Impossible d'utiliser le PatternFormatter"); + eee.printStackTrace(); + throw new LoggingException("Exception durant l'initialisation du PatternFormatter", eee); + } + } + + /** + * Methode qui formate le record + */ + public String format(LogRecord record){ + StringBuffer result = new StringBuffer(); + for ( Iterator i=compile.iterator(); i.hasNext();) + ((Argument)i.next()).toString(record, result); + return result.toString(); + } + + /** + * Si vous souhaitez ajouter des type d'argument + * Surcharger cette methode et a la fin fait un super.initArguments() + */ + protected void initArguments(){ + arguments.put("d", DateArgument.class); + arguments.put("o", FreeMemoryArgument.class); + arguments.put("O", TotalMemoryArgument.class); + arguments.put("t", ThreadArgument.class); + arguments.put("p", PriorityLevelArgument.class); + arguments.put("c", ClassNameArgument.class); + arguments.put("M", MethodNameArgument.class); + arguments.put("m", MessageArgument.class); + } + + /** + * Genere a partir de la chaine la liste des objet Argument. + */ + protected void compilePattern(String pattern){ + compile = new ArrayList(); + int next = 0; + String[] match = findNextPattern(pattern); + while(!match[1].equals("")){ + compile.add(new StringArgument(match[0])); + compile.add(patternToArgument(match[1])); + match = findNextPattern(match[2]); + } + compile.add(new StringArgument(match[0])); + } + + /** + * Recherche dans la chaine le prochaine pattern. + * @return un tableau de 3 chaines, [0] ce qu'il y a avant le + * parttern, [1] le parttern, [2] ce qu'il y a apres le pattern. + */ + protected String [] findNextPattern(String s){ + String [] result = new String[]{"","",""}; + if( s == null ) + return result; + + int d = s.indexOf("%"); + + if(d != -1){ // il y a un % + if ( d+2 < s.length() && s.charAt(d+2) == '{' ){ + int f = s.indexOf("}", d); + if(f != -1){ // il y a une pattern %c{pattern} + result[0] = s.substring(0, d); + result[1] = s.substring(d+1, f); + result[2] = s.substring(f+1); + } + else{ + throw new LoggingException("Error, { at position "+(d+2)+" not terminated in :"+s); + } + } + else{ //pas de pattern + result[0] = s.substring(0, d); + result[1] = s.substring(d+1, d+2); + result[2] = s.substring(d+2); + } + } + else + result[0] = s; + + return result; + } + + /** + * Converti un pattern en un objet Argument + */ + protected Argument patternToArgument(String s){ + if ( s.charAt(0) == 'n' ){ // new ligne + return new StringArgument("\n"); + + }else if ( s.charAt(0) == '%' ){ // le caractere % + return new StringArgument("%"); + + }else if ( s.charAt(0) == '{' ){ // le caractere { + return new StringArgument("{"); + + }else{ + String code = s.substring(0,1); + Class argumentClass = (Class)arguments.get(code); + if ( argumentClass == null ) + throw new LoggingException("Erreur dans le pattern '" + + code + "' inconnu"); + Argument argument = null; + try{ + argument = (Argument)argumentClass.newInstance(); + }catch(InstantiationException eee){ + throw new LoggingException("Erreur lors de l'instanciation de l'objet Argument: "+argumentClass.getName(), eee); + }catch(IllegalAccessException eee){ + throw new LoggingException("Erreur lors de l'instanciation de l'objet Argument: "+argumentClass.getName(), eee); + } + if ( s.length() > 1 ) { // on a un pattern + argument.setPattern(s.substring(2)); + } + + return argument; + } + } + + + /////////////////////////////////////////////////////////////////////////////// + //////////////////////////// Les Classes Argument ///////////////////////////// + /////////////////////////////////////////////////////////////////////////////// + + static protected abstract class Argument{ + protected String pattern; + public Argument(){} + public void setPattern(String pattern){ + this.pattern = pattern; + } + abstract public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo); + } + + static protected class StringArgument extends Argument{ + protected String s = null; + public StringArgument(String s){ + super(); + this.s = s; + } + public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo){ + toAppendTo.append(s); + return toAppendTo; + } + } + static protected class DateArgument extends Argument{ + protected SimpleDateFormat dateFormat = null; + + public DateArgument(){super();} + public void setPattern(String pattern){ + super.setPattern(pattern); + dateFormat = new SimpleDateFormat(pattern); + } + public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo){ + toAppendTo.append(dateFormat.format(new Date(record.getMillis()))); + return toAppendTo; + } + } + static abstract protected class SizedArgument extends Argument{ + protected boolean left = true; + protected int width = 0; + protected int maxPos = -1; + public SizedArgument(){super();} + public void setPattern(String pattern){ + super.setPattern(pattern); + if ( pattern.length() > 0 ){ + String [] subpattern = pattern.split(":"); + pattern = subpattern[0]; + char op = pattern.charAt(0); + if ( pattern.charAt(0) == '+' + || pattern.charAt(0) == '-' ) + pattern = pattern.substring(1); + width = Integer.parseInt(pattern); + left = op != '-'; + if (subpattern.length > 1){ + maxPos = Integer.parseInt(subpattern[1]); + } + } + } + protected StringBuffer justify(String s, StringBuffer toAppendTo){ + int blanc = width - s.length(); + if ( left ){ + toAppendTo.append(s); + while(0 99999 && unitIndex < unit.length){ + size /= diviseur; + unitIndex++; + } + String result = size + unit[unitIndex]; + return result; + } + } + static protected class FreeMemoryArgument extends OctetArgument{ + public FreeMemoryArgument(){super();} + public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo){ + return justify(toReadableSize(Runtime.getRuntime().freeMemory(), + UNITE, diviseur), toAppendTo); + } + } + static protected class TotalMemoryArgument extends OctetArgument{ + public TotalMemoryArgument(){super();} + public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo){ + return justify(toReadableSize(Runtime.getRuntime().totalMemory(), + UNITE, diviseur), toAppendTo); + } + } + static protected class ThreadArgument extends SizedArgument{ + public ThreadArgument(){super();} + public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo){ + return justify(Thread.currentThread().getName(), toAppendTo); + } + } + static protected class PriorityLevelArgument extends SizedArgument{ + public PriorityLevelArgument(){super();} + public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo){ + return justify(record.getLevel().toString(), toAppendTo); + } + } + static protected class ClassNameArgument extends SubStringArgument{ + public ClassNameArgument(){super();} + public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo){ + return justify(substring(record.getSourceClassName()), toAppendTo); + } + } + static protected class MethodNameArgument extends SizedArgument{ + public MethodNameArgument(){super();} + public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo){ + return justify(record.getSourceMethodName(), toAppendTo); + } + } + static protected class MessageArgument extends SizedArgument{ + public MessageArgument(){super();} + public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo){ + return justify(record.getMessage(), toAppendTo); + } + } + +} // PatternFormatter