1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.apache.maven.cling.logging;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.lang.reflect.InvocationTargetException;
24 import java.net.URL;
25 import java.util.Enumeration;
26 import java.util.Properties;
27
28 import org.apache.maven.cling.logging.impl.UnsupportedSlf4jBindingConfiguration;
29 import org.slf4j.ILoggerFactory;
30
31 /**
32 * Slf4jConfiguration factory, loading implementations from <code>META-INF/maven/slf4j-configuration.properties</code>
33 * configuration files in class loader: key is the class name of the ILoggerFactory, value is the class name of
34 * the corresponding Slf4jConfiguration.
35 *
36 * @since 3.1.0
37 */
38 public class Slf4jConfigurationFactory {
39 public static final String RESOURCE = "META-INF/maven/slf4j-configuration.properties";
40
41 public static Slf4jConfiguration getConfiguration(ILoggerFactory loggerFactory) {
42 String slf4jBinding = loggerFactory.getClass().getCanonicalName();
43
44 try {
45 Enumeration<URL> resources =
46 Slf4jConfigurationFactory.class.getClassLoader().getResources(RESOURCE);
47
48 while (resources.hasMoreElements()) {
49 URL resource = resources.nextElement();
50 try {
51 InputStream is = resource.openStream();
52 final Properties properties = new Properties();
53 if (is != null) {
54 try (InputStream in = is) {
55 properties.load(in);
56 }
57 }
58 String impl = properties.getProperty(slf4jBinding);
59 if (impl != null) {
60 return (Slf4jConfiguration)
61 Class.forName(impl).getDeclaredConstructor().newInstance();
62 }
63 } catch (IOException
64 | ClassNotFoundException
65 | NoSuchMethodException
66 | InvocationTargetException
67 | IllegalAccessException
68 | InstantiationException ex) {
69 // ignore and move on to the next
70 }
71 }
72 } catch (IOException ex) {
73 // ignore
74 }
75
76 return new UnsupportedSlf4jBindingConfiguration();
77 }
78 }