GriffonApplicationEventAppender.java
01 /*
02  * Copyright 2009-2012 the original author or authors.
03  *
04  * Licensed under the Apache License, Version 2.0 (the "License");
05  * you may not use this file except in compliance with the License.
06  * You may obtain a copy of the License at
07  *
08  *      http://www.apache.org/licenses/LICENSE-2.0
09  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.codehaus.griffon.runtime.logging;
17 
18 import griffon.core.GriffonApplication;
19 import griffon.util.ApplicationHolder;
20 import org.apache.log4j.AppenderSkeleton;
21 import org.apache.log4j.Layout;
22 import org.apache.log4j.Level;
23 import org.apache.log4j.spi.LoggingEvent;
24 import org.apache.log4j.spi.ThrowableInformation;
25 
26 import java.util.Arrays;
27 
28 
29 /**
30  * A Log4j Appender that triggers Griffon application events.
31  *
32  @author Andres Almiray
33  @since 0.9.3
34  */
35 public class GriffonApplicationEventAppender extends AppenderSkeleton {
36     private static final String EVENT_NAME = "LogEvent";
37 
38     public GriffonApplicationEventAppender(Layout layout) {
39         this.layout = layout;
40     }
41 
42     @Override
43     protected void append(LoggingEvent event) {
44         Throwable throwable = null;
45         ThrowableInformation throwableInfo = event.getThrowableInformation();
46         if (throwableInfo != null) {
47             throwable = throwableInfo.getThrowable();
48         }
49         fireApplicationEvent(event.getLevel(), asString(event), throwable);
50     }
51 
52     private String asString(LoggingEvent event) {
53         StringBuilder builder = new StringBuilder(layout.format(event));
54 
55         if (layout.ignoresThrowable()) {
56             String[] s = event.getThrowableStrRep();
57             if (s != null) {
58                 int len = s.length;
59                 for (int i = 0; i < len; i++) {
60                     builder.append(s[i]);
61                     builder.append(Layout.LINE_SEP);
62                 }
63             }
64         }
65 
66         return builder.toString();
67     }
68 
69     public void close() {
70     }
71 
72     public boolean requiresLayout() {
73         return true;
74     }
75 
76     private void fireApplicationEvent(Level level, String message, Throwable throwable) {
77         GriffonApplication app = ApplicationHolder.getApplication();
78         if (app != null) {
79             app.eventAsync(EVENT_NAME, Arrays.asList(level.toString(), message, throwable));
80         }
81     }
82 }