2 * Copyright © 2016-2017 European Support Limited
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.openecomp.sdc.logging.api;
19 import org.openecomp.sdc.logging.provider.LoggerCreationService;
20 import org.openecomp.sdc.logging.provider.LoggingContextService;
21 import org.openecomp.sdc.logging.provider.LoggingServiceProvider;
23 import java.util.Iterator;
24 import java.util.Optional;
25 import java.util.ServiceLoader;
28 * <p>Binds to a concrete implementation of logging services.</p>
30 * <p>In order to use the factory, a particular (e.g. framework-specific) implementation of a service must be
31 * configured as described in
32 * <a href="http://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html">java.util.ServiceLoader</a>).</p>
40 // No advanced logging can be used here because we don't know
41 // which underlying implementation will be used
42 @SuppressWarnings({"UseOfSystemOutOrSystemErr", "squid:S106"})
45 private static final LoggingServiceProvider PROVIDER = lookupProvider();
47 private ServiceBinder () {
48 // prevent instantiation
51 private static LoggingServiceProvider lookupProvider() {
53 ServiceLoader<LoggingServiceProvider> loader = ServiceLoader.load(LoggingServiceProvider.class);
54 Iterator<LoggingServiceProvider> iterator = loader.iterator();
56 if (!iterator.hasNext()) {
57 System.err.printf("[ERROR] No provider configured for logging services %s. " +
58 "Default implementation will be used.\n",
59 LoggingServiceProvider.class.getName());
65 LoggingServiceProvider provider = iterator.next();
66 if (!iterator.hasNext()) {
70 Logger logger = provider.getLogger(ServiceBinder.class);
71 if (logger.isWarnEnabled()) {
72 logger.warn("More than one provider for logging services {} found",
73 LoggingServiceProvider.class.getName());
78 } catch (Exception e) {
79 // don't fail if the provider cannot be instantiated
80 e.printStackTrace(System.err);
85 static Optional<LoggingContextService> getContextServiceBinding() {
86 return Optional.ofNullable(PROVIDER);
89 static Optional<LoggerCreationService> getCreationServiceBinding() {
90 return Optional.ofNullable(PROVIDER);