javaeclipseloggingosgiloggerfactory

LoggerFactory cannot getLogger


I'm currently implementing a Logger and I'm wondering why the code won't run. Most of the codes snipets are like these:

Logger log = LoggerFactory.getLogger(this.getClass());

My imported classes:

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogReaderService;
import org.osgi.service.log.LogService;
import org.osgi.service.log.Logger;
import org.osgi.service.log.LoggerFactory;

But I can't seem to use getLogger.

Why is that?

Thanks in advance! No getLogger() classes are available


Solution

  • Here is the source code of org.osgi.service.log.LoggerFactory.

    As you can see, it's an interface with no static methods therefore this code:

    Logger log = LoggerFactory.getLogger(this.getClass());
    

    is simply not valid.

    To fix this use slf4j as front end (this means replace org.osgi.service.log.LoggerFactory import with org.slf4j.LoggerFactory etc.).

    UPDATE

    If you want to stick with org.osgi.service.log.LoggerFactory then follow this:

    Obtain the LoggerFactory instance:

    public class Activator implements BundleActivator
    {
        private volatile LoggerFactory loggerFactory;
    
        public void start(BundleContext context) throws Exception 
        {   
            ServiceReference ref = context.getServiceReference(LoggerFactory.class.getName());
            if (ref != null)
            {
                loggerFactory = (LoggerFactory) context.getService(ref);
            }
        }
    
        //..
    

    Elsewhere in the bundle you can then use the LoggerFactory to get a Logger for any class:

    Logger logger = loggerFactory.getLogger(Foo.class);
    

    UPDATE2

    A better alternative would be to get a reference who's service type is LoggerFactory like this:

    @Reference(service = LoggerFactory.class)
    private Logger logger;