01: /*
02: * Copyright 2007 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
05: * use this file except in compliance with the License. You may obtain a copy of
06: * 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, WITHOUT
12: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13: * License for the specific language governing permissions and limitations under
14: * the License.
15: */
16: package com.google.gwt.dev.util.log;
17:
18: import com.google.gwt.core.ext.TreeLogger;
19:
20: /**
21: * An internal implementation support class that creates a
22: * {@link com.google.gwt.server.internal.TreeLogger} that wraps another
23: * TreeLogger to allow for the underlying logger to be redirected per thread. It
24: * can be useful for situations where it is not practical to pass in a logger as
25: * a parameter, such as when interfacing with third-party classes.
26: */
27: public final class ThreadLocalTreeLoggerProxy implements TreeLogger {
28:
29: private static final ThreadLocal<TreeLogger> perThreadLogger = new ThreadLocal<TreeLogger>();
30:
31: public ThreadLocalTreeLoggerProxy() {
32: this (null);
33: }
34:
35: public ThreadLocalTreeLoggerProxy(TreeLogger logger) {
36: push(logger);
37: }
38:
39: /**
40: * Delegates the branch to the thread-local logger if one is present.
41: * Otherwise, the log entry is discarded and <code>this</code> is returned.
42: */
43: public TreeLogger branch(Type type, String msg, Throwable caught) {
44: TreeLogger logger = perThreadLogger.get();
45: if (logger != null) {
46: return logger.branch(type, msg, caught);
47: } else {
48: return this ;
49: }
50: }
51:
52: /**
53: * Delegates the check to the thread-local logger if one is present.
54: *
55: * @return relays the return value of the wrapped logger if one exists, or
56: * returns <code>false</code> otherwise
57: */
58: public boolean isLoggable(Type type) {
59: TreeLogger logger = perThreadLogger.get();
60: if (logger != null) {
61: return logger.isLoggable(type);
62: } else {
63: return false;
64: }
65: }
66:
67: /**
68: * Delegates the log to the thread-local logger if one is present. Otherwise,
69: * the log entry is discarded.
70: */
71: public void log(Type type, String msg, Throwable caught) {
72: TreeLogger logger = perThreadLogger.get();
73: if (logger != null) {
74: logger.log(type, msg, caught);
75: }
76: }
77:
78: public void pop(TreeLogger oldLogger) {
79: perThreadLogger.set(oldLogger);
80: }
81:
82: /**
83: * Sets the logger to which calls are redirected for the current thread.
84: */
85: public TreeLogger push(TreeLogger logger) {
86: TreeLogger old = perThreadLogger.get();
87: perThreadLogger.set(logger);
88: return old;
89: }
90: }
|