2 * Copyright (C) 2007-2012 Argeo GmbH
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org
.argeo
.cms
.internal
.kernel
;
18 import java
.io
.IOException
;
19 import java
.nio
.file
.FileSystems
;
20 import java
.nio
.file
.Path
;
21 import java
.nio
.file
.Paths
;
22 import java
.nio
.file
.StandardWatchEventKinds
;
23 import java
.nio
.file
.WatchEvent
;
24 import java
.nio
.file
.WatchKey
;
25 import java
.nio
.file
.WatchService
;
26 import java
.security
.SignatureException
;
27 import java
.util
.ArrayList
;
28 import java
.util
.Collections
;
29 import java
.util
.Enumeration
;
30 import java
.util
.HashMap
;
31 import java
.util
.Iterator
;
32 import java
.util
.LinkedList
;
33 import java
.util
.List
;
34 import java
.util
.ListIterator
;
36 import java
.util
.Properties
;
37 import java
.util
.concurrent
.BlockingQueue
;
38 import java
.util
.concurrent
.LinkedBlockingQueue
;
40 import org
.apache
.commons
.logging
.Log
;
41 import org
.apache
.commons
.logging
.LogFactory
;
42 import org
.apache
.log4j
.AppenderSkeleton
;
43 import org
.apache
.log4j
.Level
;
44 import org
.apache
.log4j
.LogManager
;
45 import org
.apache
.log4j
.Logger
;
46 import org
.apache
.log4j
.PropertyConfigurator
;
47 import org
.apache
.log4j
.spi
.LoggingEvent
;
48 import org
.argeo
.cms
.CmsException
;
49 import org
.argeo
.cms
.auth
.CurrentUser
;
50 import org
.argeo
.node
.ArgeoLogListener
;
51 import org
.argeo
.node
.ArgeoLogger
;
52 import org
.argeo
.node
.NodeConstants
;
53 import org
.argeo
.osgi
.useradmin
.UserAdminConf
;
54 import org
.osgi
.framework
.Constants
;
55 import org
.osgi
.framework
.ServiceReference
;
56 import org
.osgi
.service
.cm
.ConfigurationAdmin
;
57 import org
.osgi
.service
.log
.LogEntry
;
58 import org
.osgi
.service
.log
.LogListener
;
59 import org
.osgi
.service
.log
.LogReaderService
;
60 import org
.osgi
.service
.log
.LogService
;
62 /** Not meant to be used directly in standard log4j config */
63 class NodeLogger
implements ArgeoLogger
, LogListener
{
64 /** Internal debug for development purposes. */
65 private static Boolean debug
= false;
67 // private final static Log log = LogFactory.getLog(NodeLogger.class);
69 private Boolean disabled
= false;
71 private String level
= null;
73 private Level log4jLevel
= null;
74 // private Layout layout;
76 private Properties configuration
;
78 private AppenderImpl appender
;
80 private final List
<ArgeoLogListener
> everythingListeners
= Collections
81 .synchronizedList(new ArrayList
<ArgeoLogListener
>());
82 private final List
<ArgeoLogListener
> allUsersListeners
= Collections
83 .synchronizedList(new ArrayList
<ArgeoLogListener
>());
84 private final Map
<String
, List
<ArgeoLogListener
>> userListeners
= Collections
85 .synchronizedMap(new HashMap
<String
, List
<ArgeoLogListener
>>());
87 private BlockingQueue
<LogEvent
> events
;
88 private LogDispatcherThread logDispatcherThread
= new LogDispatcherThread();
90 private Integer maxLastEventsCount
= 10 * 1000;
92 /** Marker to prevent stack overflow */
93 private ThreadLocal
<Boolean
> dispatching
= new ThreadLocal
<Boolean
>() {
96 protected Boolean
initialValue() {
101 @SuppressWarnings("unchecked")
102 public NodeLogger(LogReaderService lrs
) {
103 Enumeration
<LogEntry
> logEntries
= lrs
.getLog();
104 while (logEntries
.hasMoreElements())
105 logged(logEntries
.nextElement());
106 lrs
.addLogListener(this);
108 // configure log4j watcher
109 String log4jConfiguration
= KernelUtils
.getFrameworkProp("log4j.configuration");
110 if (log4jConfiguration
!= null && log4jConfiguration
.startsWith("file:")) {
111 if (log4jConfiguration
.contains("..")) {
112 if (log4jConfiguration
.startsWith("file://"))
113 log4jConfiguration
= log4jConfiguration
.substring("file://".length());
114 else if (log4jConfiguration
.startsWith("file:"))
115 log4jConfiguration
= log4jConfiguration
.substring("file:".length());
118 Path log4jconfigPath
= Paths
.get(log4jConfiguration
);
119 Thread log4jConfWatcher
= new Log4jConfWatcherThread(log4jconfigPath
);
120 log4jConfWatcher
.start();
121 } catch (Exception e
) {
122 stdErr("Badly formatted log4j configuration URI " + log4jConfiguration
+ ": " + e
.getMessage());
129 events
= new LinkedBlockingQueue
<LogEvent
>();
131 // if (layout != null)
132 // setLayout(layout);
134 // setLayout(new PatternLayout(pattern));
135 appender
= new AppenderImpl();
136 reloadConfiguration();
137 Logger
.getRootLogger().addAppender(appender
);
139 logDispatcherThread
= new LogDispatcherThread();
140 logDispatcherThread
.start();
141 } catch (Exception e
) {
142 throw new CmsException("Cannot initialize log4j");
146 public void destroy() throws Exception
{
147 Logger
.getRootLogger().removeAppender(appender
);
148 allUsersListeners
.clear();
149 for (List
<ArgeoLogListener
> lst
: userListeners
.values())
151 userListeners
.clear();
155 logDispatcherThread
.interrupt();
158 // public void setLayout(Layout layout) {
159 // this.layout = layout;
162 public String
toString() {
163 return "Node Logger";
170 public void logged(LogEntry status
) {
171 Log pluginLog
= LogFactory
.getLog(status
.getBundle().getSymbolicName());
172 Integer severity
= status
.getLevel();
173 if (severity
== LogService
.LOG_ERROR
) {
174 // FIXME Fix Argeo TP
175 if (status
.getException() instanceof SignatureException
)
177 pluginLog
.error(msg(status
), status
.getException());
178 } else if (severity
== LogService
.LOG_WARNING
)
179 pluginLog
.warn(msg(status
), status
.getException());
180 else if (severity
== LogService
.LOG_INFO
&& pluginLog
.isDebugEnabled())
181 pluginLog
.debug(msg(status
), status
.getException());
182 else if (severity
== LogService
.LOG_DEBUG
&& pluginLog
.isTraceEnabled())
183 pluginLog
.trace(msg(status
), status
.getException());
186 private String
msg(LogEntry status
) {
187 StringBuilder sb
= new StringBuilder();
188 sb
.append(status
.getMessage());
189 ServiceReference
<?
> sr
= status
.getServiceReference();
192 String
[] objectClasses
= (String
[]) sr
.getProperty(Constants
.OBJECTCLASS
);
193 if (isSpringApplicationContext(objectClasses
)) {
194 sb
.append("{org.springframework.context.ApplicationContext}");
195 Object symbolicName
= sr
.getProperty(Constants
.BUNDLE_SYMBOLICNAME
);
196 if (symbolicName
!= null)
197 sb
.append(" " + Constants
.BUNDLE_SYMBOLICNAME
+ ": " + symbolicName
);
199 sb
.append(arrayToString(objectClasses
));
201 Object cn
= sr
.getProperty(NodeConstants
.CN
);
203 sb
.append(" " + NodeConstants
.CN
+ ": " + cn
);
204 Object factoryPid
= sr
.getProperty(ConfigurationAdmin
.SERVICE_FACTORYPID
);
205 if (factoryPid
!= null)
206 sb
.append(" " + ConfigurationAdmin
.SERVICE_FACTORYPID
+ ": " + factoryPid
);
208 // Object servicePid = sr.getProperty(Constants.SERVICE_PID);
209 // if (servicePid != null)
210 // sb.append(" " + Constants.SERVICE_PID + ": " + servicePid);
213 Object whiteBoardPattern
= sr
.getProperty(KernelConstants
.WHITEBOARD_PATTERN_PROP
);
214 if (whiteBoardPattern
!= null) {
215 if (whiteBoardPattern
instanceof String
) {
216 sb
.append(" " + KernelConstants
.WHITEBOARD_PATTERN_PROP
+ ": " + whiteBoardPattern
);
218 sb
.append(" " + KernelConstants
.WHITEBOARD_PATTERN_PROP
+ ": "
219 + arrayToString((String
[]) whiteBoardPattern
));
223 Object contextName
= sr
.getProperty(KernelConstants
.CONTEXT_NAME_PROP
);
224 if (contextName
!= null)
225 sb
.append(" " + KernelConstants
.CONTEXT_NAME_PROP
+ ": " + contextName
);
228 Object baseDn
= sr
.getProperty(UserAdminConf
.baseDn
.name());
230 sb
.append(" " + UserAdminConf
.baseDn
.name() + ": " + baseDn
);
233 return sb
.toString();
236 private String
arrayToString(Object
[] arr
) {
237 StringBuilder sb
= new StringBuilder();
239 for (int i
= 0; i
< arr
.length
; i
++) {
245 return sb
.toString();
248 private boolean isSpringApplicationContext(String
[] objectClasses
) {
249 for (String clss
: objectClasses
) {
250 if (clss
.equals("org.eclipse.gemini.blueprint.context.DelegatedExecutionOsgiBundleApplicationContext")) {
261 public synchronized void register(ArgeoLogListener listener
, Integer numberOfPreviousEvents
) {
262 String username
= CurrentUser
.getUsername();
263 if (username
== null)
264 throw new CmsException("Only authenticated users can register a log listener");
266 if (!userListeners
.containsKey(username
)) {
267 List
<ArgeoLogListener
> lst
= Collections
.synchronizedList(new ArrayList
<ArgeoLogListener
>());
268 userListeners
.put(username
, lst
);
270 userListeners
.get(username
).add(listener
);
271 List
<LogEvent
> lastEvents
= logDispatcherThread
.getLastEvents(username
, numberOfPreviousEvents
);
272 for (LogEvent evt
: lastEvents
)
273 dispatchEvent(listener
, evt
);
276 public synchronized void registerForAll(ArgeoLogListener listener
, Integer numberOfPreviousEvents
,
277 boolean everything
) {
279 everythingListeners
.add(listener
);
281 allUsersListeners
.add(listener
);
282 List
<LogEvent
> lastEvents
= logDispatcherThread
.getLastEvents(null, numberOfPreviousEvents
);
283 for (LogEvent evt
: lastEvents
)
284 if (everything
|| evt
.getUsername() != null)
285 dispatchEvent(listener
, evt
);
288 public synchronized void unregister(ArgeoLogListener listener
) {
289 String username
= CurrentUser
.getUsername();
290 if (username
== null)// FIXME
292 if (!userListeners
.containsKey(username
))
293 throw new CmsException("No user listeners " + listener
+ " registered for user " + username
);
294 if (!userListeners
.get(username
).contains(listener
))
295 throw new CmsException("No user listeners " + listener
+ " registered for user " + username
);
296 userListeners
.get(username
).remove(listener
);
297 if (userListeners
.get(username
).isEmpty())
298 userListeners
.remove(username
);
302 public synchronized void unregisterForAll(ArgeoLogListener listener
) {
303 everythingListeners
.remove(listener
);
304 allUsersListeners
.remove(listener
);
307 /** For development purpose, since using regular logging is not easy here */
308 private static void stdOut(Object obj
) {
309 System
.out
.println(obj
);
312 private static void stdErr(Object obj
) {
313 System
.err
.println(obj
);
316 private static void debug(Object obj
) {
318 System
.out
.println(obj
);
321 private static boolean isInternalDebugEnabled() {
325 // public void setPattern(String pattern) {
326 // this.pattern = pattern;
329 public void setDisabled(Boolean disabled
) {
330 this.disabled
= disabled
;
333 public void setLevel(String level
) {
337 public void setConfiguration(Properties configuration
) {
338 this.configuration
= configuration
;
341 public void updateConfiguration(Properties configuration
) {
342 setConfiguration(configuration
);
343 reloadConfiguration();
346 public Properties
getConfiguration() {
347 return configuration
;
351 * Reloads configuration (if the configuration {@link Properties} is set)
353 protected void reloadConfiguration() {
354 if (configuration
!= null) {
355 LogManager
.resetConfiguration();
356 PropertyConfigurator
.configure(configuration
);
360 protected synchronized void processLoggingEvent(LogEvent event
) {
364 if (dispatching
.get())
367 if (level
!= null && !level
.trim().equals("")) {
368 if (log4jLevel
== null || !log4jLevel
.toString().equals(level
))
370 log4jLevel
= Level
.toLevel(level
);
371 } catch (Exception e
) {
372 System
.err
.println("Log4j level could not be set for level '" + level
+ "', resetting it to null.");
377 if (log4jLevel
!= null && !event
.getLoggingEvent().getLevel().isGreaterOrEqual(log4jLevel
)) {
384 Iterator
<ArgeoLogListener
> everythingIt
= everythingListeners
.iterator();
385 while (everythingIt
.hasNext())
386 dispatchEvent(everythingIt
.next(), event
);
388 if (event
.getUsername() != null) {
389 Iterator
<ArgeoLogListener
> allUsersIt
= allUsersListeners
.iterator();
390 while (allUsersIt
.hasNext())
391 dispatchEvent(allUsersIt
.next(), event
);
393 if (userListeners
.containsKey(event
.getUsername())) {
394 Iterator
<ArgeoLogListener
> userIt
= userListeners
.get(event
.getUsername()).iterator();
395 while (userIt
.hasNext())
396 dispatchEvent(userIt
.next(), event
);
399 } catch (Exception e
) {
400 stdOut("Cannot process logging event");
405 protected void dispatchEvent(ArgeoLogListener logListener
, LogEvent evt
) {
406 LoggingEvent event
= evt
.getLoggingEvent();
407 logListener
.appendLog(evt
.getUsername(), event
.getTimeStamp(), event
.getLevel().toString(),
408 event
.getLoggerName(), event
.getThreadName(), event
.getMessage(), event
.getThrowableStrRep());
411 private class AppenderImpl
extends AppenderSkeleton
{
412 public boolean requiresLayout() {
416 public void close() {
420 protected void append(LoggingEvent event
) {
421 if (events
!= null) {
423 String username
= CurrentUser
.getUsername();
424 events
.put(new LogEvent(username
, event
));
425 } catch (InterruptedException e
) {
433 private class LogDispatcherThread
extends Thread
{
434 /** encapsulated in order to simplify concurrency management */
435 private LinkedList
<LogEvent
> lastEvents
= new LinkedList
<LogEvent
>();
437 public LogDispatcherThread() {
438 super("Argeo Logging Dispatcher Thread");
442 while (events
!= null) {
444 LogEvent loggingEvent
= events
.take();
445 processLoggingEvent(loggingEvent
);
446 addLastEvent(loggingEvent
);
447 } catch (InterruptedException e
) {
454 protected synchronized void addLastEvent(LogEvent loggingEvent
) {
455 if (lastEvents
.size() >= maxLastEventsCount
)
457 lastEvents
.add(loggingEvent
);
460 public synchronized List
<LogEvent
> getLastEvents(String username
, Integer maxCount
) {
461 LinkedList
<LogEvent
> evts
= new LinkedList
<LogEvent
>();
462 ListIterator
<LogEvent
> it
= lastEvents
.listIterator(lastEvents
.size());
464 while (it
.hasPrevious() && (count
< maxCount
)) {
465 LogEvent evt
= it
.previous();
466 if (username
== null || username
.equals(evt
.getUsername())) {
475 private class LogEvent
{
476 private final String username
;
477 private final LoggingEvent loggingEvent
;
479 public LogEvent(String username
, LoggingEvent loggingEvent
) {
481 this.username
= username
;
482 this.loggingEvent
= loggingEvent
;
486 public int hashCode() {
487 return loggingEvent
.hashCode();
491 public boolean equals(Object obj
) {
492 return loggingEvent
.equals(obj
);
496 public String
toString() {
497 return username
+ "@ " + loggingEvent
.toString();
500 public String
getUsername() {
504 public LoggingEvent
getLoggingEvent() {
510 private class Log4jConfWatcherThread
extends Thread
{
511 private Path log4jConfigurationPath
;
513 public Log4jConfWatcherThread(Path log4jConfigurationPath
) {
514 super("Log4j Configuration Watcher");
516 this.log4jConfigurationPath
= log4jConfigurationPath
.toRealPath();
517 } catch (IOException e
) {
518 this.log4jConfigurationPath
= log4jConfigurationPath
.toAbsolutePath();
519 stdOut("Cannot determine real path for " + log4jConfigurationPath
+ ": " + e
.getMessage());
524 Path parentDir
= log4jConfigurationPath
.getParent();
525 try (final WatchService watchService
= FileSystems
.getDefault().newWatchService()) {
526 parentDir
.register(watchService
, StandardWatchEventKinds
.ENTRY_MODIFY
);
528 watching
: while ((wk
= watchService
.take()) != null) {
529 for (WatchEvent
<?
> event
: wk
.pollEvents()) {
530 final Path changed
= (Path
) event
.context();
531 if (log4jConfigurationPath
.equals(parentDir
.resolve(changed
))) {
532 if (isInternalDebugEnabled())
533 debug(log4jConfigurationPath
+ " has changed, reloading.");
534 PropertyConfigurator
.configure(log4jConfigurationPath
.toUri().toURL());
538 boolean valid
= wk
.reset();
543 } catch (IOException
| InterruptedException e
) {
544 stdErr("Log4j configuration watcher failed: " + e
.getMessage());