Time for action – adding logging

The OSGi platform defines a LogService which allows messages to be logged to a central collector. In the E4 platform, an instance of LogService is available as part of the platform, routing error messages through to the console.

  1. Open the Hello class and add a private field LogService log.
  2. Add an @Inject annotation above the LogService field.
  3. In the create() method, add a call to the log service.
  4. The Hello class will look like:
    import javax.inject.Inject;
    import org.osgi.service.log.LogService;
    public class Hello {
      @Inject
      private LogService log;
      @PostConstruct
      public void create(Composite parent) {
        label = new Label(parent, SWT.NONE);
        label.setText("Hello");
        log.log(LogService.LOG_ERROR,"Hello");
      }
    }
  5. Run the application, and a log message will be printed out to the console of the host Eclipse:
    !ENTRY org.eclipse.e4.ui.workbench 4 0 2013-01-24 23:15:51.543
    !MESSAGE Hello

What just happened?

The E4 runtime infrastructure injected the reference into the class when it was constructed. The instance was obtained from the E4 context, which looks through a hierarchy of contexts until it can find an instance which matches the class type. At the root of the context tree, the list of OSGi services is consulted.

If a LogService cannot be found in the context, the part will fail to be created with an error message:

!ENTRY org.eclipse.e4.ui.workbench 4 0 2013-01-24 23:19:04.328
!MESSAGE Unable to create class 'com.pactpub.e4.app.parts.Hello'
 from bundle '29'
!STACK 0
org.eclipse.e4.core.di.InjectionException: Unable to process
 "Hello.log": no actual value was found for the argument "LogService"
  at org.eclipse.e4.core.internal.di.InjectorImpl.
     reportUnresolvedArgument(InjectorImpl.java:394)

To mark the service as optional (that is it can be null), annotate it with @Optional:

import org.eclipse.e4.core.di.annotations.Optional;
public class Hello {
  @Inject @Optional
  private LogService log;
  @PostConstruct
  public void create(Composite parent) {
    if (log != null) {
      log.log(LogService.LOG_ERROR, "Hello");
    }

Remember that @Optional annotated fields or parameters have to be guarded against the possibility of being null.

If a service arrives after instantiation, the service will be injected into the part.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset