Register a Log Service with a Component
Purpose
Show how to register a service with a component.
Prerequisites
- Declarative services - org.osgi.service.component
- Log Service - org.osgi.service.log
- osgi interfaces, provides all service interfaces for the OSGi specifications.
Instructions
Components use POJOs: simple objects that are not hindered by any framework code. In this snippet we can actually use the same code as in the RegisterService snippet.
Source: aQute.servicecomponent.SimpleLogService package aQute.servicecomponent; import org.osgi.framework.*; import org.osgi.service.log.*; public class SimpleLogService implements org.osgi.service.log.LogService { public void log(int level, String message) { log(level, message, null); } public void log(int level, String message, Throwable exception) { System.err.println(level(level) + ":" + message + ":" + exception); } public void log(ServiceReference sr, int level, String message) { log(sr, level, message, null); } public void log(ServiceReference sr, int level, String message, Throwable exception) { System.err.println(level(level) + ":" + sr.getProperty(Constants.SERVICE_ID) + ":" + message + ":" + exception); } private String level(int level) { switch (level) { case LogService.LOG_DEBUG: return "DEBUG"; case LogService.LOG_ERROR: return "ERROR"; case LogService.LOG_INFO: return "INFO"; case LogService.LOG_WARNING: return "WARNING"; default: return "UNKNOWN(" + level + ")"; } } }
There is no need for an activator because we use Declarative Services. The only thing we therefore need is Bnd:
Bnd: aQute.servicecomponent Export-Package: aQute.servicecomponent Service-Component: aQute.servicecomponent.SimpleLogService; \
provide:=org.osgi.service.log.LogService; \
properties:="service.pid=biz.aQute.servicecomponent, \
service.ranking=2000"
Links
- The specification discusses declarative services in chapter 112 of the OSGi Compendium.
- Declarative Services Javadoc
- Log Service Javadoc
- aQute.servicecomponent.jar



