Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: aa1426beac83e8e04ea953d7069c45f5c0c8ddd8 (plain) (blame)
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*******************************************************************************
s
s This
 * program and the accompanying materials are made available under the terms of
 * the Eclipse Public License 2.0 which accompanies this distribution, and is
 * available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 * 
 * Contributors: IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.equinox.log.test;

import java.io.File;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.equinox.log.ExtendedLogEntry;
import org.eclipse.equinox.log.SynchronousLogListener;
import org.eclipse.osgi.container.Module;
import org.eclipse.osgi.container.ModuleContainerAdaptor.ContainerEvent;
import org.eclipse.osgi.internal.framework.EquinoxConfiguration;
import org.eclipse.osgi.launch.Equinox;
import org.eclipse.osgi.tests.OSGiTestsActivator;
import org.eclipse.osgi.tests.bundles.AbstractBundleTests;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.log.LogEntry;
import org.osgi.service.log.LogLevel;
import org.osgi.service.log.LogListener;
import org.osgi.service.log.LogReaderService;
import org.osgi.service.log.LogService;
import org.osgi.service.log.Logger;
import org.osgi.service.log.admin.LoggerAdmin;
import org.osgi.service.log.admin.LoggerContext;

public class LogReaderServiceTest extends AbstractBundleTests {

	private LogService log;
	private ServiceReference logReference;
	private LogReaderService reader;
	private ServiceReference readerReference;
	private ServiceReference<LoggerAdmin> loggerAdminReference;
	private LoggerAdmin loggerAdmin;
	LoggerContext rootLoggerContext;
	Map<String, LogLevel> rootLogLevels;

	public LogReaderServiceTest(String name) {
		setName(name);
	}

	protected void setUp() throws Exception {
		super.setUp();
		logReference = OSGiTestsActivator.getContext().getServiceReference(LogService.class.getName());
		readerReference = OSGiTestsActivator.getContext().getServiceReference(LogReaderService.class.getName());
		loggerAdminReference = OSGiTestsActivator.getContext().getServiceReference(LoggerAdmin.class);

		log = (LogService) OSGiTestsActivator.getContext().getService(logReference);
		reader = (LogReaderService) OSGiTestsActivator.getContext().getService(readerReference);
		loggerAdmin = OSGiTestsActivator.getContext().getService(loggerAdminReference);

		rootLoggerContext = loggerAdmin.getLoggerContext(null);
		rootLogLevels = rootLoggerContext.getLogLevels();

		Map<String, LogLevel> copyLogLevels = new HashMap<String, LogLevel>(rootLogLevels);
		copyLogLevels.put(Logger.ROOT_LOGGER_NAME, LogLevel.TRACE);
		rootLoggerContext.setLogLevels(copyLogLevels);
	}

	protected void tearDown() throws Exception {
		rootLoggerContext.setLogLevels(rootLogLevels);
		OSGiTestsActivator.getContext().ungetService(loggerAdminReference);
		OSGiTestsActivator.getContext().ungetService(logReference);
		OSGiTestsActivator.getContext().ungetService(readerReference);
		super.tearDown();
	}

	public void testaddListener() throws Exception {
		TestListener listener = new TestListener();
		reader.addLogListener(listener);
		synchronized (listener) {
			log.log(LogService.LOG_INFO, "info"); //$NON-NLS-1$
			listener.waitForLogEntry();
		}
		assertTrue(listener.getEntryX().getLevel() == LogService.LOG_INFO);
	}

	public void testaddListenerTwice() throws Exception {
		TestListener listener = new TestListener();
		reader.addLogListener(listener);
		reader.addLogListener(listener);
		synchronized (listener) {
			log.log(LogService.LOG_INFO, "info"); //$NON-NLS-1$
			listener.waitForLogEntry();
		}
		assertTrue(listener.getEntryX().getLevel() == LogService.LOG_INFO);
	}

	public void testaddNullListener() throws Exception {
		try {
			reader.addLogListener(null);
		} catch (IllegalArgumentException t) {
			return;
		}
		fail();
	}

	public void testBadListener() throws Exception {
		LogListener listener = new LogListener() {
			public synchronized void logged(LogEntry entry) {
				notifyAll();
				throw new RuntimeException("Expected error for testBadListener."); //$NON-NLS-1$
			}
		};
		reader.addLogListener(listener);

		synchronized (listener) {
			log.log(LogService.LOG_INFO, "info"); //$NON-NLS-1$
			listener.wait();
		}
	}

