001 package com.saelist.util;
002
003 import java.io.*;
004 import java.util.*;
005 import org.apache.log4j.*;
006 import com.saelist.stx.*;
007 import com.saelist.stx.parser.*;
008
009 // Warning: creates circular dependancy between stx and util.
010 // Logging uses stx uses Strings.
011
012 public class Logging {
013
014 private static Logger logger = Logger.getLogger(Logging.class);
015
016 public static void setLogLevels(String filename) throws IOException {
017 Pair logConfig = LstxParser.parse(Strings.loadFile(filename));
018 LstxParser.applyBasicProfile(logConfig);
019 for(Iterator levels = logConfig.select("//*[starts-with(., '-')"); levels.hasNext(); ) {
020 Pair level = (Pair) levels.next();
021 Level logLevel = toLevel(level.getText().substring(1));
022 getLogger(pathOf(level.getParent(), ".")).setLevel(logLevel);
023 logger.info("setLogLevel(): " + pathOf(level.getParent(), ".") + "=" + level.getText().substring(1));
024 }
025 }
026
027 private static Logger getLogger(String name) {
028 if("".equals(name))
029 return Logger.getRootLogger();
030 return Logger.getLogger(name);
031 }
032
033 /** Returns the path of the pair e.g. "a.b.c" for the pair c in a[ b[ c ] ].
034 @throws NullPointerException if pair is null. */
035 private static String pathOf(Pair pair, String pathsep) {
036 if(pair == null || "root".equals(pair.getText()))
037 return "";
038 if(pair.getParent() == null || "root".equals(pair.getParent().getText()))
039 return pair.getText();
040 return pathOf(pair.getParent(), pathsep) + pathsep + pair.getText();
041 }
042
043
044 public static Level toLevel(String level) {
045 if(level.equals("fatal")) return Level.FATAL;
046 if(level.equals("error")) return Level.ERROR;
047 if(level.equals("warn")) return Level.WARN;
048 if(level.equals("info")) return Level.INFO;
049 if(level.equals("debug")) return Level.DEBUG;
050 if(level.equals("all")) return Level.ALL;
051 throw new RuntimeException("Invalid level '" + level + "'.");
052 }
053
054 }