Apache Felix OSGi 使用 Logback 进行日志记录

Apache Felix OSGi logging with Logback

我当前的应用程序使用 Logback 进行日志记录。我使用 Apache Felix 部署了一个 OSGi 框架,该框架允许在运行时动态注册捆绑包。 Felix设置如下:

    ...

    //System.out.println("Building OSGi Framework");
    FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
    Map<String, String> config = new HashMap<>();

    // specify the class loader
    config.put(Constants.FRAMEWORK_BUNDLE_PARENT, Constants.FRAMEWORK_BUNDLE_PARENT_FRAMEWORK);

    // specify the osgi cache directory
    config.put(Constants.FRAMEWORK_STORAGE, appConfig.getOsgiCacheDir());

    // make sure the cache is cleaned
    config.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);

    // expose api
    config.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "list.of.packages.to.export");

    // more properties available at: http://felix.apache.org/documentation/subprojects/apache-felix-service-component-runtime.html
    config.put("ds.showtrace", "false");
    config.put("ds.showerrors", "true");
    config.put("felix.fileinstall.dir", appConfig.getActiveOsgiExtDir());
    config.put("felix.fileinstall.tmpdir", appConfig.getTempOsgiExtDir());
    config.put("felix.fileinstall.bundles.startTransient","true");
    config.put("felix.fileinstall.poll","5000");
    config.put("felix.fileinstall.bundles.new.start", "true");

    LOG.debug("OSGi config: " + config.toString());

    framework = frameworkFactory.newFramework(config);

    try {
        framework.init();
        FrameworkEvent event;

        do {
            framework.start();
    ...

唯一的问题是 Felix 似乎没有日志记录。当捆绑由于某种原因无法加载时,我不明白为什么!我知道我可以在包中使用以下内容来获取父记录器:

ServiceReference ref = bundleContext.getServiceReference(LogService.class.getName());
if (ref != null) {
    LogService log = (LogService) bundleContext.getService(ref);
    ...
   }

但是,我不明白如何让 felix 首先使用 logback 作为记录器。

我猜你使用 Apache Felix Log 在你的 OSGi 容器中有一个 LogService。 Apache Felix Log 实现了 OSGi Enterprise Specification 101 Log Service Specification 章节。

LogService 实现的基础是将记录的条目存储一段时间,但不会将它们写入任何地方。您可以通过 LogReaderServiceLogListener.

查询记录条目

另一方面,您可以按照将 slf4j-api 和 slf4j-logback 添加到 OSGi 容器的方式使用 Logback。通过这样做,通过 slf4j-api 类 记录的所有内容都将由 logback.

记录

如果我的猜测是正确的,osgi-loglistener-slf4j bundle could help you. This bundle does nothing else but registers a LogListener for every LogReaderService in the environment and forwards every log entries it catches to slf4j-api. The bundle is available on maven-central

如果您不想使用 slf4j API,您可以编写一个类似的包,将日志从 LogReaderService 转发到 Logback。如果你检查我链接的包的源代码,你会发现它只用几行代码实现。