	public void testLogEntry() throws Exception {
		TestListener listener = new TestListener();
		reader.addLogListener(listener);
		long timeBeforeLog = System.currentTimeMillis();
		synchronized (listener) {
			log.log(logReference, LogService.LOG_INFO, "info", new Throwable("test")); //$NON-NLS-1$ //$NON-NLS-2$
			listener.waitForLogEntry();
		}
		LogEntry entry = listener.getEntryX();
		assertTrue(entry.getBundle() == OSGiTestsActivator.getContext().getBundle());
		assertTrue(entry.getMessage().equals("info")); //$NON-NLS-1$
		assertTrue(entry.getException().getMessage().equals("test")); //$NON-NLS-1$
		assertTrue(entry.getServiceReference() == logReference);
		assertTrue(entry.getTime() >= timeBeforeLog);
		assertTrue(entry.getLevel() == LogService.LOG_INFO);
	}

	public void testLogBundleEventInfo() throws Exception {
		// this is just a bundle that is harmless to start/stop
		Bundle testBundle = installer.installBundle("test.logging.a"); //$NON-NLS-1$
		TestListener listener = new TestListener(testBundle);
		reader.addLogListener(listener);
		synchronized (listener) {
			testBundle.start();
			listener.waitForLogEntry();
		}

		ExtendedLogEntry entry = listener.getEntryX();
		assertTrue(entry.getLevel() == LogService.LOG_INFO);
		assertEquals("Wrong level.", LogLevel.INFO, entry.getLogLevel());
		assertTrue("Wrong context: " + entry.getContext(), entry.getContext() instanceof BundleEvent);
	}

	public void testLogBundleEventSynchronous() throws Exception {
		// this is just a bundle that is harmless to start/stop
		final Bundle testBundle = installer.installBundle("test.logging.a"); //$NON-NLS-1$
		final AtomicReference<Thread> logThread = new AtomicReference<>();
		LogListener listener = new SynchronousLogListener() {
			@Override
			public void logged(LogEntry entry) {
				if (entry.getBundle() == testBundle) {
					logThread.compareAndSet(null, Thread.currentThread());
				}
			}
		};
		reader.addLogListener(listener);
		testBundle.start();

		assertEquals("Wrong thread for synchronous bundle event logs.", Thread.currentThread(), logThread.get());

	}

	public void testLogServiceEventInfo() throws Exception {
		TestListener listener = new TestListener();
		reader.addLogListener(listener);
		synchronized (listener) {
			OSGiTestsActivator.getContext().registerService(Object.class.getName(), new Object(), null);
			listener.waitForLogEntry();
		}
		ExtendedLogEntry entry = listener.getEntryX();
		assertTrue(entry.getLevel() == LogService.LOG_INFO);
		assertEquals("Wrong level.", LogLevel.INFO, entry.getLogLevel());
		assertTrue("Wrong context: " + entry.getContext(), entry.getContext() instanceof ServiceEvent);
	}

	public void testLogServiceEventDebug() throws Exception {
		ServiceRegistration registration = OSGiTestsActivator.getContext().registerService(Object.class.getName(), new Object(), null);

		TestListener listener = new TestListener();
		reader.addLogListener(listener);
		synchronized (listener) {
			registration.setProperties(new Hashtable());
			listener.waitForLogEntry();
		}
		ExtendedLogEntry entry = listener.getEntryX();
		assertTrue(entry.getLevel() == LogService.LOG_DEBUG);
		assertEquals("Wrong level.", LogLevel.DEBUG, entry.getLogLevel());
		assertTrue("Wrong context: " + entry.getContext(), entry.getContext() instanceof ServiceEvent);
	}

	public void testLogFrameworkEvent() throws Exception {
		Bundle testBundle = installer.installBundle("test.logging.a"); //$NON-NLS-1$
		final AtomicReference<LogEntry> logEntry = new AtomicReference<>();
		final CountDownLatch countDown = new CountDownLatch(1);
		LogListener listener = new LogListener() {
			@Override
			public void logged(LogEntry entry) {
				if ("Events.Framework".equals(entry.getLoggerName())) {
					logEntry.set(entry);
					countDown.countDown();
				}
			}
		};
		reader.addLogListener(listener);
		installer.refreshPackages(new Bundle[] {testBundle});

		countDown.await(5, TimeUnit.SECONDS);

		ExtendedLogEntry entry = (ExtendedLogEntry) logEntry.get();
		assertTrue(entry.getLevel() == LogService.LOG_INFO);
		assertEquals("Wrong level.", LogLevel.INFO, entry.getLogLevel());
		assertTrue("Wrong context: " + entry.getContext(), entry.getContext() instanceof FrameworkEvent);
	}

