如何在激活器中获取IEclipseContext

Tom*_* K. 6 java eclipse-rcp e4

我遇到了Eclipse 4 RCP应用程序的一个问题.我需要记录一些事件.我需要以某种方式获取对记录器的引用.我知道,如何使用IEclipseContext,但我没有找到,如何获得IEclipseContext没有依赖注入,我不能在激活器中使用.你有谁知道,请问如何解决这个问题?

非常感谢

gre*_*449 6

您可以IEclipseContext通过调用获得专门的EclipseContextFactory.getServiceContext(bundleContext)访问OSGi服务.


Tom*_* K. 4

似乎遗憾的是,不使用注入就无法获取。\n在How to use eclipse 4 DI in classes that are not Attached to the application model 的IEclipseContext答案中写道:

\n\n
\n

然而,问题是,IEclipseContext已经需要将其注入到可以访问需要注入的对象的类中。

\n
\n\n

不过我已经解决了日志记录的问题,而且我认为原理基本有效。总有一些服务可以提供您需要的东西。如果您无法使用依赖项注入,则必须以某种方式(互联网和实验很常见)获得适当的服务类名称。如果您已经获得了服务类名称,那么您可以从捆绑上下文中获取实例引用。幸运的是,无需使用注入即可访问包上下文。

\n\n

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

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

等瞧\xc3\xa0!

\n\n
!ENTRY eu.barbucha.rcp-experiment.kernel 4 0 2013-08-20 07:32:32.347\n!MESSAGE The bundle is starting...\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

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

\n\n

最终解决方案(也可以捕获全局异常)

\n\n

我扩展了我的激活器:

\n\n
ServiceReference<?> logreser = bundleContext.getServiceReference(LogReaderService.class);\nLogReaderService lrs = (LogReaderService) bundleContext.getService(logreser);   \nlrs.addLogListener(new LogListener() {\n    @Override\n    public void logged(LogEntry entry) {\n        System.err.println("Something was logged: " + entry.getMessage());\n    }\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

以Something 开头的文本已被记录内容时,确实会出现以“Something waslogging”但最大的好处是,这个班级是我的。我可以控制它。日志条目还包含级别。我还可以轻松设置阈值。例如在命令行上。

\n