Package list libslf4j-java / 9429776
New upstream version 1.7.25 Emmanuel Bourg 4 years ago
36 changed file(s) with 760 addition(s) and 457 deletion(s). Raw diff Collapse all Expand all
0 Copyright (c) 2004-2014 QOS.ch
0 Copyright (c) 2004-2017 QOS.ch
11 All rights reserved.
22
33 Permission is hereby granted, free of charge, to any person obtaining
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>integration</artifactId>
3939 <dependency>
4040 <groupId>org.apache.felix</groupId>
4141 <artifactId>org.apache.felix.main</artifactId>
42 <version>2.0.2</version>
42 <version>5.6.1</version>
43 <!--<version>2.0.2</version>-->
4344 </dependency>
4445 </dependencies>
4546
5858
5959 public void doLaunch() {
6060 // Create a case-insensitive configuration property map.
61 StringMap configMap = new StringMap(false);
61 StringMap configMap = new StringMap();
6262 // Configure the Felix instance to be embedded.
6363 // configMap.put(FelixConstants.EMBEDDED_EXECUTION_PROP, "true");
6464 // Add core OSGi packages to be exported from the class path
8888
8989 // otherProps.put(Constants.FRAMEWORK_STORAGE, "bundles");
9090
91 otherProps.put(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, AutoProcessor.AUTO_DEPLOY_DIR_VALUE);
92 otherProps.put(AutoProcessor.AUTO_DEPLOY_ACTION_PROPERY, AutoProcessor.AUTO_DEPLOY_START_VALUE + "," + AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE);
91 otherProps.put(AutoProcessor.AUTO_DEPLOY_DIR_PROPERTY, AutoProcessor.AUTO_DEPLOY_DIR_VALUE);
92 otherProps.put(AutoProcessor.AUTO_DEPLOY_ACTION_PROPERTY, AutoProcessor.AUTO_DEPLOY_START_VALUE + "," + AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE);
9393
9494 BundleContext felixBudleContext = felix.getBundleContext();
9595
44 <parent>
55 <groupId>org.slf4j</groupId>
66 <artifactId>slf4j-parent</artifactId>
7 <version>1.7.22</version>
7 <version>1.7.25</version>
88 </parent>
99
1010 <modelVersion>4.0.0</modelVersion>
1111
1212 <artifactId>jcl-over-slf4j</artifactId>
1313 <packaging>jar</packaging>
14 <name>JCL 1.1.1 implemented over SLF4J</name>
15 <description>JCL 1.1.1 implemented over SLF4J</description>
14 <name>JCL 1.2 implemented over SLF4J</name>
15 <description>JCL 1.2 implemented over SLF4J</description>
1616 <url>http://www.slf4j.org</url>
1717
1818 <dependencies>
33 Bundle-Name: jcl-over-slf4j
44 Bundle-Vendor: SLF4J.ORG
55 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.apache.commons.logging;version=1.1.1,
7 org.apache.commons.logging.impl;version=1.1.1
6 Export-Package: org.apache.commons.logging;version=1.2,
7 org.apache.commons.logging.impl;version=1.2
88 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>jul-to-slf4j</artifactId>
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>osgi-over-slf4j</artifactId>
55
66 <groupId>org.slf4j</groupId>
77 <artifactId>slf4j-parent</artifactId>
8 <version>1.7.22</version>
8 <version>1.7.25</version>
99
1010 <packaging>pom</packaging>
1111 <name>SLF4J</name>
4545 <logback.version>1.0.13</logback.version>
4646 <junit.version>4.12</junit.version>
4747 <maven-site-plugin.version>3.3</maven-site-plugin.version>
48 <javadoc.plugin.version>2.10.2</javadoc.plugin.version>
48 <javadoc.plugin.version>2.10.4</javadoc.plugin.version>
4949 </properties>
5050
5151 <developers>
5858
5959 <modules>
6060 <module>slf4j-api</module>
61 <!--<module>slf4j-scala-api</module>-->
6261 <module>slf4j-simple</module>
6362 <module>slf4j-nop</module>
6463 <module>slf4j-jdk14</module>
6564 <module>slf4j-log4j12</module>
66 <module>slf4j-jcl</module>
65 <module>slf4j-jcl</module>
6766 <module>slf4j-android</module>
6867 <module>slf4j-ext</module>
6968 <module>jcl-over-slf4j</module>
261260 <artifactId>maven-javadoc-plugin</artifactId>
262261 <version>${javadoc.plugin.version}</version>
263262 <configuration>
263 <linksource>true</linksource>
264264 <!--<aggregate>true</aggregate>-->
265265 <excludePackageNames>org.slf4j.migrator:org.slf4j.migrator.*</excludePackageNames>
266266 <links>
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>slf4j-android</artifactId>
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>slf4j-api</artifactId>
8181 </plugin>
8282 </plugins>
8383
84 <pluginManagement>
85 <plugins>
86 <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
87 <plugin>
88 <groupId>org.eclipse.m2e</groupId>
89 <artifactId>lifecycle-mapping</artifactId>
90 <version>1.0.0</version>
91 <configuration>
92 <lifecycleMappingMetadata>
93 <pluginExecutions>
94 <pluginExecution>
95 <pluginExecutionFilter>
96 <groupId>
97 org.apache.maven.plugins
98 </groupId>
99 <artifactId>
100 maven-antrun-plugin
101 </artifactId>
102 <versionRange>[1.3,)</versionRange>
103 <goals>
104 <goal>run</goal>
105 </goals>
106 </pluginExecutionFilter>
107 <action>
108 <ignore></ignore>
109 </action>
110 </pluginExecution>
111 </pluginExecutions>
112 </lifecycleMappingMetadata>
113 </configuration>
114 </plugin>
115 </plugins>
116 </pluginManagement>
84117 </build>
85118
86119 </project>
7373 static final String REPLAY_URL = CODES_PREFIX + "#replay";
7474
7575 static final String UNSUCCESSFUL_INIT_URL = CODES_PREFIX + "#unsuccessfulInit";
76 static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory could not be successfully initialized. See also " + UNSUCCESSFUL_INIT_URL;
76 static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory in failed state. Original exception was thrown EARLIER. See also " + UNSUCCESSFUL_INIT_URL;
7777
7878 static final int UNINITIALIZED = 0;
7979 static final int ONGOING_INITIALIZATION = 1;
8282 static final int NOP_FALLBACK_INITIALIZATION = 4;
8383
8484 static volatile int INITIALIZATION_STATE = UNINITIALIZED;
85 static SubstituteLoggerFactory SUBST_FACTORY = new SubstituteLoggerFactory();
86 static NOPLoggerFactory NOP_FALLBACK_FACTORY = new NOPLoggerFactory();
85 static final SubstituteLoggerFactory SUBST_FACTORY = new SubstituteLoggerFactory();
86 static final NOPLoggerFactory NOP_FALLBACK_FACTORY = new NOPLoggerFactory();
8787
8888 // Support for detecting mismatched logger names.
8989 static final String DETECT_LOGGER_NAME_MISMATCH_PROPERTY = "slf4j.detectLoggerNameMismatch";
3232 loggingEvent.setLevel(level);
3333 loggingEvent.setLogger(logger);
3434 loggingEvent.setLoggerName(name);
35
35 loggingEvent.setMarker(marker);
3636 loggingEvent.setMessage(msg);
3737 loggingEvent.setArgumentArray(args);
3838 loggingEvent.setThrowable(throwable);
2323 */
2424 package org.slf4j.helpers;
2525
26 import java.util.Collections;
2726 import java.util.Iterator;
2827 import java.util.List;
29 import java.util.Vector;
28 import java.util.concurrent.CopyOnWriteArrayList;
3029
3130 import org.slf4j.Marker;
3231
3837 */
3938 public class BasicMarker implements Marker {
4039
41 private static final long serialVersionUID = 1803952589649545191L;
42
40 private static final long serialVersionUID = -2849567615646933777L;
4341 private final String name;
44 private List<Marker> referenceList;
42 private List<Marker> referenceList = new CopyOnWriteArrayList<Marker>();
4543
4644 BasicMarker(String name) {
4745 if (name == null) {
5452 return name;
5553 }
5654
57 public synchronized void add(Marker reference) {
55 public void add(Marker reference) {
5856 if (reference == null) {
5957 throw new IllegalArgumentException("A null value cannot be added to a Marker as reference.");
6058 }
6462 return;
6563
6664 } else if (reference.contains(this)) { // avoid recursion
67 // a potential reference should not its future "parent" as a reference
65 // a potential reference should not hold its future "parent" as a reference
6866 return;
6967 } else {
70 // let's add the reference
71 if (referenceList == null) {
72 referenceList = new Vector<Marker>();
73 }
7468 referenceList.add(reference);
7569 }
76
7770 }
7871
79 public synchronized boolean hasReferences() {
80 return ((referenceList != null) && (referenceList.size() > 0));
72 public boolean hasReferences() {
73 return (referenceList.size() > 0);
8174 }
8275
8376 public boolean hasChildren() {
8477 return hasReferences();
8578 }
8679
87 public synchronized Iterator<Marker> iterator() {
88 if (referenceList != null) {
89 return referenceList.iterator();
90 } else {
91 List<Marker> emptyList = Collections.emptyList();
92 return emptyList.iterator();
93 }
80 public Iterator<Marker> iterator() {
81 return referenceList.iterator();
9482 }
9583
96 public synchronized boolean remove(Marker referenceToRemove) {
97 if (referenceList == null) {
98 return false;
99 }
100
101 int size = referenceList.size();
102 for (int i = 0; i < size; i++) {
103 Marker m = referenceList.get(i);
104 if (referenceToRemove.equals(m)) {
105 referenceList.remove(i);
106 return true;
107 }
108 }
109 return false;
84 public boolean remove(Marker referenceToRemove) {
85 return referenceList.remove(referenceToRemove);
11086 }
11187
11288 public boolean contains(Marker other) {
3131 */
3232 public final class Util {
3333
34
3435 private Util() {
3536 }
3637
125126 static final public void report(String msg) {
126127 System.err.println("SLF4J: " + msg);
127128 }
129
130
131
128132 }
+0
-55
slf4j-api/src/test/java/org/slf4j/FindStaticLoggerBinderPathsPerfTest.hava less more
0 package org.slf4j;
1
2 import org.junit.Ignore;
3 import org.junit.Test;
4
5 public class FindStaticLoggerBinderPathsPerfTest {
6
7 @Test
8 @Ignore
9 public void test() {
10 long duration = timeFindBindingSetCall();
11 System.out.println(duration / (1000) + " microseconds");
12
13 int count = 10;
14 long sum = 0;
15 for (int i = 0; i < count; i++) {
16 sum += timeFindBindingSetCall();
17 }
18 System.out.println(sum / (count * 1000) + " microseconds in average");
19 }
20
21 @Test
22 public void testAsync() throws InterruptedException {
23 long start = System.nanoTime();
24 FindPathSetThread thread = new FindPathSetThread();
25 thread.start();
26 long end = System.nanoTime();
27
28 long duration = end - start;
29 System.out.println(duration / (1000) + " microseconds");
30
31 thread.join();
32 }
33
34 long timeFindBindingSetCall() {
35 long start = System.nanoTime();
36
37 LoggerFactory.findPossibleStaticLoggerBinderPathSet();
38 long end = System.nanoTime();
39 return end - start;
40
41 }
42
43 static class FindPathSetThread extends Thread {
44
45 public void run() {
46 long start = System.nanoTime();
47 LoggerFactory.findPossibleStaticLoggerBinderPathSet();
48 long end = System.nanoTime();
49
50 System.out.println("Found set in " + (end - start)/1000 + " microseconds");
51
52 }
53 }
54 }
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>slf4j-ext</artifactId>
3131 <dependency>
3232 <groupId>ch.qos.cal10n</groupId>
3333 <artifactId>cal10n-api</artifactId>
34 <optional>true</optional>
3435 </dependency>
3536 <dependency>
3637 <groupId>javassist</groupId>
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>slf4j-jcl</artifactId>
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>slf4j-jdk14</artifactId>
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>slf4j-log4j12</artifactId>
0 package org.apache.log4j;
1
2 import java.lang.reflect.Field;
3 import java.lang.reflect.Method;
4
5 import org.apache.log4j.helpers.ThreadLocalMap;
6
7 public class MDCFriend {
8
9 public static void fixForJava9() {
10 if (MDC.mdc.tlm == null) {
11 MDC.mdc.tlm = new ThreadLocalMap();
12 MDC.mdc.java1 = false;
13 setRemoveMethod(MDC.mdc);
14 }
15
16 }
17
18 private static void setRemoveMethod(MDC mdc) {
19 try {
20 Method removeMethod = ThreadLocal.class.getMethod("remove");
21 Field removeMethodField = MDC.class.getDeclaredField("removeMethod");
22 removeMethodField.setAccessible(true);
23 removeMethodField.set(mdc, removeMethod);
24 } catch (NoSuchMethodException e) {
25 } catch (SecurityException e) {
26 } catch (NoSuchFieldException e) {
27 } catch (IllegalArgumentException e) {
28 } catch (IllegalAccessException e) {
29 }
30
31 }
32 }
2727 import java.util.concurrent.ConcurrentMap;
2828
2929 import org.apache.log4j.LogManager;
30 import org.slf4j.helpers.Util;
3130 import org.slf4j.ILoggerFactory;
3231 import org.slf4j.Logger;
32 import org.slf4j.helpers.Util;
3333
3434 /**
3535 * Log4jLoggerFactory is an implementation of {@link ILoggerFactory} returning
2727 import java.util.Iterator;
2828 import java.util.Map;
2929
30 import org.apache.log4j.MDCFriend;
3031 import org.slf4j.spi.MDCAdapter;
3132
3233 public class Log4jMDCAdapter implements MDCAdapter {
3334
34 public void clear() {
35 @SuppressWarnings("rawtypes")
36 Map map = org.apache.log4j.MDC.getContext();
37 if (map != null) {
38 map.clear();
39 }
40 }
35 static {
36 if (VersionUtil.getJavaMajorVersion() >= 9) {
37 MDCFriend.fixForJava9();
38 }
39 }
4140
42 public String get(String key) {
43 return (String) org.apache.log4j.MDC.get(key);
44 }
41 public void clear() {
42 @SuppressWarnings("rawtypes")
43 Map map = org.apache.log4j.MDC.getContext();
44 if (map != null) {
45 map.clear();
46 }
47 }
4548
46 /**
47 * Put a context value (the <code>val</code> parameter) as identified with
48 * the <code>key</code> parameter into the current thread's context map. The
49 * <code>key</code> parameter cannot be null. Log4j does <em>not</em>
50 * support null for the <code>val</code> parameter.
51 *
52 * <p>
53 * This method delegates all work to log4j's MDC.
54 *
55 * @throws IllegalArgumentException
56 * in case the "key" or <b>"val"</b> parameter is null
57 */
58 public void put(String key, String val) {
59 org.apache.log4j.MDC.put(key, val);
60 }
49 public String get(String key) {
50 return (String) org.apache.log4j.MDC.get(key);
51 }
6152
62 public void remove(String key) {
63 org.apache.log4j.MDC.remove(key);
64 }
53 /**
54 * Put a context value (the <code>val</code> parameter) as identified with
55 * the <code>key</code> parameter into the current thread's context map. The
56 * <code>key</code> parameter cannot be null. Log4j does <em>not</em>
57 * support null for the <code>val</code> parameter.
58 *
59 * <p>
60 * This method delegates all work to log4j's MDC.
61 *
62 * @throws IllegalArgumentException
63 * in case the "key" or <b>"val"</b> parameter is null
64 */
65 public void put(String key, String val) {
66 org.apache.log4j.MDC.put(key, val);
67 }
6568
66 @SuppressWarnings({ "rawtypes", "unchecked" })
67 public Map getCopyOfContextMap() {
68 Map old = org.apache.log4j.MDC.getContext();
69 if (old != null) {
70 return new HashMap(old);
71 } else {
72 return null;
73 }
74 }
69 public void remove(String key) {
70 org.apache.log4j.MDC.remove(key);
71 }
7572
76 @SuppressWarnings({ "rawtypes", "unchecked" })
77 public void setContextMap(Map contextMap) {
78 Map old = org.apache.log4j.MDC.getContext();
79 if (old == null) {
80 Iterator entrySetIterator = contextMap.entrySet().iterator();
81 while (entrySetIterator.hasNext()) {
82 Map.Entry mapEntry = (Map.Entry) entrySetIterator.next();
83 org.apache.log4j.MDC.put((String) mapEntry.getKey(), mapEntry.getValue());
84 }
85 } else {
86 old.clear();
87 old.putAll(contextMap);
88 }
89 }
73 @SuppressWarnings({ "rawtypes", "unchecked" })
74 public Map getCopyOfContextMap() {
75 Map old = org.apache.log4j.MDC.getContext();
76 if (old != null) {
77 return new HashMap(old);
78 } else {
79 return null;
80 }
81 }
82
83 @SuppressWarnings({ "rawtypes", "unchecked" })
84 public void setContextMap(Map contextMap) {
85 Map old = org.apache.log4j.MDC.getContext();
86 if (old == null) {
87 Iterator entrySetIterator = contextMap.entrySet().iterator();
88 while (entrySetIterator.hasNext()) {
89 Map.Entry mapEntry = (Map.Entry) entrySetIterator.next();
90 org.apache.log4j.MDC.put((String) mapEntry.getKey(), mapEntry.getValue());
91 }
92 } else {
93 old.clear();
94 old.putAll(contextMap);
95 }
96 }
9097 }
3232 */
3333 public class StaticMDCBinder {
3434
35 /**
36 * The unique instance of this class.
37 */
38 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
35 /**
36 * The unique instance of this class.
37 */
38 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
3939
40 private StaticMDCBinder() {
41 }
40 private StaticMDCBinder() {
41 }
4242
43 /**
44 * Return the singleton of this class.
45 *
46 * @return the StaticMDCBinder singleton
47 * @since 1.7.14
48 */
49 public static final StaticMDCBinder getSingleton() {
50 return SINGLETON;
51 }
43 /**
44 * Return the singleton of this class.
45 *
46 * @return the StaticMDCBinder singleton
47 * @since 1.7.14
48 */
49 public static final StaticMDCBinder getSingleton() {
50 return SINGLETON;
51 }
5252
53 /**
54 * Currently this method always returns an instance of
55 * {@link StaticMDCBinder}.
56 */
57 public MDCAdapter getMDCA() {
58 return new Log4jMDCAdapter();
59 }
53 /**
54 * Currently this method always returns an instance of
55 * {@link StaticMDCBinder}.
56 */
57 public MDCAdapter getMDCA() {
58 return new Log4jMDCAdapter();
59 }
6060
61 public String getMDCAdapterClassStr() {
62 return Log4jMDCAdapter.class.getName();
63 }
61 public String getMDCAdapterClassStr() {
62 return Log4jMDCAdapter.class.getName();
63 }
6464 }
0 package org.slf4j.impl;
1
2 import java.lang.reflect.Method;
3
4 import org.slf4j.helpers.Util;
5
6 public class VersionUtil {
7 static final int MINIMAL_VERSION = 5;
8
9 static public int getJavaMajorVersion() {
10 String javaVersionString = Util.safeGetSystemProperty("java.version");
11 return getJavaMajorVersion(javaVersionString);
12 }
13
14 static int getJavaMajorVersion(String versionString) {
15 if (versionString == null)
16 return MINIMAL_VERSION;
17 if (versionString.startsWith("1.")) {
18 return versionString.charAt(2) - '0';
19 } else {
20 // we running under Java 9 or later
21 try {
22 Method versionMethod = Runtime.class.getMethod("version");
23 Object versionObj = versionMethod.invoke(null);
24 Method majorMethod = versionObj.getClass().getMethod("major");
25 Integer resultInteger = (Integer) majorMethod.invoke(versionObj);
26 return resultInteger.intValue();
27 } catch (Exception e) {
28 return MINIMAL_VERSION;
29 }
30 }
31 }
32 }
0 package org.apache.log4j;
1
2 import static org.junit.Assert.assertEquals;
3 import static org.junit.Assert.assertNull;
4
5 import java.util.Random;
6
7 import org.junit.Test;
8 import org.slf4j.impl.VersionUtil;
9
10 public class MDCFriendTest {
11
12
13 private static Random random = new Random();
14 int diff = random.nextInt(1024*8);
15
16 @Test
17 public void smoke() {
18 if(VersionUtil.getJavaMajorVersion() < 9)
19 return;
20
21 MDCFriend.fixForJava9();
22 String key = "MDCFriendTest.smoke"+diff;
23 String val = "val"+diff;
24 MDC.put(key, val);
25 assertEquals(val, MDC.get(key));
26 MDC.clear();
27 assertNull(MDC.get(key));
28
29 }
30
31 }
6767
6868 @Test
6969 public void test2() {
70 Integer i1 = new Integer(1);
71 Integer i2 = new Integer(2);
72 Integer i3 = new Integer(3);
70 Integer i1 = Integer.valueOf(1);
71 Integer i2 = Integer.valueOf(2);
72 Integer i3 = Integer.valueOf(3);
7373 Exception e = new Exception("This is a test exception.");
7474 Logger logger = LoggerFactory.getLogger("test2");
7575
8787 logger.warn("Hello world 3", e);
8888
8989 logger.error("Hello world 4.");
90 logger.error("Hello world {}", new Integer(3));
90 logger.error("Hello world {}", Integer.valueOf(3));
9191 logger.error("Hello world 4.", e);
9292 assertEquals(11, listAppender.list.size());
9393 }
0 package org.slf4j.impl;
1
2 import static org.junit.Assert.*;
3
4 import org.junit.Ignore;
5 import org.junit.Test;
6
7 public class UtilVersionTest {
8
9 @Test
10 public void test() {
11 System.out.println(System.getProperty("java.version"));
12 assertEquals(6, VersionUtil.getJavaMajorVersion("1.6"));
13 assertEquals(7, VersionUtil.getJavaMajorVersion("1.7.0_21-b11"));
14 assertEquals(8, VersionUtil.getJavaMajorVersion("1.8.0_25"));
15 }
16
17 @Ignore
18 @Test // requires Java 9 to pass
19 public void testJava9() {
20 assertEquals(9, VersionUtil.getJavaMajorVersion("9ea"));
21 }
22
23 }
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>slf4j-migrator</artifactId>
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>slf4j-nop</artifactId>
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>slf4j-simple</artifactId>
0 package org.slf4j.impl;
1
2 import java.io.PrintStream;
3
4 /**
5 * This class encapsulates the user's choice of output target.
6 *
7 * @author Ceki G&uuml;lc&uuml;
8 *
9 */
10 class OutputChoice {
11
12 enum OutputChoiceType {
13 SYS_OUT, CACHED_SYS_OUT, SYS_ERR, CACHED_SYS_ERR, FILE;
14 }
15
16 final OutputChoiceType outputChoiceType;
17 final PrintStream targetPrintStream;
18
19 OutputChoice(OutputChoiceType outputChoiceType) {
20 if (outputChoiceType == OutputChoiceType.FILE) {
21 throw new IllegalArgumentException();
22 }
23 this.outputChoiceType = outputChoiceType;
24 if (outputChoiceType == OutputChoiceType.CACHED_SYS_OUT) {
25 this.targetPrintStream = System.out;
26 } else if (outputChoiceType == OutputChoiceType.CACHED_SYS_ERR) {
27 this.targetPrintStream = System.err;
28 } else {
29 this.targetPrintStream = null;
30 }
31 }
32
33 OutputChoice(PrintStream printStream) {
34 this.outputChoiceType = OutputChoiceType.FILE;
35 this.targetPrintStream = printStream;
36 }
37
38 PrintStream getTargetPrintStream() {
39 switch (outputChoiceType) {
40 case SYS_OUT:
41 return System.out;
42 case SYS_ERR:
43 return System.err;
44 case CACHED_SYS_ERR:
45 case CACHED_SYS_OUT:
46 case FILE:
47 return targetPrintStream;
48 default:
49 throw new IllegalArgumentException();
50 }
51
52 }
53
54 }
2323 */
2424 package org.slf4j.impl;
2525
26 import java.io.FileNotFoundException;
27 import java.io.FileOutputStream;
28 import java.io.InputStream;
2926 import java.io.PrintStream;
30 import java.security.AccessController;
31 import java.security.PrivilegedAction;
32 import java.text.DateFormat;
33 import java.text.SimpleDateFormat;
3427 import java.util.Date;
35 import java.util.Properties;
3628
3729 import org.slf4j.Logger;
3830 import org.slf4j.event.LoggingEvent;
3931 import org.slf4j.helpers.FormattingTuple;
4032 import org.slf4j.helpers.MarkerIgnoringBase;
4133 import org.slf4j.helpers.MessageFormatter;
42 import org.slf4j.helpers.Util;
4334 import org.slf4j.spi.LocationAwareLogger;
4435
4536 /**
46 * <p>Simple implementation of {@link Logger} that sends all enabled log messages,
47 * for all defined loggers, to the console ({@code System.err}).
48 * The following system properties are supported to configure the behavior of this logger:</p>
37 * <p>
38 * Simple implementation of {@link Logger} that sends all enabled log messages,
39 * for all defined loggers, to the console ({@code System.err}). The following
40 * system properties are supported to configure the behavior of this logger:
41 * </p>
4942 *
5043 * <ul>
51 * <li><code>org.slf4j.simpleLogger.logFile</code> - The output target which can be the <em>path</em> to a file, or
52 * the special values "System.out" and "System.err". Default is "System.err".
53 *
54 * <li><code>org.slf4j.simpleLogger.defaultLogLevel</code> - Default log level for all instances of SimpleLogger.
55 * Must be one of ("trace", "debug", "info", "warn", "error" or "off"). If not specified, defaults to "info". </li>
56 *
57 * <li><code>org.slf4j.simpleLogger.log.<em>a.b.c</em></code> - Logging detail level for a SimpleLogger instance
58 * named "a.b.c". Right-side value must be one of "trace", "debug", "info", "warn", "error" or "off". When a SimpleLogger
59 * named "a.b.c" is initialized, its level is assigned from this property. If unspecified, the level of nearest parent
60 * logger will be used, and if none is set, then the value specified by
44 * <li><code>org.slf4j.simpleLogger.logFile</code> - The output target which can
45 * be the <em>path</em> to a file, or the special values "System.out" and
46 * "System.err". Default is "System.err".</li>
47 *
48 * <li><code>org.slf4j.simpleLogger.cacheOutputStream</code> - If the output
49 * target is set to "System.out" or "System.err" (see preceding entry), by
50 * default, logs will be output to the latest value referenced by
51 * <code>System.out/err</code> variables. By setting this
52 * parameter to true, the output stream will be cached, i.e. assigned once at
53 * initialization time and re-used independently of the current value referenced by
54 * <code>System.out/err</code>.
55 * </li>
56 *
57 * <li><code>org.slf4j.simpleLogger.defaultLogLevel</code> - Default log level
58 * for all instances of SimpleLogger. Must be one of ("trace", "debug", "info",
59 * "warn", "error" or "off"). If not specified, defaults to "info".</li>
60 *
61 * <li><code>org.slf4j.simpleLogger.log.<em>a.b.c</em></code> - Logging detail
62 * level for a SimpleLogger instance named "a.b.c". Right-side value must be one
63 * of "trace", "debug", "info", "warn", "error" or "off". When a SimpleLogger
64 * named "a.b.c" is initialized, its level is assigned from this property. If
65 * unspecified, the level of nearest parent logger will be used, and if none is
66 * set, then the value specified by
6167 * <code>org.slf4j.simpleLogger.defaultLogLevel</code> will be used.</li>
6268 *
63 * <li><code>org.slf4j.simpleLogger.showDateTime</code> - Set to <code>true</code> if you want the current date and
64 * time to be included in output messages. Default is <code>false</code></li>
65 *
66 * <li><code>org.slf4j.simpleLogger.dateTimeFormat</code> - The date and time format to be used in the output messages.
67 * The pattern describing the date and time format is defined by
68 * <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html"><code>SimpleDateFormat</code></a>.
69 * If the format is not specified or is invalid, the number of milliseconds since start up will be output. </li>
70 *
71 * <li><code>org.slf4j.simpleLogger.showThreadName</code> -Set to <code>true</code> if you want to output the current
72 * thread name. Defaults to <code>true</code>.</li>
73 *
74 * <li><code>org.slf4j.simpleLogger.showLogName</code> - Set to <code>true</code> if you want the Logger instance name
75 * to be included in output messages. Defaults to <code>true</code>.</li>
76 *
77 * <li><code>org.slf4j.simpleLogger.showShortLogName</code> - Set to <code>true</code> if you want the last component
78 * of the name to be included in output messages. Defaults to <code>false</code>.</li>
79 *
80 * <li><code>org.slf4j.simpleLogger.levelInBrackets</code> - Should the level string be output in brackets? Defaults
81 * to <code>false</code>.</li>
82 *
83 * <li><code>org.slf4j.simpleLogger.warnLevelString</code> - The string value output for the warn level. Defaults
84 * to <code>WARN</code>.</li>
85
69 * <li><code>org.slf4j.simpleLogger.showDateTime</code> - Set to
70 * <code>true</code> if you want the current date and time to be included in
71 * output messages. Default is <code>false</code></li>
72 *
73 * <li><code>org.slf4j.simpleLogger.dateTimeFormat</code> - The date and time
74 * format to be used in the output messages. The pattern describing the date and
75 * time format is defined by <a href=
76 * "http://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html">
77 * <code>SimpleDateFormat</code></a>. If the format is not specified or is
78 * invalid, the number of milliseconds since start up will be output.</li>
79 *
80 * <li><code>org.slf4j.simpleLogger.showThreadName</code> -Set to
81 * <code>true</code> if you want to output the current thread name. Defaults to
82 * <code>true</code>.</li>
83 *
84 * <li><code>org.slf4j.simpleLogger.showLogName</code> - Set to
85 * <code>true</code> if you want the Logger instance name to be included in
86 * output messages. Defaults to <code>true</code>.</li>
87 *
88 * <li><code>org.slf4j.simpleLogger.showShortLogName</code> - Set to
89 * <code>true</code> if you want the last component of the name to be included
90 * in output messages. Defaults to <code>false</code>.</li>
91 *
92 * <li><code>org.slf4j.simpleLogger.levelInBrackets</code> - Should the level
93 * string be output in brackets? Defaults to <code>false</code>.</li>
94 *
95 * <li><code>org.slf4j.simpleLogger.warnLevelString</code> - The string value
96 * output for the warn level. Defaults to <code>WARN</code>.</li>
97 *
8698 * </ul>
8799 *
88 * <p>In addition to looking for system properties with the names specified above, this implementation also checks for
89 * a class loader resource named <code>"simplelogger.properties"</code>, and includes any matching definitions
90 * from this resource (if it exists).</p>
91 *
92 * <p>With no configuration, the default output includes the relative time in milliseconds, thread name, the level,
93 * logger name, and the message followed by the line separator for the host. In log4j terms it amounts to the "%r [%t]
94 * %level %logger - %m%n" pattern. </p>
95 * <p>Sample output follows.</p>
100 * <p>
101 * In addition to looking for system properties with the names specified above,
102 * this implementation also checks for a class loader resource named
103 * <code>"simplelogger.properties"</code>, and includes any matching definitions
104 * from this resource (if it exists).
105 * </p>
106 *
107 * <p>
108 * With no configuration, the default output includes the relative time in
109 * milliseconds, thread name, the level, logger name, and the message followed
110 * by the line separator for the host. In log4j terms it amounts to the "%r [%t]
111 * %level %logger - %m%n" pattern.
112 * </p>
113 * <p>
114 * Sample output follows.
115 * </p>
116 *
96117 * <pre>
97118 * 176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
98119 * 225 [main] INFO examples.SortAlgo - Entered the sort method.
106127 * 467 [main] INFO examples.Sort - Exiting main method.
107128 * </pre>
108129 *
109 * <p>This implementation is heavily inspired by
110 * <a href="http://commons.apache.org/logging/">Apache Commons Logging</a>'s SimpleLog.</p>
130 * <p>
131 * This implementation is heavily inspired by
132 * <a href="http://commons.apache.org/logging/">Apache Commons Logging</a>'s
133 * SimpleLog.
134 * </p>
111135 *
112136 * @author Ceki G&uuml;lc&uuml;
113 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
137 * @author Scott Sanders
114138 * @author Rod Waldhoff
115139 * @author Robert Burrell Donkin
116140 * @author C&eacute;drik LIME
118142 public class SimpleLogger extends MarkerIgnoringBase {
119143
120144 private static final long serialVersionUID = -632788891211436180L;
121 private static final String CONFIGURATION_FILE = "simplelogger.properties";
122145
123146 private static long START_TIME = System.currentTimeMillis();
124 private static final Properties SIMPLE_LOGGER_PROPS = new Properties();
125
126 private static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT;
127 private static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT;
128 private static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT;
129 private static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT;
130 private static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT;
131 // The OFF level can only be used in configuration files to disable logging. It has
147
148 protected static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT;
149 protected static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT;
150 protected static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT;
151 protected static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT;
152 protected static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT;
153 // The OFF level can only be used in configuration files to disable logging.
154 // It has
132155 // no printing method associated with it in o.s.Logger interface.
133 private static final int LOG_LEVEL_OFF = LOG_LEVEL_ERROR + 10;
156 protected static final int LOG_LEVEL_OFF = LOG_LEVEL_ERROR + 10;
134157
135158 private static boolean INITIALIZED = false;
136
137 private static int DEFAULT_LOG_LEVEL = LOG_LEVEL_INFO;
138 private static boolean SHOW_DATE_TIME = false;
139 private static String DATE_TIME_FORMAT_STR = null;
140 private static DateFormat DATE_FORMATTER = null;
141 private static boolean SHOW_THREAD_NAME = true;
142 private static boolean SHOW_LOG_NAME = true;
143 private static boolean SHOW_SHORT_LOG_NAME = false;
144 private static String LOG_FILE = "System.err";
145 private static PrintStream TARGET_STREAM = null;
146 private static boolean LEVEL_IN_BRACKETS = false;
147 private static String WARN_LEVEL_STRING = "WARN";
148
149 /** All system properties used by <code>SimpleLogger</code> start with this prefix */
150 public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger.";
151
152 public static final String DEFAULT_LOG_LEVEL_KEY = SYSTEM_PREFIX + "defaultLogLevel";
153 public static final String SHOW_DATE_TIME_KEY = SYSTEM_PREFIX + "showDateTime";
154 public static final String DATE_TIME_FORMAT_KEY = SYSTEM_PREFIX + "dateTimeFormat";
155 public static final String SHOW_THREAD_NAME_KEY = SYSTEM_PREFIX + "showThreadName";
156 public static final String SHOW_LOG_NAME_KEY = SYSTEM_PREFIX + "showLogName";
157 public static final String SHOW_SHORT_LOG_NAME_KEY = SYSTEM_PREFIX + "showShortLogName";
158 public static final String LOG_FILE_KEY = SYSTEM_PREFIX + "logFile";
159 public static final String LEVEL_IN_BRACKETS_KEY = SYSTEM_PREFIX + "levelInBrackets";
160 public static final String WARN_LEVEL_STRING_KEY = SYSTEM_PREFIX + "warnLevelString";
161
162 public static final String LOG_KEY_PREFIX = SYSTEM_PREFIX + "log.";
163
164 private static String getStringProperty(String name) {
165 String prop = null;
166 try {
167 prop = System.getProperty(name);
168 } catch (SecurityException e) {
169 ; // Ignore
170 }
171 return (prop == null) ? SIMPLE_LOGGER_PROPS.getProperty(name) : prop;
172 }
173
174 private static String getStringProperty(String name, String defaultValue) {
175 String prop = getStringProperty(name);
176 return (prop == null) ? defaultValue : prop;
177 }
178
179 private static boolean getBooleanProperty(String name, boolean defaultValue) {
180 String prop = getStringProperty(name);
181 return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop);
182 }
159 static SimpleLoggerConfiguration CONFIG_PARAMS = null;
183160
184161 static void lazyInit() {
185162 if (INITIALIZED) {
188165 INITIALIZED = true;
189166 init();
190167 }
191
168
169 // external software might be invoking this method directly. Do not rename
170 // or change its semantics.
192171 static void init() {
193 loadProperties();
194
195 String defaultLogLevelString = getStringProperty(DEFAULT_LOG_LEVEL_KEY, null);
196 if (defaultLogLevelString != null)
197 DEFAULT_LOG_LEVEL = stringToLevel(defaultLogLevelString);
198
199 SHOW_LOG_NAME = getBooleanProperty(SHOW_LOG_NAME_KEY, SHOW_LOG_NAME);
200 SHOW_SHORT_LOG_NAME = getBooleanProperty(SHOW_SHORT_LOG_NAME_KEY, SHOW_SHORT_LOG_NAME);
201 SHOW_DATE_TIME = getBooleanProperty(SHOW_DATE_TIME_KEY, SHOW_DATE_TIME);
202 SHOW_THREAD_NAME = getBooleanProperty(SHOW_THREAD_NAME_KEY, SHOW_THREAD_NAME);
203 DATE_TIME_FORMAT_STR = getStringProperty(DATE_TIME_FORMAT_KEY, DATE_TIME_FORMAT_STR);
204 LEVEL_IN_BRACKETS = getBooleanProperty(LEVEL_IN_BRACKETS_KEY, LEVEL_IN_BRACKETS);
205 WARN_LEVEL_STRING = getStringProperty(WARN_LEVEL_STRING_KEY, WARN_LEVEL_STRING);
206
207 LOG_FILE = getStringProperty(LOG_FILE_KEY, LOG_FILE);
208 TARGET_STREAM = computeTargetStream(LOG_FILE);
209
210 if (DATE_TIME_FORMAT_STR != null) {
211 try {
212 DATE_FORMATTER = new SimpleDateFormat(DATE_TIME_FORMAT_STR);
213 } catch (IllegalArgumentException e) {
214 Util.report("Bad date format in " + CONFIGURATION_FILE + "; will output relative time", e);
215 }
216 }
217 }
218
219 private static PrintStream computeTargetStream(String logFile) {
220 if ("System.err".equalsIgnoreCase(logFile))
221 return System.err;
222 else if ("System.out".equalsIgnoreCase(logFile)) {
223 return System.out;
224 } else {
225 try {
226 FileOutputStream fos = new FileOutputStream(logFile);
227 PrintStream printStream = new PrintStream(fos);
228 return printStream;
229 } catch (FileNotFoundException e) {
230 Util.report("Could not open [" + logFile + "]. Defaulting to System.err", e);
231 return System.err;
232 }
233 }
234 }
235
236 private static void loadProperties() {
237 // Add props from the resource simplelogger.properties
238 InputStream in = AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
239 public InputStream run() {
240 ClassLoader threadCL = Thread.currentThread().getContextClassLoader();
241 if (threadCL != null) {
242 return threadCL.getResourceAsStream(CONFIGURATION_FILE);
243 } else {
244 return ClassLoader.getSystemResourceAsStream(CONFIGURATION_FILE);
245 }
246 }
247 });
248 if (null != in) {
249 try {
250 SIMPLE_LOGGER_PROPS.load(in);
251 } catch (java.io.IOException e) {
252 // ignored
253 } finally {
254 try {
255 in.close();
256 } catch (java.io.IOException e) {
257 // ignored
258 }
259 }
260 }
172 CONFIG_PARAMS = new SimpleLoggerConfiguration();
173 CONFIG_PARAMS.init();
261174 }
262175
263176 /** The current log level */
266179 private transient String shortLogName = null;
267180
268181 /**
182 * All system properties used by <code>SimpleLogger</code> start with this
183 * prefix
184 */
185 public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger.";
186
187 public static final String LOG_KEY_PREFIX = SimpleLogger.SYSTEM_PREFIX + "log.";
188
189 public static final String CACHE_OUTPUT_STREAM_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "cacheOutputStream";
190
191 public static final String WARN_LEVEL_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "warnLevelString";
192
193 public static final String LEVEL_IN_BRACKETS_KEY = SimpleLogger.SYSTEM_PREFIX + "levelInBrackets";
194
195 public static final String LOG_FILE_KEY = SimpleLogger.SYSTEM_PREFIX + "logFile";
196
197 public static final String SHOW_SHORT_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showShortLogName";
198
199 public static final String SHOW_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showLogName";
200
201 public static final String SHOW_THREAD_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showThreadName";
202
203 public static final String DATE_TIME_FORMAT_KEY = SimpleLogger.SYSTEM_PREFIX + "dateTimeFormat";
204
205 public static final String SHOW_DATE_TIME_KEY = SimpleLogger.SYSTEM_PREFIX + "showDateTime";
206
207 public static final String DEFAULT_LOG_LEVEL_KEY = SimpleLogger.SYSTEM_PREFIX + "defaultLogLevel";
208
209 /**
269210 * Package access allows only {@link SimpleLoggerFactory} to instantiate
270211 * SimpleLogger instances.
271212 */
274215
275216 String levelString = recursivelyComputeLevelString();
276217 if (levelString != null) {
277 this.currentLogLevel = stringToLevel(levelString);
218 this.currentLogLevel = SimpleLoggerConfiguration.stringToLevel(levelString);
278219 } else {
279 this.currentLogLevel = DEFAULT_LOG_LEVEL;
220 this.currentLogLevel = CONFIG_PARAMS.defaultLogLevel;
280221 }
281222 }
282223
286227 int indexOfLastDot = tempName.length();
287228 while ((levelString == null) && (indexOfLastDot > -1)) {
288229 tempName = tempName.substring(0, indexOfLastDot);
289 levelString = getStringProperty(LOG_KEY_PREFIX + tempName, null);
230 levelString = CONFIG_PARAMS.getStringProperty(SimpleLogger.LOG_KEY_PREFIX + tempName, null);
290231 indexOfLastDot = String.valueOf(tempName).lastIndexOf(".");
291232 }
292233 return levelString;
293234 }
294235
295 private static int stringToLevel(String levelStr) {
296 if ("trace".equalsIgnoreCase(levelStr)) {
297 return LOG_LEVEL_TRACE;
298 } else if ("debug".equalsIgnoreCase(levelStr)) {
299 return LOG_LEVEL_DEBUG;
300 } else if ("info".equalsIgnoreCase(levelStr)) {
301 return LOG_LEVEL_INFO;
302 } else if ("warn".equalsIgnoreCase(levelStr)) {
303 return LOG_LEVEL_WARN;
304 } else if ("error".equalsIgnoreCase(levelStr)) {
305 return LOG_LEVEL_ERROR;
306 } else if ("off".equalsIgnoreCase(levelStr)) {
307 return LOG_LEVEL_OFF;
308 }
309 // assume INFO by default
310 return LOG_LEVEL_INFO;
311 }
312
313 /**
314 * This is our internal implementation for logging regular (non-parameterized)
315 * log messages.
236 /**
237 * This is our internal implementation for logging regular
238 * (non-parameterized) log messages.
316239 *
317 * @param level One of the LOG_LEVEL_XXX constants defining the log level
318 * @param message The message itself
319 * @param t The exception whose stack trace should be logged
240 * @param level
241 * One of the LOG_LEVEL_XXX constants defining the log level
242 * @param message
243 * The message itself
244 * @param t
245 * The exception whose stack trace should be logged
320246 */
321247 private void log(int level, String message, Throwable t) {
322248 if (!isLevelEnabled(level)) {
326252 StringBuilder buf = new StringBuilder(32);
327253
328254 // Append date-time if so configured
329 if (SHOW_DATE_TIME) {
330 if (DATE_FORMATTER != null) {
255 if (CONFIG_PARAMS.showDateTime) {
256 if (CONFIG_PARAMS.dateFormatter != null) {
331257 buf.append(getFormattedDate());
332258 buf.append(' ');
333259 } else {
337263 }
338264
339265 // Append current thread name if so configured
340 if (SHOW_THREAD_NAME) {
266 if (CONFIG_PARAMS.showThreadName) {
341267 buf.append('[');
342268 buf.append(Thread.currentThread().getName());
343269 buf.append("] ");
344270 }
345271
346 if (LEVEL_IN_BRACKETS)
272 if (CONFIG_PARAMS.levelInBrackets)
347273 buf.append('[');
348274
349275 // Append a readable representation of the log level
350 switch (level) {
351 case LOG_LEVEL_TRACE:
352 buf.append("TRACE");
353 break;
354 case LOG_LEVEL_DEBUG:
355 buf.append("DEBUG");
356 break;
357 case LOG_LEVEL_INFO:
358 buf.append("INFO");
359 break;
360 case LOG_LEVEL_WARN:
361 buf.append(WARN_LEVEL_STRING);
362 break;
363 case LOG_LEVEL_ERROR:
364 buf.append("ERROR");
365 break;
366 }
367 if (LEVEL_IN_BRACKETS)
276 String levelStr = renderLevel(level);
277 buf.append(levelStr);
278 if (CONFIG_PARAMS.levelInBrackets)
368279 buf.append(']');
369280 buf.append(' ');
370281
371282 // Append the name of the log instance if so configured
372 if (SHOW_SHORT_LOG_NAME) {
283 if (CONFIG_PARAMS.showShortLogName) {
373284 if (shortLogName == null)
374285 shortLogName = computeShortName();
375286 buf.append(String.valueOf(shortLogName)).append(" - ");
376 } else if (SHOW_LOG_NAME) {
287 } else if (CONFIG_PARAMS.showLogName) {
377288 buf.append(String.valueOf(name)).append(" - ");
378289 }
379290
384295
385296 }
386297
298 protected String renderLevel(int level) {
299 switch (level) {
300 case LOG_LEVEL_TRACE:
301 return "TRACE";
302 case LOG_LEVEL_DEBUG:
303 return ("DEBUG");
304 case LOG_LEVEL_INFO:
305 return "INFO";
306 case LOG_LEVEL_WARN:
307 return CONFIG_PARAMS.warnLevelString;
308 case LOG_LEVEL_ERROR:
309 return "ERROR";
310 }
311 throw new IllegalStateException("Unrecognized level [" + level + "]");
312 }
313
387314 void write(StringBuilder buf, Throwable t) {
388 TARGET_STREAM.println(buf.toString());
315 PrintStream targetStream = CONFIG_PARAMS.outputChoice.getTargetPrintStream();
316
317 targetStream.println(buf.toString());
318 writeThrowable(t, targetStream);
319 targetStream.flush();
320 }
321
322 protected void writeThrowable(Throwable t, PrintStream targetStream) {
389323 if (t != null) {
390 t.printStackTrace(TARGET_STREAM);
391 }
392 TARGET_STREAM.flush();
324 t.printStackTrace(targetStream);
325 }
393326 }
394327
395328 private String getFormattedDate() {
396329 Date now = new Date();
397330 String dateText;
398 synchronized (DATE_FORMATTER) {
399 dateText = DATE_FORMATTER.format(now);
331 synchronized (CONFIG_PARAMS.dateFormatter) {
332 dateText = CONFIG_PARAMS.dateFormatter.format(now);
400333 }
401334 return dateText;
402335 }
426359 *
427360 * @param level
428361 * @param format
429 * @param arguments a list of 3 ore more arguments
362 * @param arguments
363 * a list of 3 ore more arguments
430364 */
431365 private void formatAndLog(int level, String format, Object... arguments) {
432366 if (!isLevelEnabled(level)) {
439373 /**
440374 * Is the given log level currently enabled?
441375 *
442 * @param logLevel is this level enabled?
376 * @param logLevel
377 * is this level enabled?
443378 */
444379 protected boolean isLevelEnabled(int logLevel) {
445380 // log level are numerically ordered so can use simple numeric
453388 }
454389
455390 /**
456 * A simple implementation which logs messages of level TRACE according
457 * to the format outlined above.
391 * A simple implementation which logs messages of level TRACE according to
392 * the format outlined above.
458393 */
459394 public void trace(String msg) {
460395 log(LOG_LEVEL_TRACE, msg, null);
495430 }
496431
497432 /**
498 * A simple implementation which logs messages of level DEBUG according
499 * to the format outlined above.
433 * A simple implementation which logs messages of level DEBUG according to
434 * the format outlined above.
500435 */
501436 public void debug(String msg) {
502437 log(LOG_LEVEL_DEBUG, msg, null);
537472 }
538473
539474 /**
540 * A simple implementation which logs messages of level INFO according
541 * to the format outlined above.
475 * A simple implementation which logs messages of level INFO according to
476 * the format outlined above.
542477 */
543478 public void info(String msg) {
544479 log(LOG_LEVEL_INFO, msg, null);
579514 }
580515
581516 /**
582 * A simple implementation which always logs messages of level WARN according
583 * to the format outlined above.
517 * A simple implementation which always logs messages of level WARN
518 * according to the format outlined above.
584519 */
585520 public void warn(String msg) {
586521 log(LOG_LEVEL_WARN, msg, null);
621556 }
622557
623558 /**
624 * A simple implementation which always logs messages of level ERROR according
625 * to the format outlined above.
559 * A simple implementation which always logs messages of level ERROR
560 * according to the format outlined above.
626561 */
627562 public void error(String msg) {
628563 log(LOG_LEVEL_ERROR, msg, null);
0 package org.slf4j.impl;
1
2 import java.io.FileNotFoundException;
3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.io.PrintStream;
6 import java.security.AccessController;
7 import java.security.PrivilegedAction;
8 import java.text.DateFormat;
9 import java.text.SimpleDateFormat;
10 import java.util.Properties;
11
12 import org.slf4j.helpers.Util;
13 import org.slf4j.impl.OutputChoice.OutputChoiceType;
14
15 /**
16 * This class holds configuration values for {@link SimpleLogger}. The
17 * values are computed at runtime. See {@link SimpleLogger} documentation for
18 * more information.
19 *
20 *
21 * @author Ceki G&uuml;lc&uuml;
22 * @author Scott Sanders
23 * @author Rod Waldhoff
24 * @author Robert Burrell Donkin
25 * @author C&eacute;drik LIME
26 *
27 * @since 1.7.25
28 */
29 public class SimpleLoggerConfiguration {
30
31 private static final String CONFIGURATION_FILE = "simplelogger.properties";
32
33 static int DEFAULT_LOG_LEVEL_DEFAULT = SimpleLogger.LOG_LEVEL_INFO;
34 int defaultLogLevel = DEFAULT_LOG_LEVEL_DEFAULT;
35
36 private static final boolean SHOW_DATE_TIME_DEFAULT = false;
37 boolean showDateTime = SHOW_DATE_TIME_DEFAULT;
38
39 private static final String DATE_TIME_FORMAT_STR_DEFAULT = null;
40 private static String dateTimeFormatStr = DATE_TIME_FORMAT_STR_DEFAULT;
41
42 DateFormat dateFormatter = null;
43
44 private static final boolean SHOW_THREAD_NAME_DEFAULT = true;
45 boolean showThreadName = SHOW_THREAD_NAME_DEFAULT;
46
47 final static boolean SHOW_LOG_NAME_DEFAULT = true;
48 boolean showLogName = SHOW_LOG_NAME_DEFAULT;
49
50 private static final boolean SHOW_SHORT_LOG_NAME_DEFAULT = false;
51 boolean showShortLogName = SHOW_SHORT_LOG_NAME_DEFAULT;
52
53 private static final boolean LEVEL_IN_BRACKETS_DEFAULT = false;
54 boolean levelInBrackets = LEVEL_IN_BRACKETS_DEFAULT;
55
56 private static String LOG_FILE_DEFAULT = "System.err";
57 private String logFile = LOG_FILE_DEFAULT;
58 OutputChoice outputChoice = null;
59
60 private static final boolean CACHE_OUTPUT_STREAM_DEFAULT = false;
61 private boolean cacheOutputStream = CACHE_OUTPUT_STREAM_DEFAULT;
62
63 private static final String WARN_LEVELS_STRING_DEFAULT = "WARN";
64 String warnLevelString = WARN_LEVELS_STRING_DEFAULT;
65
66 private final Properties properties = new Properties();
67
68 void init() {
69 loadProperties();
70
71 String defaultLogLevelString = getStringProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, null);
72 if (defaultLogLevelString != null)
73 defaultLogLevel = stringToLevel(defaultLogLevelString);
74
75 showLogName = getBooleanProperty(SimpleLogger.SHOW_LOG_NAME_KEY, SimpleLoggerConfiguration.SHOW_LOG_NAME_DEFAULT);
76 showShortLogName = getBooleanProperty(SimpleLogger.SHOW_SHORT_LOG_NAME_KEY, SHOW_SHORT_LOG_NAME_DEFAULT);
77 showDateTime = getBooleanProperty(SimpleLogger.SHOW_DATE_TIME_KEY, SHOW_DATE_TIME_DEFAULT);
78 showThreadName = getBooleanProperty(SimpleLogger.SHOW_THREAD_NAME_KEY, SHOW_THREAD_NAME_DEFAULT);
79 dateTimeFormatStr = getStringProperty(SimpleLogger.DATE_TIME_FORMAT_KEY, DATE_TIME_FORMAT_STR_DEFAULT);
80 levelInBrackets = getBooleanProperty(SimpleLogger.LEVEL_IN_BRACKETS_KEY, LEVEL_IN_BRACKETS_DEFAULT);
81 warnLevelString = getStringProperty(SimpleLogger.WARN_LEVEL_STRING_KEY, WARN_LEVELS_STRING_DEFAULT);
82
83 logFile = getStringProperty(SimpleLogger.LOG_FILE_KEY, logFile);
84
85 cacheOutputStream = getBooleanProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, CACHE_OUTPUT_STREAM_DEFAULT);
86 outputChoice = computeOutputChoice(logFile, cacheOutputStream);
87
88 if (dateTimeFormatStr != null) {
89 try {
90 dateFormatter = new SimpleDateFormat(dateTimeFormatStr);
91 } catch (IllegalArgumentException e) {
92 Util.report("Bad date format in " + CONFIGURATION_FILE + "; will output relative time", e);
93 }
94 }
95 }
96
97 private void loadProperties() {
98 // Add props from the resource simplelogger.properties
99 InputStream in = AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
100 public InputStream run() {
101 ClassLoader threadCL = Thread.currentThread().getContextClassLoader();
102 if (threadCL != null) {
103 return threadCL.getResourceAsStream(CONFIGURATION_FILE);
104 } else {
105 return ClassLoader.getSystemResourceAsStream(CONFIGURATION_FILE);
106 }
107 }
108 });
109 if (null != in) {
110 try {
111 properties.load(in);
112 } catch (java.io.IOException e) {
113 // ignored
114 } finally {
115 try {
116 in.close();
117 } catch (java.io.IOException e) {
118 // ignored
119 }
120 }
121 }
122 }
123
124 String getStringProperty(String name, String defaultValue) {
125 String prop = getStringProperty(name);
126 return (prop == null) ? defaultValue : prop;
127 }
128
129 boolean getBooleanProperty(String name, boolean defaultValue) {
130 String prop = getStringProperty(name);
131 return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop);
132 }
133
134 String getStringProperty(String name) {
135 String prop = null;
136 try {
137 prop = System.getProperty(name);
138 } catch (SecurityException e) {
139 ; // Ignore
140 }
141 return (prop == null) ? properties.getProperty(name) : prop;
142 }
143
144 static int stringToLevel(String levelStr) {
145 if ("trace".equalsIgnoreCase(levelStr)) {
146 return SimpleLogger.LOG_LEVEL_TRACE;
147 } else if ("debug".equalsIgnoreCase(levelStr)) {
148 return SimpleLogger.LOG_LEVEL_DEBUG;
149 } else if ("info".equalsIgnoreCase(levelStr)) {
150 return SimpleLogger.LOG_LEVEL_INFO;
151 } else if ("warn".equalsIgnoreCase(levelStr)) {
152 return SimpleLogger.LOG_LEVEL_WARN;
153 } else if ("error".equalsIgnoreCase(levelStr)) {
154 return SimpleLogger.LOG_LEVEL_ERROR;
155 } else if ("off".equalsIgnoreCase(levelStr)) {
156 return SimpleLogger.LOG_LEVEL_OFF;
157 }
158 // assume INFO by default
159 return SimpleLogger.LOG_LEVEL_INFO;
160 }
161
162 private static OutputChoice computeOutputChoice(String logFile, boolean cacheOutputStream) {
163 if ("System.err".equalsIgnoreCase(logFile))
164 if (cacheOutputStream)
165 return new OutputChoice(OutputChoiceType.CACHED_SYS_ERR);
166 else
167 return new OutputChoice(OutputChoiceType.SYS_ERR);
168 else if ("System.out".equalsIgnoreCase(logFile)) {
169 if (cacheOutputStream)
170 return new OutputChoice(OutputChoiceType.CACHED_SYS_OUT);
171 else
172 return new OutputChoice(OutputChoiceType.SYS_OUT);
173 } else {
174 try {
175 FileOutputStream fos = new FileOutputStream(logFile);
176 PrintStream printStream = new PrintStream(fos);
177 return new OutputChoice(printStream);
178 } catch (FileNotFoundException e) {
179 Util.report("Could not open [" + logFile + "]. Defaulting to System.err", e);
180 return new OutputChoice(OutputChoiceType.SYS_ERR);
181 }
182 }
183 }
184
185 }
2323 */
2424 package org.slf4j.impl;
2525
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertFalse;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.assertTrue;
30
31 import java.io.ByteArrayOutputStream;
32 import java.io.PrintStream;
33
2634 import org.junit.After;
2735 import org.junit.Before;
2836 import org.junit.Test;
2937
30 import static org.junit.Assert.*;
31
3238 public class SimpleLoggerTest {
3339
3440 String A_KEY = SimpleLogger.LOG_KEY_PREFIX + "a";
41 PrintStream original = System.out;
42 ByteArrayOutputStream bout = new ByteArrayOutputStream();
43 PrintStream replacement = new PrintStream(bout);
3544
3645 @Before
3746 public void before() {
4150 @After
4251 public void after() {
4352 System.clearProperty(A_KEY);
53 System.clearProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY);
54 System.setErr(original);
4455 }
4556
4657 @Test
5263 @Test
5364 public void offLevel() {
5465 System.setProperty(A_KEY, "off");
66 SimpleLogger.init();
5567 SimpleLogger simpleLogger = new SimpleLogger("a");
5668 assertEquals("off", simpleLogger.recursivelyComputeLevelString());
5769 assertFalse(simpleLogger.isErrorEnabled());
5870 }
59
71
6072 @Test
6173 public void loggerNameWithNoDots_WithLevel() {
74 SimpleLogger.init();
6275 SimpleLogger simpleLogger = new SimpleLogger("a");
76
6377 assertEquals("info", simpleLogger.recursivelyComputeLevelString());
6478 }
6579
8195 assertNull(simpleLogger.recursivelyComputeLevelString());
8296 }
8397
98 @Test
99 public void checkUseOfLastSystemStreamReference() {
100 SimpleLogger.init();
101 SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName());
102
103 System.setErr(replacement);
104 simpleLogger.info("hello");
105 replacement.flush();
106 assertTrue(bout.toString().contains("INFO org.slf4j.impl.SimpleLoggerTest - hello"));
107 }
108
109 @Test
110 public void checkUseOfCachedOutputStream() {
111 System.setErr(replacement);
112 System.setProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, "true");
113 SimpleLogger.init();
114 SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName());
115 // change reference to original before logging
116 System.setErr(original);
117
118 simpleLogger.info("hello");
119 replacement.flush();
120 assertTrue(bout.toString().contains("INFO org.slf4j.impl.SimpleLoggerTest - hello"));
121 }
84122 }
66 <parent>
77 <groupId>org.slf4j</groupId>
88 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.22</version>
9 <version>1.7.25</version>
1010 </parent>
1111
1212 <artifactId>slf4j-site</artifactId>