Skip to content

Commit bf93c0d

Browse files
committed
✨ Adds feature that allows to prefer a provider
Signed-off-by: Marco Carletti <[email protected]>
1 parent 6fd9db9 commit bf93c0d

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

slf4j-api/src/main/java/org/slf4j/LoggerFactory.java

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ private final static void bind() {
178178
List<SLF4JServiceProvider> providersList = findServiceProviders();
179179
reportMultipleBindingAmbiguity(providersList);
180180
if (providersList != null && !providersList.isEmpty()) {
181-
PROVIDER = providersList.get(0);
181+
PROVIDER = preferProvider(providersList);
182182
// SLF4JServiceProvider.initialize() is intended to be called here and nowhere else.
183183
PROVIDER.initialize();
184184
INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
@@ -199,6 +199,29 @@ private final static void bind() {
199199
}
200200
}
201201

202+
/**
203+
* In case of multiple providers, it picks the one from "slf4j.preferred.provider" system property,
204+
* or leave the default one.
205+
* @param providersList List<SLF4JServiceProvider> providers
206+
* @return SLF4JServiceProvider the found provider, matching class name provided in the system property
207+
* if found, default one otherwise
208+
*/
209+
private static SLF4JServiceProvider preferProvider(List<SLF4JServiceProvider> providersList) {
210+
final String preferred = System.getProperty("slf4j.preferred.provider", "");
211+
SLF4JServiceProvider found = providersList.get(0);
212+
if (preferred == null || preferred.isEmpty()) {
213+
return found;
214+
} else {
215+
Util.report("Preferred provider : " + preferred);
216+
}
217+
return providersList.stream()
218+
.filter(provider -> preferred.equalsIgnoreCase(provider.getClass().getName()))
219+
.findFirst().orElseGet(() -> {
220+
Util.report("Preferred provider not found in the providers, use " + found);
221+
return found;
222+
});
223+
}
224+
202225
private static void reportIgnoredStaticLoggerBinders(Set<URL> staticLoggerBinderPathSet) {
203226
if (staticLoggerBinderPathSet.isEmpty()) {
204227
return;
@@ -374,7 +397,7 @@ private static void reportMultipleBindingAmbiguity(List<SLF4JServiceProvider> pr
374397
private static void reportActualBinding(List<SLF4JServiceProvider> providerList) {
375398
// binderPathSet can be null under Android
376399
if (!providerList.isEmpty() && isAmbiguousProviderList(providerList)) {
377-
Util.report("Actual provider is of type [" + providerList.get(0) + "]");
400+
Util.report("Actual provider is of type [" + PROVIDER + "]");
378401
}
379402
}
380403

0 commit comments

Comments
 (0)