	public void testLogFrameworkEventType() throws Exception {
		final List<LogEntry> events = new CopyOnWriteArrayList<LogEntry>();
		final CountDownLatch countDown = new CountDownLatch(3);
		final Bundle b = getContext().getBundle();
		LogListener listener = new LogListener() {
			@Override
			public void logged(LogEntry entry) {
				if (b.equals(entry.getBundle())) {
					events.add(entry);
					countDown.countDown();
				}
			}
		};
		reader.addLogListener(listener);

		//publishing an event with ERROR
		b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.ERROR, b.adapt(Module.class), new Exception());
		//publishing an event with WARNING
		b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.WARNING, b.adapt(Module.class), new Exception());
		//publishing an event with INFO
		b.adapt(Module.class).getContainer().getAdaptor().publishContainerEvent(ContainerEvent.INFO, b.adapt(Module.class), new Exception());

		countDown.await(2, TimeUnit.SECONDS);
		assertEquals("Wrong number of events", 3, events.size());
		assertEquals("Wrong type.", LogLevel.ERROR, events.get(0).getLogLevel());
		assertEquals("Wrong type.", LogLevel.WARN, events.get(1).getLogLevel());
		assertEquals("Wrong type.", LogLevel.INFO, events.get(2).getLogLevel());

	}

	public void testLogHistory1() throws BundleException {
		File config = OSGiTestsActivator.getContext().getDataFile(getName());
		Map<String, Object> configuration = new HashMap<String, Object>();
		configuration.put(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath());
		configuration.put(EquinoxConfiguration.PROP_LOG_HISTORY_MAX, "10");
		Equinox equinox = new Equinox(configuration);
		equinox.start();

		try {
			LogService testLog = equinox.getBundleContext().getService(equinox.getBundleContext().getServiceReference(LogService.class));
			LogReaderService testReader = equinox.getBundleContext().getService(equinox.getBundleContext().getServiceReference(LogReaderService.class));
			assertEquals("Expecting no logs.", 0, countLogEntries(testReader.getLog(), 0));
			// log 9 things
			for (int i = 0; i < 9; i++) {
				testLog.log(LogService.LOG_WARNING, String.valueOf(i));
			}
			assertEquals("Wrong number of logs.", 9, countLogEntries(testReader.getLog(), 8));

			// log 9 more things
			for (int i = 9; i < 18; i++) {
				testLog.log(LogService.LOG_WARNING, String.valueOf(i));
			}

			// should only be the last 10 logs (17-8)
			assertEquals("Wrong number of logs.", 10, countLogEntries(testReader.getLog(), 17));
		} finally {
			try {
				equinox.stop();
			} catch (BundleException e) {
				// ignore
			}
		}
	}

	public void testLogHistory2() throws BundleException {
		File config = OSGiTestsActivator.getContext().getDataFile(getName());
		Map<String, Object> configuration = new HashMap<String, Object>();
		configuration.put(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath());
		Equinox equinox = new Equinox(configuration);
		equinox.start();

		try {
			LogService testLog = equinox.getBundleContext().getService(equinox.getBundleContext().getServiceReference(LogService.class));
			LogReaderService testReader = equinox.getBundleContext().getService(equinox.getBundleContext().getServiceReference(LogReaderService.class));
			assertEquals("Expecting no logs.", 0, countLogEntries(testReader.getLog(), 0));
			// log 9 things
			for (int i = 0; i < 9; i++) {
				testLog.log(LogService.LOG_WARNING, String.valueOf(i));
			}
			assertEquals("Wrong number of logs.", 0, countLogEntries(testReader.getLog(), 0));
		} finally {
			try {
				equinox.stop();
			} catch (BundleException e) {
				// ignore
			}
		}
	}

	private int countLogEntries(Enumeration logEntries, int startingMessage) {
		int count = 0;
		while (logEntries.hasMoreElements()) {
			LogEntry entry = (LogEntry) logEntries.nextElement();
			assertEquals("Wrong log message.", String.valueOf(startingMessage), entry.getMessage());
			startingMessage--;
			count++;
		}
		return count;
	}

	public void testLoggerContextSetLogLevelsWithBundleInstalledAndLogger() throws Exception {
		Bundle bundle = null;
		String loggerName = "test.logger";
		try {
			bundle = installer.installBundle("test.logging.a");
			bundle.start();
			Logger logger = log.getLogger(bundle, loggerName, Logger.class);
			assertNotNull("Logger cannot be null", logger);
			//Bundle is installed and a logger is associated with that bundle before setting the log level
			setAndAssertLogLevel(bundle.getSymbolicName(), loggerName);

			TestListener listener = new TestListener(bundle);
			reader.addLogListener(listener);
			for (LogLevel logLevel : LogLevel.values()) {
				String message = logLevel.name() + " MESSAGE";
				doLogging(bundle, logger, listener, logLevel, message);
			}
		} finally {
			if (bundle != null) {
				bundle.stop();
				bundle.uninstall();
			}
		}
	}

	public void testLoggerContextSetLogLevelsWithBundleInstalledAndNoLogger() throws Exception {
		Bundle bundle = null;
		String loggerName = "test.logger";
		try {
			bundle = installer.installBundle("test.logging.a");
			bundle.start();
			//Bundle is installed but a logger is not associated with the bundle before setting the log level
			setAndAssertLogLevel(bundle.getSymbolicName(), loggerName);
			Logger logger = log.getLogger(bundle, loggerName, Logger.class);
			assertNotNull("Logger cannot be null", logger);
			TestListener listener = new TestListener(bundle);
			reader.addLogListener(listener);
			for (LogLevel logLevel : LogLevel.values()) {
				String message = logLevel.name() + " MESSAGE";
				doLogging(bundle, logger, listener, logLevel, message);
			}
		} finally {
			if (bundle != null) {
				bundle.stop();
				bundle.uninstall();
			}
		}
	}

	public void testLoggerContextSetLogLevelsWithoutBundleAndLogger() throws Exception {
		Bundle bundle = null;
		String loggerName = "test.logger";
		//Bundle is not installed and also the logger is not associated with the bundle before setting the log level
		setAndAssertLogLevel("test.logging.a", loggerName);
		try {
			bundle = installer.installBundle("test.logging.a");
			bundle.start();
			Logger logger = log.getLogger(bundle, loggerName, Logger.class);
			assertNotNull("Logger cannot be null", logger);
			TestListener listener = new TestListener(bundle);
			reader.addLogListener(listener);
			for (LogLevel logLevel : LogLevel.values()) {
				String message = logLevel.name() + " MESSAGE";
				doLogging(bundle, logger, listener, logLevel, message);
			}
		} finally {
			if (bundle != null) {
				bundle.stop();
				bundle.uninstall();
			}
		}
	}

	private void setAndAssertLogLevel(String loggerContextName, String loggerName) {
		LoggerContext loggerContext = loggerAdmin.getLoggerContext(loggerContextName);
		Map<String, LogLevel> logLevels = loggerContext.getLogLevels();
		logLevels.put(loggerName, LogLevel.TRACE);
		loggerContext.setLogLevels(logLevels);
		assertEquals("Log levels not set for " + loggerContext.getName(), logLevels, loggerContext.getLogLevels());
		assertEquals("Wrong effective level", LogLevel.TRACE, loggerContext.getEffectiveLogLevel(loggerName));
	}

	private void doLogging(Bundle bundle, Logger logger, TestListener listener, LogLevel logLevel, String message) throws Exception {
		synchronized (listener) {
			logToLogger(logger, message, logLevel);
			listener.waitForLogEntry();
		}
		ExtendedLogEntry logEntry = listener.getEntryX();
		assertEquals("Wrong message logged", message, logEntry.getMessage());
		assertEquals("Wrong Log level", logLevel, logEntry.getLogLevel());
		assertEquals("Wrong Logger name", logger.getName(), logEntry.getLoggerName());
		assertEquals("Wrong bundle", bundle.getSymbolicName(), logEntry.getBundle().getSymbolicName());
	}

	private void logToLogger(Logger logger, String message, LogLevel logLevel) {
		switch (logLevel) {
			case AUDIT :
				logger.audit(message);
				break;
			case ERROR :
				logger.error(message);
				break;
			case WARN :
				logger.warn(message);
				break;
			case INFO :
				logger.info(message);
				break;
			case DEBUG :
				logger.debug(message);
				break;
			case TRACE :
				logger.trace(message);
				break;
			default :
				fail("Unknown Log level");
		}
	}
}

Back to the top