summaryrefslogtreecommitdiffstats
path: root/branches/sca-java-integration/sca/kernel/core/src/main/java/org/apache/tuscany/core/monitor/JavaLoggingMonitorFactory.java
blob: 019dcbdcd373597e1e8d571e29751aed5b5b364c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */
package org.apache.tuscany.core.monitor;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import org.osoa.sca.annotations.Service;

import org.apache.tuscany.api.annotation.LogLevel;
import org.apache.tuscany.host.MonitorFactory;
import org.apache.tuscany.host.monitor.ExceptionFormatter;
import org.apache.tuscany.host.monitor.FormatterRegistry;

/**
 * A factory for monitors that forwards events to a {@link java.util.logging.Logger Java Logging (JSR47) Logger}.
 *
 * @version $Rev$ $Date$
 * @see java.util.logging
 */
@Service(interfaces = {MonitorFactory.class, FormatterRegistry.class})
public class JavaLoggingMonitorFactory implements MonitorFactory, FormatterRegistry {
    private String bundleName;
    private Level defaultLevel;
    private Map<String, Level> levels;
    private List<ExceptionFormatter> formatters = new ArrayList<ExceptionFormatter>();
    private ExceptionFormatter defaultFormatter = new DefaultExceptionFormatter();
    private Map<Class<?>, WeakReference<?>> proxies = new WeakHashMap<Class<?>, WeakReference<?>>();

    /**
     * Construct a MonitorFactory that will monitor the specified methods at the specified levels and generate messages
     * using java.util.logging.
     * <p/>
     * The supplied Properties can be used to specify custom log levels for specific monitor methods. The key should be
     * the method name in form returned by <code>Class.getName() + '#' + Method.getName()</code> and the value the log
     * level to use as defined by {@link java.util.logging.Level}.
     *
     * @param levels       definition of custom levels for specific monitored methods, may be null or empty.
     * @param defaultLevel the default log level to use
     * @param bundleName   the name of a resource bundle that will be passed to the logger
     * @see java.util.logging.Logger
     */
    public JavaLoggingMonitorFactory(Properties levels, Level defaultLevel, String bundleName) {
        Map<String, Object> configProperties = new HashMap<String, Object>();
        configProperties.put("levels", levels);
        configProperties.put("defaultLevel", defaultLevel);
        configProperties.put("bundleName", bundleName);
        initInternal(configProperties);
    }

    /**
     * Constructs a MonitorFactory that needs to be subsequently configured via a call to {@link #initialize}.
     */
    public JavaLoggingMonitorFactory() {
    }

    public void initialize(Map<String, Object> configProperties) {
        if (configProperties == null) {
            return;
        }
        initInternal(configProperties);
    }

    private void initInternal(Map<String, Object> configProperties) {
        try {
            this.defaultLevel = (Level) configProperties.get("defaultLevel");
            this.bundleName = (String) configProperties.get("bundleName");
            Properties levels = (Properties) configProperties.get("levels");

            this.levels = new HashMap<String, Level>();
            if (levels != null) {
                for (Map.Entry<Object, Object> entry : levels.entrySet()) {
                    String method = (String) entry.getKey();
                    String level = (String) entry.getValue();
                    try {
                        this.levels.put(method, Level.parse(level));
                    } catch (IllegalArgumentException e) {
                        throw new InvalidLevelException(method, level);
                    }
                }
            }
        } catch (ClassCastException cce) {
            throw new IllegalArgumentException(cce.getLocalizedMessage());
        }
    }

    public synchronized <T> T getMonitor(Class<T> monitorInterface) {
        T proxy = getCachedMonitor(monitorInterface);
        if (proxy == null) {
            proxy = createMonitor(monitorInterface, bundleName);
            proxies.put(monitorInterface, new WeakReference<T>(proxy));
        }
        return proxy;
    }

    private <T> T getCachedMonitor(Class<T> monitorInterface) {
        WeakReference<?> ref = proxies.get(monitorInterface);
        return (ref != null) ? monitorInterface.cast(ref.get()) : null;
    }

    private <T> T createMonitor(Class<T> monitorInterface, String bundleName) {
        String className = monitorInterface.getName();
        Logger logger = Logger.getLogger(className);
        Method[] methods = monitorInterface.getMethods();
        Map<String, Level> levels = new HashMap<String, Level>(methods.length);
        for (Method method : methods) {
            String key = className + '#' + method.getName();
            Level level = null;
            if (this.levels != null) {
                this.levels.get(key);
            }
            // if not specified the in config properties, look for an annotation on the method
            if (level == null) {
                LogLevel annotation = method.getAnnotation(LogLevel.class);
                if (annotation != null && annotation.value() != null) {
                    try {
                        level = Level.parse(annotation.value());
                    } catch (IllegalArgumentException e) {
                        // bad value, just use the default
                        level = defaultLevel;
                    }
                }
            }
            if (level == null) {
                level = defaultLevel;
            }
            levels.put(method.getName(), level);
        }

        ResourceBundle bundle = locateBundle(monitorInterface, bundleName);

        InvocationHandler handler = new LoggingHandler(logger, levels, bundle, formatters, defaultFormatter);
        return monitorInterface
            .cast(Proxy.newProxyInstance(monitorInterface.getClassLoader(), new Class<?>[]{monitorInterface}, handler));
    }

