01: package org.jzonic.jlo.formatter.tokens;
02:
03: import org.jzonic.jlo.LogRecord;
04: import org.jzonic.jlo.error.ErrorHandler;
05: import gnu.regexp.RE;
06: import gnu.regexp.REMatch;
07:
08: import java.util.Map;
09: import java.util.HashMap;
10:
11: /**
12: * User: Mecky
13: * Date: 19.07.2005
14: * Time: 12:20:09
15: */
16: public class TokenParser {
17:
18: private static Map tokens = new HashMap();
19: static {
20: tokens.put("text", new TextToken());
21: tokens.put("class", new ClassToken());
22: tokens.put("shortclass", new ShortClassToken());
23: tokens.put("target", new TargetToken());
24: tokens.put("date", new DateToken());
25: tokens.put("ndc", new NDCToken());
26: tokens.put("elapsed", new TimeTrackerToken());
27: }
28:
29: public String parseLine(LogRecord lr, String format) {
30: String ret = format;
31: try {
32: String expression = "\\$\\{([^\\}]+)\\}";
33: RE re = new RE(expression);
34: REMatch[] matches = re.getAllMatches(format);
35: for (int i = 0; i < matches.length; i++) {
36: String token = matches[i].toString(1);
37: String placeHolder = matches[i].toString(1);
38: String txt = null;
39: if (token.startsWith("${")) {
40: token = token.substring(2);
41: }
42: if (token.endsWith("}")) {
43: token = token.substring(0, token.length() - 1);
44: }
45: if (token.indexOf(":") != -1) {
46: token = token.substring(0, token.indexOf(":"));
47: txt = placeHolder.substring(placeHolder
48: .indexOf(":") + 1);
49: txt = txt.substring(0, txt.length());
50: }
51: String match = null;
52: if (tokens.containsKey(token)) {
53: FormatterToken ft = (FormatterToken) tokens
54: .get(token);
55: if (txt != null) {
56: ft.setParameterString(txt);
57: }
58: match = ft.format(lr);
59: }
60: if (match != null) {
61: ret = re.substitute(ret, match);
62: }
63: }
64: return ret;
65: } catch (Exception e) {
66: ErrorHandler.reportError(
67: "Error while formatting logrecord", e);
68: }
69: return ret;
70: }
71: }
|