如何在激活器中获取IEclipseContext

我遇到了Eclipse 4 RCP应用程序的一个问题。 我需要记录一些事件。 我需要以某种方式获得对记录器的引用。 我知道,如何使用IEclipseContext做到这IEclipseContext ,但我无处可寻,如何在没有dependency injection的情况下获取IEclipseContext ,我无法在激活器中使用。 你有谁知道,请问如何解决这个问题?

非常感谢

您可以通过调用EclipseContextFactory.getServiceContext(bundleContext)来获取专门的IEclipseContext ,这将允许访问OSGi服务。

似乎很遗憾,没有使用注入就无法获得IEclipseContext 。 关于如何在未附加到应用程序模型的类中使用eclipse 4 DI的答案中写了:

但是,问题是IEclipseContext已经需要注入到一个可以访问需要注入的对象的类中。

不过我已经解决了伐木问题和我的事情,这个原则一般都有效。 总有一些服务提供您需要的东西。 如果你不能使用dependency injection,你必须以某种方式(互联网和实验经常)获得适当的服务类名称。 如果您已获得服务类名称,则可以从捆绑上下文中获取实例引用。 幸运的是,可以在不使用注入的情况下访问bundle上下文。

回到我们的日志问题。 被搜索的类是org.osgi.service.log.LogService

 public class Activator implements BundleActivator { ... private static BundleContext context; ... public static BundleContext getContext() { return context; } ... public void start(BundleContext bundleContext) throws Exception { ServiceReference logser = bundleContext.getServiceReference(LogService.class); LogService ls = (LogService)bundleContext.getService(logser); //print an error to test it (note, that info can be below the threshold) ls.log(LogService.LOG_ERROR, "The bundle is starting..."); Activator.context = bundleContext; } ... } 

Etvoilà!

 !ENTRY eu.barbucha.rcp-experiment.kernel 4 0 2013-08-20 07:32:32.347 !MESSAGE The bundle is starting... 

就这样。 稍后,如果需要,可以使用Activator.getContext()获取bundle上下文。

重要提示:遗憾的是,您现在无法降低阈值。 JVM参数-Declipse.log.level不会影响OSGI日志服务,您现在只使用OSGI记录器。 不幸的是,他们(可能暂时)硬编码了日志记录阈值(请参阅如何在日食3.7中记录警告和信息 )。 我发现,他们还没有修复它。 在开普勒版本中都没有。 但是你可以做出妥协。 在可能的情况下 ,您可以采用注射方式

最终解决方案(以便在全球范围内捕获exception)

我扩展了我的激活器:

 ServiceReference logreser = bundleContext.getServiceReference(LogReaderService.class); LogReaderService lrs = (LogReaderService) bundleContext.getService(logreser); lrs.addLogListener(new LogListener() { @Override public void logged(LogEntry entry) { System.err.println("Something was logged: " + entry.getMessage()); } }); 

记录Something开头的文本确实出现了,whenewer记录了某个地方。 但最大的优点是,这个class级是我的。 我可以控制它。 日志条目还包含级别。 我也可以轻松设置阈值。 例如,在命令行上。

可以从IWorkbench获取“WorkbenchContext”作为服务:

 import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.ui.PlatformUI; public final class EclipseContextHelper { public static IEclipseContext getActiveContext(){ IEclipseContext context = getWorkbenchContext(); return context == null ? null : context.getActiveLeaf(); } public static IEclipseContext getWorkbenchContext(){ return PlatformUI.getWorkbench().getService(IEclipseContext.class); } }