Home > database >  Eclipse E4 RCP Logger - Get calling class or package
Eclipse E4 RCP Logger - Get calling class or package

Time:11-29

I have to use a separate class to for loggin instead of calling the LOGGER directly in every class i'd like to log.

I am using the following to do so:

    import org.eclipse.e4.core.services.log.Logger
     
class A {
    static Logger logger = PlatformUI.getWorkbench().getService(org.eclipse.e4.core.services.log.Logger.class)
    
    public static void info(String message) {
        logger.info(message);
    }
}

class B {
    A.info("Foobar");
}

Now when I call the Info() method it writes the following in the .log file: "[...] org.eclipse.e4.ui.workbench [...] !MESSAGE Foobar"

Question: How can I log the class from which the Logger was called without implementing the logger in that specific class. I want it to log something like "!MESSAGE Class A Foobar". So i know which class or at least Package the log entry comes from. Thank you!

CodePudding user response:

The Logger class Javadoc says it is not intended for end-user use. PlatformUI is not for pure e4 (you can't use anything in org.eclipse.ui.xxx plug-ins).

Instead you can use the ILog interface returned by Platform.getLog(). The Java 9 and onwards StackWalker can be used to get the caller.

I use something like:

public final class Log
{
  /** The stack walker to get the caller */
  private static final StackWalker Stack_Walker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);


  public static void info(final String msg)
  {
    final var caller = Stack_Walker.getCallerClass();

    Platform.getLog(caller).info(msg);
  }
}
  • Related