blob: 3eedcf6f3cb5735d47e899cb570202777bb93a2c [file] [log] [blame]
Marcel Offermansa962bc92009-11-21 17:59:33 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
Pierre De Ropf74a1162009-12-04 22:40:38 +000019package org.apache.felix.dm.impl;
Marcel Offermansa962bc92009-11-21 17:59:33 +000020
21import java.lang.reflect.InvocationTargetException;
22import java.lang.reflect.Method;
23
24import org.osgi.framework.BundleContext;
25import org.osgi.framework.BundleException;
26import org.osgi.framework.InvalidSyntaxException;
27import org.osgi.framework.ServiceEvent;
28import org.osgi.framework.ServiceListener;
29import org.osgi.framework.ServiceReference;
30
31/**
32 * This class mimics the standard OSGi <tt>LogService</tt> interface. An
33 * instance of this class is used by the dependency manager for all logging.
34 * By default this class logs messages to standard out. The log level can be set to
35 * control the amount of logging performed, where a higher number results in
36 * more logging. A log level of zero turns off logging completely.
37 *
38 * The log levels match those specified in the OSGi Log Service.
39 * This class also tracks log services and will use the highest ranking
40 * log service, if present, as a back end instead of printing to standard
41 * out. The class uses reflection to invoking the log service's method to
42 * avoid a dependency on the log interface. This class is in many ways similar
43 * to the one used in the system bundle for that same purpose.
44 *
45 * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
46 */
47public class Logger implements ServiceListener {
48 public static final int LOG_ERROR = 1;
49 public static final int LOG_WARNING = 2;
50 public static final int LOG_INFO = 3;
51 public static final int LOG_DEBUG = 4;
52
53 private final BundleContext m_context;
54
55 private final static int LOGGER_OBJECT_IDX = 0;
56 private final static int LOGGER_METHOD_IDX = 1;
57 private ServiceReference m_logRef = null;
58 private Object[] m_logger = null;
59
60 public Logger(BundleContext context) {
61 m_context = context;
62 startListeningForLogService();
63 }
64
65 public final void log(int level, String msg) {
66 _log(null, level, msg, null);
67 }
68
69 public final void log(int level, String msg, Throwable throwable) {
70 _log(null, level, msg, throwable);
71 }
72
73 public final void log(ServiceReference sr, int level, String msg) {
74 _log(sr, level, msg, null);
75 }
76
77 public final void log(ServiceReference sr, int level, String msg, Throwable throwable) {
78 _log(sr, level, msg, throwable);
79 }
80
81 protected void doLog(ServiceReference sr, int level, String msg, Throwable throwable) {
82 String s = (sr == null) ? null : "SvcRef " + sr;
83 s = (s == null) ? msg : s + " " + msg;
84 s = (throwable == null) ? s : s + " (" + throwable + ")";
85 switch (level) {
86 case LOG_DEBUG:
87 System.out.println("DEBUG: " + s);
88 break;
89 case LOG_ERROR:
90 System.out.println("ERROR: " + s);
91 if (throwable != null) {
92 if ((throwable instanceof BundleException) && (((BundleException) throwable).getNestedException() != null)) {
93 throwable = ((BundleException) throwable).getNestedException();
94 }
95 throwable.printStackTrace();
96 }
97 break;
98 case LOG_INFO:
99 System.out.println("INFO: " + s);
100 break;
101 case LOG_WARNING:
102 System.out.println("WARNING: " + s);
103 break;
104 default:
105 System.out.println("UNKNOWN[" + level + "]: " + s);
106 }
107 }
108
109 private void _log(ServiceReference sr, int level, String msg, Throwable throwable) {
110 // Save our own copy just in case it changes. We could try to do
111 // more conservative locking here, but let's be optimistic.
112 Object[] logger = m_logger;
113 // Use the log service if available.
114 if (logger != null) {
115 _logReflectively(logger, sr, level, msg, throwable);
116 }
117 // Otherwise, default logging action.
118 else {
119 doLog(sr, level, msg, throwable);
120 }
121 }
122
123 private void _logReflectively(Object[] logger, ServiceReference sr, int level, String msg, Throwable throwable) {
124 if (logger != null) {
125 Object[] params = { sr, new Integer(level), msg, throwable };
126 try {
127 ((Method) logger[LOGGER_METHOD_IDX]).invoke(logger[LOGGER_OBJECT_IDX], params);
128 }
129 catch (InvocationTargetException ex) {
130 System.err.println("Logger: " + ex);
131 }
132 catch (IllegalAccessException ex) {
133 System.err.println("Logger: " + ex);
134 }
135 }
136 }
137
138 /**
139 * This method is called when the bundle context is set;
140 * it simply adds a service listener so that the bundle can track
141 * log services to be used as the back end of the logging mechanism. It also
142 * attempts to get an existing log service, if present, but in general
143 * there will never be a log service present since the system bundle is
144 * started before every other bundle.
145 */
146 private synchronized void startListeningForLogService() {
147 // Add a service listener for log services.
148 try {
149 m_context.addServiceListener(this, "(objectClass=org.osgi.service.log.LogService)");
150 }
151 catch (InvalidSyntaxException ex) {
152 // This will never happen since the filter is hard coded.
153 }
154 // Try to get an existing log service.
155 m_logRef = m_context.getServiceReference("org.osgi.service.log.LogService");
156 // Get the service object if available and set it in the logger.
157 if (m_logRef != null) {
158 setLogger(m_context.getService(m_logRef));
159 }
160 }
161
162 /**
163 * This method implements the callback for the ServiceListener interface.
164 * It is public as a byproduct of implementing the interface and should
165 * not be called directly. This method tracks run-time changes to log
166 * service availability. If the log service being used by the framework's
167 * logging mechanism goes away, then this will try to find an alternative.
168 * If a higher ranking log service is registered, then this will switch
169 * to the higher ranking log service.
170 */
171 public final synchronized void serviceChanged(ServiceEvent event) {
172 // If no logger is in use, then grab this one.
173 if ((event.getType() == ServiceEvent.REGISTERED) && (m_logRef == null)) {
174 m_logRef = event.getServiceReference();
175 // Get the service object and set it in the logger.
176 setLogger(m_context.getService(m_logRef));
177 }
178 // If a logger is in use, but this one has a higher ranking, then swap
179 // it for the existing logger.
180 else if ((event.getType() == ServiceEvent.REGISTERED) && (m_logRef != null)) {
181 ServiceReference ref = m_context.getServiceReference("org.osgi.service.log.LogService");
182 if (!ref.equals(m_logRef)) {
183 m_context.ungetService(m_logRef);
184 m_logRef = ref;
185 setLogger(m_context.getService(m_logRef));
186 }
187 }
188 // If the current logger is going away, release it and try to
189 // find another one.
190 else if ((event.getType() == ServiceEvent.UNREGISTERING) && m_logRef.equals(event.getServiceReference())) {
191 // Unget the service object.
192 m_context.ungetService(m_logRef);
193 // Try to get an existing log service.
194 m_logRef = m_context.getServiceReference("org.osgi.service.log.LogService");
195 // Get the service object if available and set it in the logger.
196 if (m_logRef != null) {
197 setLogger(m_context.getService(m_logRef));
198 }
199 else {
200 setLogger(null);
201 }
202 }
203 }
204
205 /**
206 * This method sets the new log service object. It also caches the method to
207 * invoke. The service object and method are stored in array to optimistically
208 * eliminate the need to locking when logging.
209 */
210 private void setLogger(Object logObj) {
211 if (logObj == null) {
212 m_logger = null;
213 }
214 else {
215 Class[] formalParams = { ServiceReference.class, Integer.TYPE, String.class, Throwable.class };
216 try {
217 Method logMethod = logObj.getClass().getMethod("log", formalParams);
218 logMethod.setAccessible(true);
219 m_logger = new Object[] { logObj, logMethod };
220 }
221 catch (NoSuchMethodException ex) {
222 System.err.println("Logger: " + ex);
223 m_logger = null;
224 }
225 }
226 }
227}