    private static <T> ResourceBundle locateBundle(Class<T> monitorInterface, String bundleName) {
        Locale locale = Locale.getDefault();
        ClassLoader cl = monitorInterface.getClassLoader();
        String packageName = monitorInterface.getPackage().getName();
        while (true) {
            try {
                return ResourceBundle.getBundle(packageName + '.' + bundleName, locale, cl);
            } catch (MissingResourceException e) {
                //ok
            }
            int index = packageName.lastIndexOf('.');
            if (index == -1) {
                break;
            }
            packageName = packageName.substring(0, index);
        }
        try {
            return ResourceBundle.getBundle(bundleName, locale, cl);
        } catch (Exception e) {
            return null;
        }
    }

    public void register(ExceptionFormatter formatter) {
        formatters.add(formatter);
    }

    public void unregister(ExceptionFormatter formatter) {
        formatters.remove(formatter);
    }

    private static final class LoggingHandler implements InvocationHandler {
        private final Logger logger;
        private final Map<String, Level> methodLevels;
        private final ResourceBundle bundle;
        private List<ExceptionFormatter> formatters;
        private ExceptionFormatter defaultFormatter;

        public LoggingHandler(Logger logger,
                              Map<String, Level> methodLevels,
                              ResourceBundle bundle,
                              List<ExceptionFormatter> formatters,
                              ExceptionFormatter defaultFormatter) {
            this.logger = logger;
            this.methodLevels = methodLevels;
            this.bundle = bundle;
            this.formatters = formatters;
            this.defaultFormatter = defaultFormatter;
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String sourceMethod = method.getName();
            Level level = methodLevels.get(sourceMethod);
            if (level != null && logger.isLoggable(level)) {
                // construct the key for the resource bundle
                String className = logger.getName();
                String key = className + '#' + sourceMethod;

                LogRecord logRecord = new LogRecord(level, key);
                logRecord.setLoggerName(className);
                logRecord.setSourceClassName(className);
                logRecord.setSourceMethodName(sourceMethod);
                logRecord.setParameters(args);
                if (args != null) {
                    for (Object o : args) {
                        if (o instanceof Throwable) {
                            Throwable e = (Throwable) o;
                            ExceptionFormatter formatter = null;
                            for (ExceptionFormatter candidate : formatters) {
                                if (candidate.canFormat(e.getClass())) {
                                    formatter = candidate;
                                    break;
                                }
                            }
                            StringWriter writer = new StringWriter();
                            PrintWriter pw = new PrintWriter(writer);
                            if (formatter != null) {
                                formatter.write(pw, e);
                            } else {
                                defaultFormatter.write(pw, e);
                            }
                            format(pw, e);
                            pw.close();
                            logRecord.setMessage(writer.toString());
                            break;
                        }
                    }
                }
                logRecord.setResourceBundle(bundle);
                logger.log(logRecord);
            }
            return null;
        }

        private void format(PrintWriter writer, Throwable throwable) {
            writer.println(throwable.getClass().getName());
            StackTraceElement[] trace = throwable.getStackTrace();
            for (StackTraceElement aTrace : trace) {
                writer.println("\tat " + aTrace);
            }
            Throwable ourCause = throwable.getCause();

            if (ourCause != null) {
                printStackTraceAsCause(writer, ourCause, trace);
            }
        }

        private void printStackTraceAsCause(PrintWriter pw,
                                            Throwable throwable,
                                            StackTraceElement[] causedTrace) {

            // Compute number of frames in common between this and caused
            StackTraceElement[] trace = throwable.getStackTrace();
            int m = trace.length - 1;
            int n = causedTrace.length - 1;
            while (m >= 0 && n >= 0 && trace[m].equals(causedTrace[n])) {
                m--;
                n--;
            }
            int framesInCommon = trace.length - 1 - m;

            pw.println("Caused by: " + throwable.getClass().getName());

            ExceptionFormatter formatter = null;
            for (ExceptionFormatter candidate : formatters) {
                if (candidate.canFormat(throwable.getClass())) {
                    formatter = candidate;
                    break;
                }
            }
            if (formatter != null) {
                formatter.write(pw, throwable);
            } else {
                defaultFormatter.write(pw, throwable);
            }


            for (int i = 0; i <= m; i++) {
                pw.println("\tat " + trace[i]);
            }
            if (framesInCommon != 0) {
                pw.println("\t... " + framesInCommon + " more");
            }

            // Recurse if we have a cause
            Throwable ourCause = throwable.getCause();
            if (ourCause != null) {
                printStackTraceAsCause(pw, ourCause, trace);
            }
        }

    }
}