Skip to content

Instantly share code, notes, and snippets.

@agentgt
Last active March 17, 2017 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agentgt/28dc6e9724cb8b96ca08fc147476a7de to your computer and use it in GitHub Desktop.
Save agentgt/28dc6e9724cb8b96ca08fc147476a7de to your computer and use it in GitHub Desktop.
A wrapper SLF4j to avoid default static initialization
package com.snaphop.slf4j;
import java.util.ServiceLoader;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.helpers.NOPLoggerFactory;
public interface LoggerService {
public static class InternalLoggerFactory {
/*
* Simply prefix Internal in front of LoggerFactory:
* So instead of:
* Logger logger = LoggerFactory.getLogger(MyClass.class);
* It should be:
* Logger logger = InternalLoggerFactory.getLogger(MyClass.class);
*/
public static Logger getLogger(Class<?> clazz) {
return getILoggerFactory().getLogger(clazz.getName());
}
public static ILoggerFactory getILoggerFactory() {
return LazyHolder.INSTANCE;
}
//We should not load unless we are requested to. This avoids accidental initialization. @agentgt
//See https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
private static class LazyHolder {
private static final ILoggerFactory INSTANCE = InternalLoggerFactory.createFactory();
}
private static ILoggerFactory createFactory() {
/*
* You could also use a system property or static variable for resolution as well.
* The following looks for a file located here:
* /META-INF/services/LoggerService.getPackage().getName()
* With the name of the class as a single line that implements LoggerService.
*/
ServiceLoader<LoggerService> loader = ServiceLoader.load(LoggerService.class);
for (LoggerService ls : loader) {
return ls.createLoggerFactory();
}
return new NOPLoggerFactory();
//or if you prefer the default
//return LoggerFactory.getILoggerFactory();
}
}
public ILoggerFactory createLoggerFactory();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment