View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.boolex;
15  
16  import ch.qos.logback.classic.spi.ILoggingEvent;
17  import ch.qos.logback.core.boolex.EvaluationException;
18  import ch.qos.logback.core.boolex.EventEvaluatorBase;
19  import ch.qos.logback.core.util.FileUtil;
20  import groovy.lang.*;
21  import org.codehaus.groovy.control.CompilationFailedException;
22  
23  /**
24   * @author Ceki Gülcü
25   */
26  public class GEventEvaluator extends EventEvaluatorBase<ILoggingEvent> {
27  
28    String expression;
29  
30    IEvaluator delegateEvaluator;
31    Script script;
32  
33    public String getExpression() {
34      return expression;
35    }
36  
37    public void setExpression(String expression) {
38      this.expression = expression;
39    }
40  
41    public void start() {
42      int errors = 0;
43      if (expression == null || expression.length() == 0) {
44        addError("Empty expression");
45        return;
46      } else {
47        addInfo("Expression to evaluate [" + expression + "]");
48      }
49  
50  
51      ClassLoader classLoader = getClass().getClassLoader();
52      String currentPackageName = this.getClass().getPackage().getName();
53      currentPackageName = currentPackageName.replace('.', '/');
54  
55      String scriptText = FileUtil.resourceAsString(this, classLoader, currentPackageName + "/EvaluatorTemplate.groovy");
56      if (scriptText == null) {
57        return;
58      }
59  
60      // insert the expression into script text
61      scriptText = scriptText.replace("//EXPRESSION", expression);
62  
63      GroovyClassLoader gLoader = new GroovyClassLoader(classLoader);
64      try {
65        Class scriptClass = gLoader.parseClass(scriptText);
66  
67        GroovyObject goo = (GroovyObject) scriptClass.newInstance();
68        delegateEvaluator = (IEvaluator) goo;
69  
70      } catch (CompilationFailedException cfe) {
71        addError("Failed to compile expression [" + expression + "]", cfe);
72        errors++;
73      } catch (Exception e) {
74        addError("Failed to compile expression [" + expression + "]", e);
75        errors++;
76      }
77      if (errors == 0)
78        super.start();
79    }
80  
81    public boolean evaluate(ILoggingEvent event) throws NullPointerException, EvaluationException {
82      if (delegateEvaluator == null) {
83        return false;
84      }
85      return delegateEvaluator.doEvaluate(event);
86    }
87  
88  
89  }