Codebase list libslf4j-java / 382251d
Merge tag 'upstream/1.7.12' Upstream version 1.7.12 Emmanuel Bourg 8 years ago
283 changed file(s) with 28914 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 Copyright (c) 2004-2014 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
23
0 # About SLF4J
1 The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.
2 More information can be found on the [SLF4J website](http://www.slf4j.org).
3 # Build Status
4 [![Build Status](https://travis-ci.org/qos-ch/slf4j.png)](https://travis-ci.org/qos-ch/slf4j)
5
6 # How to contribute pull requests
7 If you are interested in improving SLF4J, great! The SLF4J community looks forward to your contribution. Please follow this process:
8
9 1. Start a discussion on the [slf4j-dev mailing list](http://www.slf4j.org/mailing-lists.html) about your proposed change. Alternately file a [bug report](http://www.slf4j.org/bug-reporting.html).
10 2. Fork qos-ch/slf4j. Ideally, create a new branch from your fork for your contribution to make it easier to merge your changes back.
11 3. Make your changes on the branch you hopefuly created in Step 2. Be sure that your code passes existing unit tests. Please add unit tests for your work if appropriate. It usually is.
12 4. Push your changes to your fork/branch in github. Don't push it to your master! If you do it will make it harder to submit new changes later.
13 5. Submit a pull request to SLF4J from from your commit page on github.
0 <project name="integration" default="testAll" basedir=".">
1
2 <!--
3 This build file is usually run indirectly via Maven.
4
5 When running this build file through Ant directly, you must
6 define the currentVersion property on the command line, e.g.:
7
8 ant -DcurrentVersion=1.5.4-SNAPSHOT
9 -->
10
11 <echo message="compile classpath: ${compile_classpath}" />
12 <echo message="runtime classpath: ${runtime_classpath}" />
13 <echo message="test classpath: ${test_classpath}" />
14 <echo message="plugin classpath: ${plugin_classpath}" />
15
16
17 <path id="path142Binding">
18 <pathelement location="target/test-classes/" />
19 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
20 <pathelement location="./lib/slf4j-simple-1.4.2.jar" />
21 </path >
22
23 <path id="path150Binding">
24 <pathelement location="target/test-classes/" />
25 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
26 <pathelement location="./lib/slf4j-simple-1.5.0.jar" />
27 </path >
28
29 <path id="path1511API">
30 <pathelement location="target/test-classes/" />
31 <pathelement location="./lib/slf4j-api-1.5.11.jar" />
32 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
33 </path >
34
35 <path id="path1511Binding">
36 <pathelement location="target/test-classes/" />
37 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
38 <pathelement location="./lib/slf4j-simple-1.5.11.jar" />
39 </path >
40
41 <!--<path id="pathIncompatible">
42 <pathelement location="target/test-classes/" />
43 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
44 <pathelement location="./lib/slf4j-simple-INCOMPATIBLE.jar" />
45 </path >
46 -->
47
48 <path id="pathCurrent">
49 <pathelement location="target/test-classes/" />
50 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
51 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
52 </path >
53
54
55 <path id="incompatibleMultiBinding">
56 <pathelement location="target/test-classes/" />
57 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
58 <pathelement location="./lib/slf4j-simple-1.5.0.jar" />
59 <pathelement location="./lib/slf4j-nop-1.5.6.jar" />
60 </path >
61
62 <path id="multiBinding">
63 <pathelement location="target/test-classes/" />
64 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
65 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
66 <pathelement location="../slf4j-nop/target/slf4j-nop-${currentVersion}.jar" />
67 </path >
68
69 <path id="binding166">
70 <pathelement location="target/test-classes/" />
71 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
72 <pathelement location="./lib/slf4j-simple-1.6.6.jar" />
73 </path >
74
75 <path id="binding2099">
76 <pathelement location="target/test-classes/" />
77 <pathelement location="../slf4j-api/target/slf4j-api-${currentVersion}.jar" />
78 <pathelement location="./lib/slf4j-simple-2.0.99.jar" />
79 </path >
80
81
82 <path id="api166">
83 <pathelement location="target/test-classes/" />
84 <pathelement location="../slf4j-simple/target/slf4j-simple-${currentVersion}.jar" />
85 <pathelement location="./lib/slf4j-api-1.6.6.jar" />
86 </path >
87
88
89 <!-- this is really very ugly, but it's the only way to circumvent
90 http://jira.codehaus.org/browse/MANTRUN-95
91 -->
92 <taskdef name="junit" classpath="${plugin_classpath};${compile_classpath}"
93 classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask" />
94
95 <target name="init">
96 <mkdir dir="target/unit-reports" />
97 </target>
98
99 <target name="testAll" depends="init,
100 testMissingSingletonMethod,
101 testMismatch,
102 testMatch,
103 testMultiBinding,
104 testIncompatibleMultiBinding,
105 testFuture_16Series">
106 </target>
107
108
109 <target name="testMissingSingletonMethod">
110
111 <junit printsummary="yes" fork="no" haltonfailure="yes">
112 <classpath refid="path142Binding" />
113 <formatter type="plain" />
114 <test fork="yes" todir="target/unit-reports"
115 outfile="TEST-142BININDING"
116 name="org.slf4j.MissingSingletonMethodAssertionTest" />
117 </junit>
118
119 <junit printsummary="yes" fork="no" haltonfailure="yes">
120 <classpath refid="path150Binding" />
121 <formatter type="plain" />
122 <test fork="yes" todir="target/unit-reports"
123 outfile="TEST-150BINDING"
124 name="org.slf4j.MissingSingletonMethodAssertionTest" />
125 </junit>
126
127 </target>
128
129 <target name="testMismatch">
130
131 <junit printsummary="yes" fork="no" haltonfailure="yes">
132 <classpath refid="path1511API" />
133 <formatter type="plain" />
134 <test fork="yes" todir="target/unit-reports"
135 outfile="TEST-MISMATCH-1511API"
136 name="org.slf4j.VersionMismatchAssertionTest" />
137 </junit>
138
139
140 <junit printsummary="yes" fork="no" haltonfailure="yes">
141 <classpath refid="path1511Binding" />
142 <formatter type="plain" />
143 <test fork="yes" todir="target/unit-reports"
144 outfile="TEST-MISMATCH-1511Binding"
145 name="org.slf4j.VersionMismatchAssertionTest" />
146 </junit>
147
148 </target>
149
150 <target name="testMatch">
151 <junit printsummary="yes" fork="no" haltonfailure="yes">
152 <classpath refid="pathCurrent" />
153 <formatter type="plain" />
154 <test fork="yes" todir="target/unit-reports"
155 outfile="TEST-Match"
156 name="org.slf4j.CompatibilityAssertionTest" />
157 </junit>
158 </target>
159
160 <target name="testIncompatibleMultiBinding">
161 <junit printsummary="yes" fork="no" haltonfailure="yes">
162 <classpath refid="incompatibleMultiBinding" />
163 <formatter type="plain" />
164 <test fork="yes" todir="target/unit-reports"
165 outfile="TEST-IncompatibleMultiBinding"
166 name="org.slf4j.IncompatibleMultiBindingAssertionTest" />
167 </junit>
168 </target>
169
170 <target name="testMultiBinding">
171 <junit printsummary="yes" fork="no" haltonfailure="yes">
172 <classpath refid="multiBinding" />
173 <formatter type="plain" />
174 <test fork="yes" todir="target/unit-reports"
175 outfile="TEST-MultiBinding"
176 name="org.slf4j.MultiBindingAssertionTest" />
177 </junit>
178 </target>
179
180 <target name="testFuture_16Series">
181 <junit printsummary="yes" fork="no" haltonfailure="yes">
182 <classpath refid="binding166" />
183 <formatter type="plain" />
184 <test fork="yes" todir="target/unit-reports"
185 outfile="TEST-binding166"
186 name="org.slf4j.CompatibilityAssertionTest" />
187 </junit>
188
189
190 <junit printsummary="yes" fork="no" haltonfailure="yes">
191 <classpath refid="api166" />
192 <formatter type="plain" />
193 <test fork="yes" todir="target/unit-reports"
194 outfile="TEST-api166"
195 name="org.slf4j.CompatibilityAssertionTest" />
196 </junit>
197
198 </target>
199 </project>
0 <project name="osgi-test" default="testAll">
1
2 <!--
3 This build file is usually run indirectly via Maven.
4
5 When running this build file through Ant directly, you must
6 define the currentVersion property on the command line, e.g.:
7
8 ant -DcurrentVersion=1.5.4-SNAPSHOT
9 -->
10
11 <echo message="compile classpath: ${currentVersion}" />
12 <echo message="test classpath: ${test_classpath}" />
13 <echo message="basedir: ${basedir}" />
14
15 <property name="iBundleJar" value="target/iBundle.jar"/>
16 <property name="bundlesDir" value="bundle"/>
17
18
19 <!-- this is really very ugly, but it's the only way to circumvent
20 http://jira.codehaus.org/browse/MANTRUN-95
21 -->
22 <taskdef name="junit" classpath="${test_classpath}"
23 classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask" />
24
25 <path id="minimal">
26 <pathelement location="target/test-classes/" />
27 </path >
28
29 <target name="init">
30 <mkdir dir="target/unit-reports" />
31 </target>
32
33 <target name="createIBundle">
34 <mkdir dir="${bundlesDir}"/>
35 <jar destFile="${iBundleJar}"
36 manifest="src/IBUNDLE-META-INF/MANIFEST.MF"
37 basedir="target/test-classes/"
38 includes="integrator/**.class"/>
39
40 </target>
41
42 <target name="testAll" depends="init, createIBundle, nop, simple, jdk14">
43 </target>
44
45
46 <macrodef name="prepareOSGiHarness">
47 <attribute name="binding"/>
48 <sequential>
49 <delete>
50 <fileset dir="${bundlesDir}" includes="*.jar"/>
51 </delete>
52 <copy file="${iBundleJar}" todir="${bundlesDir}"/>
53 <copy file="../slf4j-api/target/slf4j-api-${currentVersion}.jar" todir="${bundlesDir}"/>
54 <copy file="../slf4j-@{binding}/target/slf4j-@{binding}-${currentVersion}.jar" todir="${bundlesDir}"/>
55 <echo>value of t = @{t}</echo>
56 </sequential>
57 </macrodef>
58
59
60 <!-- for some reason if mvn is invoked from the parent directory, junit gets
61 invoked from the parent dir, which messes up theses tests. Hence, the
62 fork="yes" dir="${basedir}" -->
63
64 <target name="nop">
65 <prepareOSGiHarness binding="nop"/>
66 <junit printsummary="yes" fork="yes" dir="${basedir}" haltonfailure="yes">
67 <classpath path="${test_classpath}"/>
68 <formatter type="plain" />
69 <test fork="yes" todir="target/unit-reports" name="org.slf4j.test_osgi.BundleTest" />
70 </junit>
71 </target>
72
73 <target name="simple">
74 <prepareOSGiHarness binding="simple"/>
75 <junit printsummary="yes" fork="yes" dir="${basedir}" haltonfailure="yes">
76 <classpath path="${test_classpath}"/>
77 <formatter type="plain" />
78 <test fork="yes" todir="target/unit-reports" name="org.slf4j.test_osgi.BundleTest" />
79 </junit>
80 </target>
81
82 <target name="jdk14">
83 <prepareOSGiHarness binding="jdk14"/>
84 <junit printsummary="yes" fork="yes" dir="${basedir}" haltonfailure="yes">
85 <classpath path="${test_classpath}"/>
86 <formatter type="plain" />
87 <test fork="yes" todir="target/unit-reports" name="org.slf4j.test_osgi.BundleTest" />
88 </junit>
89 </target>
90
91 </project>
0 <project
1 xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
5 <modelVersion>4.0.0</modelVersion>
6
7 <parent>
8 <groupId>org.slf4j</groupId>
9 <artifactId>slf4j-parent</artifactId>
10 <version>1.7.12</version>
11 </parent>
12
13
14 <artifactId>integration</artifactId>
15 <packaging>jar</packaging>
16 <name>SLF4J Integration tests</name>
17
18 <url>http://www.slf4j.org</url>
19 <description>SLF4J integration tests</description>
20
21 <dependencies>
22 <dependency>
23 <groupId>org.slf4j</groupId>
24 <artifactId>slf4j-api</artifactId>
25 </dependency>
26
27 <!-- declaration to circumvent http://jira.codehaus.org/browse/MANTRUN-95 -->
28 <dependency>
29 <groupId>junit</groupId>
30 <artifactId>junit</artifactId>
31 <version>3.8.1</version>
32 </dependency>
33 <!-- declaration to circumvent http://jira.codehaus.org/browse/MANTRUN-95 -->
34 <dependency>
35 <groupId>ant</groupId>
36 <artifactId>ant-junit</artifactId>
37 <version>1.6.5</version>
38 </dependency>
39
40
41 <!-- some test run Felix in hosted mode -->
42 <dependency>
43 <groupId>org.apache.felix</groupId>
44 <artifactId>org.apache.felix.main</artifactId>
45 <version>2.0.2</version>
46 </dependency>
47 </dependencies>
48
49 <build>
50 <plugins>
51 <plugin>
52 <artifactId>maven-antrun-plugin</artifactId>
53 <version>1.2</version>
54 <dependencies>
55 <dependency>
56 <groupId>junit</groupId>
57 <artifactId>junit</artifactId>
58 <version>3.8.1</version>
59 </dependency>
60 <dependency>
61 <groupId>ant</groupId>
62 <artifactId>ant-junit</artifactId>
63 <version>1.6.5</version>
64 </dependency>
65 </dependencies>
66 <executions>
67 <execution>
68 <id>ant-test</id>
69 <phase>package</phase>
70 <configuration>
71 <tasks>
72 <property name="currentVersion" value="${project.version}"/>
73 <property name="compile_classpath" refid="maven.compile.classpath"/>
74 <property name="runtime_classpath" refid="maven.runtime.classpath"/>
75 <property name="test_classpath" refid="maven.test.classpath"/>
76 <property name="plugin_classpath" refid="maven.plugin.classpath"/>
77 <ant antfile="${basedir}/build.xml"/>
78 </tasks>
79 </configuration>
80 <goals>
81 <goal>run</goal>
82 </goals>
83 </execution>
84 <execution>
85 <id>ant-osgi-test</id>
86 <phase>package</phase>
87 <configuration>
88 <tasks>
89 <property name="currentVersion" value="${project.version}"/>
90 <property name="test_classpath" refid="maven.test.classpath"/>
91 <property name="basedir" value="${basedir}"/>
92 <ant antfile="${basedir}/osgi-build.xml"/>
93 </tasks>
94 </configuration>
95 <goals>
96 <goal>run</goal>
97 </goals>
98 </execution>
99
100 </executions>
101 </plugin>
102
103 <plugin>
104 <groupId>org.apache.maven.plugins</groupId>
105 <artifactId>maven-surefire-plugin</artifactId>
106 <configuration>
107 <forkMode>once</forkMode>
108 <reportFormat>plain</reportFormat>
109 <trimStackTrace>false</trimStackTrace>
110 <excludes>
111 <exclude>**/*Test.java</exclude>
112 </excludes>
113 </configuration>
114 </plugin>
115 </plugins>
116
117
118 </build>
119
120 </project>
0 Manifest-Version: 1.0
1 Archiver-Version: Plexus Archiver
2 Created-By: Apache Maven
3 Built-By: ceki
4 Build-Jdk: 1.6.0_16
5 Bundle-Description: iBundle
6 Bundle-Version: 0.1
7 Bundle-Activator: integrator.Activator
8 Implementation-Title: iBundle
9 Bundle-ManifestVersion: 2
10 Bundle-SymbolicName: iBundle
11 Bundle-Name: abundle
12 Bundle-RequiredExecutionEnvironment: J2SE-1.5
13 Export-Package: apack
14 Import-Package: org.osgi.framework, org.slf4j;version=1.5
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package integrator;
25
26 import org.osgi.framework.Bundle;
27 import org.osgi.framework.BundleActivator;
28 import org.osgi.framework.BundleContext;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33 * A BundleActivator which invokes slf4j loggers
34 * @author Ceki G&uuml;lc&uuml;
35 *
36 */
37 public class Activator implements BundleActivator {
38
39 private BundleContext m_context = null;
40
41 public void start(BundleContext context) {
42 Logger logger = LoggerFactory.getLogger(this.getClass());
43 logger.info("Activator.start()");
44 m_context = context;
45 }
46
47 public void stop(BundleContext context) {
48 m_context = null;
49 Logger logger = LoggerFactory.getLogger(this.getClass());
50 logger.info("Activator.stop");
51 }
52
53 public Bundle[] getBundles() {
54 if (m_context != null) {
55 return m_context.getBundles();
56 }
57 return null;
58 }
59 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j;
26
27 import java.io.PrintStream;
28 import java.util.Random;
29
30 import junit.framework.TestCase;
31
32 public class CompatibilityAssertionTest extends TestCase {
33
34 StringPrintStream sps = new StringPrintStream(System.err);
35 PrintStream old = System.err;
36 int diff = 1024 + new Random().nextInt(10000);
37
38 public CompatibilityAssertionTest(String name) {
39 super(name);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 System.setErr(sps);
45 }
46
47 protected void tearDown() throws Exception {
48 super.tearDown();
49 System.setErr(old);
50 }
51
52 public void test() throws Exception {
53 Logger logger = LoggerFactory.getLogger(this.getClass());
54 String msg = "hello world " + diff;
55 logger.info(msg);
56 assertEquals(1, sps.stringList.size());
57 String s0 = (String) sps.stringList.get(0);
58 assertTrue(s0.contains(msg));
59 }
60 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.List;
28 import java.util.Random;
29
30 import junit.framework.TestCase;
31
32 public class IncompatibleMultiBindingAssertionTest extends TestCase {
33
34 StringPrintStream sps = new StringPrintStream(System.err);
35 PrintStream old = System.err;
36 int diff = 1024 + new Random().nextInt(10000);
37
38 public IncompatibleMultiBindingAssertionTest(String name) {
39 super(name);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 System.setErr(sps);
45 }
46
47 protected void tearDown() throws Exception {
48 super.tearDown();
49 System.setErr(old);
50 }
51
52 public void test() throws Exception {
53 try {
54 Logger logger = LoggerFactory.getLogger(this.getClass());
55 String msg = "hello world " + diff;
56 logger.info(msg);
57 fail("was expecting NoSuchMethodError");
58 } catch (NoSuchMethodError e) {
59 }
60 List<String> list = sps.stringList;
61 assertMsgContains(list, 0, "Class path contains multiple SLF4J bindings.");
62 assertMsgContains(list, 1, "Found binding in");
63 assertMsgContains(list, 2, "Found binding in");
64 assertMsgContains(list, 3, "See http://www.slf4j.org/codes.html");
65 assertMsgContains(list, 4, "slf4j-api 1.6.x (or later) is incompatible with this binding");
66 assertMsgContains(list, 5, "Your binding is version 1.5.5 or earlier.");
67
68 }
69
70 void assertMsgContains(List<String> strList, int index, String msg) {
71 assertTrue(((String) strList.get(index)).contains(msg));
72 }
73 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.Random;
28
29 import junit.framework.TestCase;
30
31 public class MissingSingletonMethodAssertionTest extends TestCase {
32
33 StringPrintStream sps = new StringPrintStream(System.err);
34 PrintStream old = System.err;
35 int diff = 1024 + new Random().nextInt(10000);
36
37 public MissingSingletonMethodAssertionTest(String name) {
38 super(name);
39 }
40
41 protected void setUp() throws Exception {
42 super.setUp();
43 System.setErr(sps);
44 }
45
46 protected void tearDown() throws Exception {
47 super.tearDown();
48 System.setErr(old);
49 }
50
51 public void test() throws Exception {
52 try {
53 Logger logger = LoggerFactory.getLogger(this.getClass());
54 String msg = "hello world " + diff;
55 logger.info(msg);
56 fail("NoSuchMethodError expected");
57 } catch (NoSuchMethodError e) {
58 }
59
60 int lineCount = sps.stringList.size();
61 assertTrue("number of lines should be 3 but was " + lineCount, lineCount == 3);
62
63 // expected output:
64 // SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.
65 // SLF4J: Your binding is version 1.4.x or earlier.
66 // SLF4J: Upgrade your binding to version 1.6.x. or 2.0.x
67
68 {
69 String s = (String) sps.stringList.get(0);
70 assertTrue(s.contains("SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding."));
71 }
72 {
73 String s = (String) sps.stringList.get(1);
74 assertTrue(s.contains("SLF4J: Your binding is version 1.5.5 or earlier."));
75 }
76 {
77 String s = (String) sps.stringList.get(2);
78 assertTrue(s.contains("SLF4J: Upgrade your binding to version 1.6.x."));
79 }
80
81 }
82 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.List;
28 import java.util.Random;
29
30 import junit.framework.TestCase;
31
32 public class MultiBindingAssertionTest extends TestCase {
33
34 StringPrintStream sps = new StringPrintStream(System.err);
35 PrintStream old = System.err;
36 int diff = 1024 + new Random().nextInt(10000);
37
38 public MultiBindingAssertionTest(String name) {
39 super(name);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 System.setErr(sps);
45 }
46
47 protected void tearDown() throws Exception {
48 super.tearDown();
49 System.setErr(old);
50 }
51
52 public void test() throws Exception {
53 Logger logger = LoggerFactory.getLogger(this.getClass());
54 String msg = "hello world " + diff;
55 logger.info(msg);
56 List<String> list = sps.stringList;
57 assertMsgContains(list, 0, "Class path contains multiple SLF4J bindings.");
58 assertMsgContains(list, 1, "Found binding in");
59 assertMsgContains(list, 2, "Found binding in");
60 assertMsgContains(list, 3, "See http://www.slf4j.org/codes.html");
61 assertMsgContains(list, 4, "Actual binding is of type [");
62 }
63
64 void assertMsgContains(List<String> strList, int index, String msg) {
65 assertTrue(((String) strList.get(index)).contains(msg));
66 }
67 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 public class StringPrintStream extends PrintStream {
31
32 public static final String LINE_SEP = System.getProperty("line.separator");
33 PrintStream other;
34 List<String> stringList = new ArrayList<String>();
35
36 public StringPrintStream(PrintStream ps) {
37 super(ps);
38 other = ps;
39 }
40
41 public void print(String s) {
42 other.print(s);
43 stringList.add(s);
44 }
45
46 public void println(String s) {
47 other.println(s);
48 stringList.add(s);
49 }
50
51 public void println(Object o) {
52 other.println(o);
53 stringList.add(o.toString());
54 }
55 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27 import java.util.Random;
28
29 import junit.framework.TestCase;
30
31 public class VersionMismatchAssertionTest extends TestCase {
32
33 StringPrintStream sps = new StringPrintStream(System.err);
34 PrintStream old = System.err;
35 int diff = 1024 + new Random().nextInt(10000);
36
37 public VersionMismatchAssertionTest(String name) {
38 super(name);
39 }
40
41 protected void setUp() throws Exception {
42 super.setUp();
43 System.setErr(sps);
44 }
45
46 protected void tearDown() throws Exception {
47 super.tearDown();
48 System.setErr(old);
49 }
50
51 public void test() throws Exception {
52 Logger logger = LoggerFactory.getLogger(this.getClass());
53 String msg = "hello world " + diff;
54 logger.info(msg);
55
56 String s0 = (String) sps.stringList.get(0);
57 assertTrue(s0.matches("SLF4J: The requested version .* by your slf4j binding is not compatible with.*"));
58
59 String s1 = (String) sps.stringList.get(1);
60 assertTrue(s1.contains(LoggerFactory.VERSION_MISMATCH));
61
62 String s2 = (String) sps.stringList.get(2);
63 assertTrue(s2.contains(msg));
64
65 }
66 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.io.File;
27
28 import junit.framework.TestCase;
29
30 public class BundleTest extends TestCase {
31
32 FrameworkErrorListener fel = new FrameworkErrorListener();
33 CheckingBundleListener mbl = new CheckingBundleListener();
34
35 FelixHost felixHost = new FelixHost(fel, mbl);
36
37 protected void setUp() throws Exception {
38 super.setUp();
39 felixHost.doLaunch();
40 }
41
42 protected void tearDown() throws Exception {
43 super.tearDown();
44 felixHost.stop();
45 }
46
47 public void testSmoke() {
48 System.out.println("===========" + new File(".").getAbsolutePath());
49 mbl.dumpAll();
50 // check that the bundle was installed
51 assertTrue(mbl.exists("iBundle"));
52 if (fel.errorList.size() != 0) {
53 fel.dumpAll();
54 }
55 // check that no errors occured
56 assertEquals(0, fel.errorList.size());
57 }
58 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.osgi.framework.Bundle;
30 import org.osgi.framework.BundleEvent;
31 import org.osgi.framework.BundleListener;
32
33 public class CheckingBundleListener implements BundleListener {
34
35 List<BundleEvent> eventList = new ArrayList<BundleEvent>();
36
37 public void bundleChanged(BundleEvent be) {
38 eventList.add(be);
39 }
40
41 private void dump(BundleEvent be) {
42 System.out.println("BE:" + ", source " + be.getSource() + ", bundle=" + be.getBundle() + ", type=" + be.getType());
43
44 }
45
46 public void dumpAll() {
47 for (int i = 0; i < eventList.size(); i++) {
48 BundleEvent fe = (BundleEvent) eventList.get(i);
49 dump(fe);
50 }
51 }
52
53 boolean exists(String bundleName) {
54 for (int i = 0; i < eventList.size(); i++) {
55 BundleEvent fe = (BundleEvent) eventList.get(i);
56 Bundle b = fe.getBundle();
57 System.out.println("===[" + b + "]");
58 if (bundleName.equals(b.getSymbolicName())) {
59 return true;
60 }
61 }
62 return false;
63 }
64
65 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Properties;
29
30 import org.apache.felix.framework.Felix;
31 import org.apache.felix.framework.util.FelixConstants;
32 import org.apache.felix.framework.util.StringMap;
33 import org.apache.felix.main.AutoProcessor;
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.BundleContext;
36 import org.osgi.framework.BundleException;
37 import org.osgi.framework.Constants;
38
39 /**
40 * Runs a hosted version of Felix for testing purposes. Any bundle errors are
41 * reported via the FrameworkListener passed to the constructor.
42 *
43 * @author Ceki G&uuml;c&uuml;
44 */
45 public class FelixHost {
46
47 private Felix felix = null;
48
49 Properties otherProps = new Properties();
50
51 final FrameworkErrorListener frameworkErrorListener;
52 final CheckingBundleListener myBundleListener;
53
54 public FelixHost(FrameworkErrorListener frameworkErrorListener, CheckingBundleListener myBundleListener) {
55 this.frameworkErrorListener = frameworkErrorListener;
56 this.myBundleListener = myBundleListener;
57 }
58
59 public void doLaunch() {
60 // Create a case-insensitive configuration property map.
61 StringMap configMap = new StringMap(false);
62 // Configure the Felix instance to be embedded.
63 // configMap.put(FelixConstants.EMBEDDED_EXECUTION_PROP, "true");
64 // Add core OSGi packages to be exported from the class path
65 // via the system bundle.
66 configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES, "org.osgi.framework; version=1.3.0," + "org.osgi.service.packageadmin; version=1.2.0,"
67 + "org.osgi.service.startlevel; version=1.0.0," + "org.osgi.service.url; version=1.0.0");
68
69 configMap.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
70
71 // Explicitly specify the directory to use for caching bundles.
72 // configMap.put(BundleCache.CACHE_PROFILE_DIR_PROP, "cache");
73
74 try {
75 // Create host activator;
76
77 List<Object> list = new ArrayList<Object>();
78
79 // list.add(new HostActivator());
80 configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.xml.sax, org.xml.sax.helpers, javax.xml.parsers, javax.naming");
81 configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
82 configMap.put("felix.log.level", "4");
83
84 // Now create an instance of the framework with
85 // our configuration properties and activator.
86 felix = new Felix(configMap);
87 felix.init();
88
89 // otherProps.put(Constants.FRAMEWORK_STORAGE, "bundles");
90
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);
93
94 BundleContext felixBudleContext = felix.getBundleContext();
95
96 AutoProcessor.process(otherProps, felixBudleContext);
97 // listen to errors
98 felixBudleContext.addFrameworkListener(frameworkErrorListener);
99 felixBudleContext.addBundleListener(myBundleListener);
100 // Now start Felix instance.
101 felix.start();
102 System.out.println("felix started");
103
104 } catch (Exception ex) {
105 ex.printStackTrace();
106 }
107 }
108
109 public void stop() throws BundleException {
110 felix.stop();
111 }
112
113 public Bundle[] getInstalledBundles() {
114 // Use the system bundle activator to gain external
115 // access to the set of installed bundles.
116 return null;// m_activator.getBundles();
117 }
118 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.test_osgi;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.osgi.framework.FrameworkEvent;
30 import org.osgi.framework.FrameworkListener;
31
32 public class FrameworkErrorListener implements FrameworkListener {
33
34 public List<FrameworkEvent> errorList = new ArrayList<FrameworkEvent>();
35
36 public void frameworkEvent(FrameworkEvent fe) {
37 if (fe.getType() == FrameworkEvent.ERROR) {
38 errorList.add(fe);
39
40 }
41 }
42
43 private void dump(FrameworkEvent fe) {
44 Throwable t = fe.getThrowable();
45 String tString = null;
46 if (t != null) {
47 tString = t.toString();
48 }
49 System.out.println("Framework ERROR:" + ", source " + fe.getSource() + ", bundle=" + fe.getBundle() + ", ex=" + tString);
50 if (t != null) {
51 t.printStackTrace();
52 }
53 }
54
55 public void dumpAll() {
56 for (int i = 0; i < errorList.size(); i++) {
57 FrameworkEvent fe = (FrameworkEvent) errorList.get(i);
58 dump(fe);
59 }
60 }
61 }
0 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2
3 <parent>
4 <groupId>org.slf4j</groupId>
5 <artifactId>slf4j-parent</artifactId>
6 <version>1.7.12</version>
7 </parent>
8
9 <modelVersion>4.0.0</modelVersion>
10
11 <artifactId>jcl-over-slf4j</artifactId>
12 <packaging>jar</packaging>
13 <name>JCL 1.1.1 implemented over SLF4J</name>
14 <description>JCL 1.1.1 implemented over SLF4J</description>
15 <url>http://www.slf4j.org</url>
16
17
18 <dependencies>
19 <!--
20 <dependency>
21 <groupId>org.slf4j</groupId>
22 <artifactId>slf4j-nop</artifactId>
23 <version>${project.version}</version>
24 <scope>provided</scope>
25 </dependency>
26 -->
27
28 <dependency>
29 <groupId>org.slf4j</groupId>
30 <artifactId>slf4j-api</artifactId>
31 </dependency>
32
33 <dependency>
34 <groupId>org.slf4j</groupId>
35 <artifactId>slf4j-jdk14</artifactId>
36 <scope>test</scope>
37 </dependency>
38
39 </dependencies>
40
41 <build>
42 <plugins>
43
44 <plugin>
45 <groupId>org.apache.maven.plugins</groupId>
46 <artifactId>maven-jar-plugin</artifactId>
47 <configuration>
48 <archive>
49 <manifestEntries>
50 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
51 <Bundle-Description>${project.description}</Bundle-Description>
52 <Implementation-Version>${project.version}</Implementation-Version>
53 </manifestEntries>
54 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
55 </archive>
56 </configuration>
57 </plugin>
58
59 </plugins>
60
61
62 </build>
63
64 </project>
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging;
17
18 /**
19 * <p>A simple logging interface abstracting logging APIs. In order to be
20 * instantiated successfully by {@link LogFactory}, classes that implement
21 * this interface must have a constructor that takes a single String
22 * parameter representing the "name" of this Log.</p>
23 *
24 * <p> The six logging levels used by <code>Log</code> are (in order):
25 * <ol>
26 * <li>trace (the least serious)</li>
27 * <li>debug</li>
28 * <li>info</li>
29 * <li>warn</li>
30 * <li>error</li>
31 * <li>fatal (the most serious)</li>
32 * </ol>
33 * The mapping of these log levels to the concepts used by the underlying
34 * logging system is implementation dependent.
35 * The implementation should ensure, though, that this ordering behaves
36 * as expected.</p>
37 *
38 * <p>Performance is often a logging concern.
39 * By examining the appropriate property,
40 * a component can avoid expensive operations (producing information
41 * to be logged).</p>
42 *
43 * <p> For example,
44 * <code><pre>
45 * if (log.isDebugEnabled()) {
46 * ... do something expensive ...
47 * log.debug(theResult);
48 * }
49 * </pre></code>
50 * </p>
51 *
52 * <p>Configuration of the underlying logging system will generally be done
53 * external to the Logging APIs, through whatever mechanism is supported by
54 * that system.</p>
55 *
56 * <p style="color: #E40; font-weight: bold;">Please note that this interface is identical to that found in JCL 1.1.1.</p>
57 *
58 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
59 * @author Rod Waldhoff
60 * @version $Id: Log.java,v 1.19 2004/06/06 21:16:04 rdonkin Exp $
61 */
62 public interface Log {
63
64 // ----------------------------------------------------- Logging Properties
65
66 /**
67 * <p> Is debug logging currently enabled? </p>
68 *
69 * <p> Call this method to prevent having to perform expensive operations
70 * (for example, <code>String</code> concatenation)
71 * when the log level is more than debug. </p>
72 */
73 public boolean isDebugEnabled();
74
75 /**
76 * <p> Is error logging currently enabled? </p>
77 *
78 * <p> Call this method to prevent having to perform expensive operations
79 * (for example, <code>String</code> concatenation)
80 * when the log level is more than error. </p>
81 */
82 public boolean isErrorEnabled();
83
84 /**
85 * <p> Is fatal logging currently enabled? </p>
86 *
87 * <p> Call this method to prevent having to perform expensive operations
88 * (for example, <code>String</code> concatenation)
89 * when the log level is more than fatal. </p>
90 */
91 public boolean isFatalEnabled();
92
93 /**
94 * <p> Is info logging currently enabled? </p>
95 *
96 * <p> Call this method to prevent having to perform expensive operations
97 * (for example, <code>String</code> concatenation)
98 * when the log level is more than info. </p>
99 *
100 * @return true if info enabled, false otherwise
101 */
102 public boolean isInfoEnabled();
103
104 /**
105 * <p> Is trace logging currently enabled? </p>
106 *
107 * <p> Call this method to prevent having to perform expensive operations
108 * (for example, <code>String</code> concatenation)
109 * when the log level is more than trace. </p>
110 *
111 * @return true if trace enabled, false otherwise
112 */
113 public boolean isTraceEnabled();
114
115 /**
116 * <p> Is warn logging currently enabled? </p>
117 *
118 * <p> Call this method to prevent having to perform expensive operations
119 * (for example, <code>String</code> concatenation)
120 * when the log level is more than warn. </p>
121 */
122 public boolean isWarnEnabled();
123
124 // -------------------------------------------------------- Logging Methods
125
126 /**
127 * <p> Log a message with trace log level. </p>
128 *
129 * @param message log this message
130 */
131 public void trace(Object message);
132
133 /**
134 * <p> Log an error with trace log level. </p>
135 *
136 * @param message log this message
137 * @param t log this cause
138 */
139 public void trace(Object message, Throwable t);
140
141 /**
142 * <p> Log a message with debug log level. </p>
143 *
144 * @param message log this message
145 */
146 public void debug(Object message);
147
148 /**
149 * <p> Log an error with debug log level. </p>
150 *
151 * @param message log this message
152 * @param t log this cause
153 */
154 public void debug(Object message, Throwable t);
155
156 /**
157 * <p> Log a message with info log level. </p>
158 *
159 * @param message log this message
160 */
161 public void info(Object message);
162
163 /**
164 * <p> Log an error with info log level. </p>
165 *
166 * @param message log this message
167 * @param t log this cause
168 */
169 public void info(Object message, Throwable t);
170
171 /**
172 * <p> Log a message with warn log level. </p>
173 *
174 * @param message log this message
175 */
176 public void warn(Object message);
177
178 /**
179 * <p> Log an error with warn log level. </p>
180 *
181 * @param message log this message
182 * @param t log this cause
183 */
184 public void warn(Object message, Throwable t);
185
186 /**
187 * <p> Log a message with error log level. </p>
188 *
189 * @param message log this message
190 */
191 public void error(Object message);
192
193 /**
194 * <p> Log an error with error log level. </p>
195 *
196 * @param message log this message
197 * @param t log this cause
198 */
199 public void error(Object message, Throwable t);
200
201 /**
202 * <p> Log a message with fatal log level. </p>
203 *
204 * @param message log this message
205 */
206 public void fatal(Object message);
207
208 /**
209 * <p> Log an error with fatal log level. </p>
210 *
211 * @param message log this message
212 * @param t log this cause
213 */
214 public void fatal(Object message, Throwable t);
215
216 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging;
17
18 /**
19 * <p>
20 * An exception that is thrown only if a suitable <code>LogFactory</code> or
21 * <code>Log</code> instance cannot be created by the corresponding factory
22 * methods.
23 * </p>
24 *
25 * <p>
26 * In this version of JCL, this exception will never be thrown in practice.
27 * However, it is included here to ensure total compile time and run time
28 * compatibility with the original JCL 1.0.4.
29 *
30 * @author Craig R. McClanahan
31 */
32
33 public class LogConfigurationException extends RuntimeException {
34
35 private static final long serialVersionUID = 8486587136871052495L;
36
37 /**
38 * Construct a new exception with <code>null</code> as its detail message.
39 */
40 public LogConfigurationException() {
41 super();
42 }
43
44 /**
45 * Construct a new exception with the specified detail message.
46 *
47 * @param message
48 * The detail message
49 */
50 public LogConfigurationException(String message) {
51 super(message);
52 }
53
54 /**
55 * Construct a new exception with the specified cause and a derived detail
56 * message.
57 *
58 * @param cause
59 * The underlying cause
60 */
61 public LogConfigurationException(Throwable cause) {
62
63 this((cause == null) ? null : cause.toString(), cause);
64
65 }
66
67 /**
68 * Construct a new exception with the specified detail message and cause.
69 *
70 * @param message
71 * The detail message
72 * @param cause
73 * The underlying cause
74 */
75 public LogConfigurationException(String message, Throwable cause) {
76 super(message + " (Caused by " + cause + ")");
77 this.cause = cause; // Two-argument version requires JDK 1.4 or later
78 }
79
80 /**
81 * The underlying cause of this exception.
82 */
83 protected Throwable cause = null;
84
85 /**
86 * Return the underlying cause of this exception (if any).
87 */
88 public Throwable getCause() {
89 return (this.cause);
90 }
91
92 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging;
17
18 import java.util.Hashtable;
19
20 import org.apache.commons.logging.impl.SLF4JLogFactory;
21
22 /**
23 * <p>
24 * Factory for creating {@link Log} instances, which always delegates to an
25 * instance of {@link SLF4JLogFactory}.
26 *
27 * </p>
28 *
29 * @author Craig R. McClanahan
30 * @author Costin Manolache
31 * @author Richard A. Sitze
32 * @author Ceki G&uuml;lc&uuml;
33 */
34
35 @SuppressWarnings("rawtypes")
36 public abstract class LogFactory {
37
38 static String UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J = "http://www.slf4j.org/codes.html#unsupported_operation_in_jcl_over_slf4j";
39
40 static LogFactory logFactory = new SLF4JLogFactory();
41
42 /**
43 * The name (<code>priority</code>) of the key in the config file used to
44 * specify the priority of that particular config file. The associated value
45 * is a floating-point number; higher values take priority over lower values.
46 *
47 * <p>
48 * This property is not used but preserved here for compatibility.
49 */
50 public static final String PRIORITY_KEY = "priority";
51
52 /**
53 * The name (<code>use_tccl</code>) of the key in the config file used to
54 * specify whether logging classes should be loaded via the thread context
55 * class loader (TCCL), or not. By default, the TCCL is used.
56 *
57 * <p>
58 * This property is not used but preserved here for compatibility.
59 */
60 public static final String TCCL_KEY = "use_tccl";
61
62 /**
63 * The name of the property used to identify the LogFactory implementation
64 * class name.
65 * <p>
66 * This property is not used but preserved here for compatibility.
67 */
68 public static final String FACTORY_PROPERTY = "org.apache.commons.logging.LogFactory";
69
70 /**
71 * The fully qualified class name of the fallback <code>LogFactory</code>
72 * implementation class to use, if no other can be found.
73 *
74 * <p>
75 * This property is not used but preserved here for compatibility.
76 */
77 public static final String FACTORY_DEFAULT = "org.apache.commons.logging.impl.SLF4JLogFactory";
78
79 /**
80 * The name of the properties file to search for.
81 * <p>
82 * This property is not used but preserved here for compatibility.
83 */
84 public static final String FACTORY_PROPERTIES = "commons-logging.properties";
85
86 /**
87 * JDK1.3+ <a href="http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service%20Provider">
88 * 'Service Provider' specification</a>.
89 * <p>
90 * This property is not used but preserved here for compatibility.
91 */
92 protected static final String SERVICE_ID = "META-INF/services/org.apache.commons.logging.LogFactory";
93
94 /**
95 * The name (<code>org.apache.commons.logging.diagnostics.dest</code>) of
96 * the property used to enable internal commons-logging diagnostic output, in
97 * order to get information on what logging implementations are being
98 * discovered, what classloaders they are loaded through, etc.
99 *
100 * <p>
101 * This property is not used but preserved here for compatibility.
102 */
103 public static final String DIAGNOSTICS_DEST_PROPERTY = "org.apache.commons.logging.diagnostics.dest";
104
105 /**
106 * <p>
107 * Setting this system property value allows the <code>Hashtable</code> used
108 * to store classloaders to be substituted by an alternative implementation.
109 * <p>
110 * This property is not used but preserved here for compatibility.
111 */
112 public static final String HASHTABLE_IMPLEMENTATION_PROPERTY = "org.apache.commons.logging.LogFactory.HashtableImpl";
113
114 /**
115 * The previously constructed <code>LogFactory</code> instances, keyed by
116 * the <code>ClassLoader</code> with which it was created.
117 *
118 * <p>
119 * This property is not used but preserved here for compatibility.
120 */
121 protected static Hashtable factories = null;
122
123 /**
124 * <p>
125 * This property is not used but preserved here for compatibility.
126 */
127 protected static LogFactory nullClassLoaderFactory = null;
128
129 /**
130 * Protected constructor that is not available for public use.
131 */
132 protected LogFactory() {
133 }
134
135 // --------------------------------------------------------- Public Methods
136
137 /**
138 * Return the configuration attribute with the specified name (if any), or
139 * <code>null</code> if there is no such attribute.
140 *
141 * @param name Name of the attribute to return
142 * @return configuration attribute
143 */
144 public abstract Object getAttribute(String name);
145
146 /**
147 * Return an array containing the names of all currently defined configuration
148 * attributes. If there are no such attributes, a zero length array is
149 * returned.
150 *
151 * @return names of all currently defined configuration attributes
152 */
153 public abstract String[] getAttributeNames();
154
155 /**
156 * Convenience method to derive a name from the specified class and call
157 * <code>getInstance(String)</code> with it.
158 *
159 * @param clazz
160 * Class for which a suitable Log name will be derived
161 *
162 * @exception LogConfigurationException
163 * if a suitable <code>Log</code> instance cannot be
164 * returned
165 */
166 public abstract Log getInstance(Class clazz) throws LogConfigurationException;
167
168 /**
169 * <p>
170 * Construct (if necessary) and return a <code>Log</code> instance, using
171 * the factory's current set of configuration attributes.
172 * </p>
173 *
174 * <p>
175 * <strong>NOTE </strong>- Depending upon the implementation of the
176 * <code>LogFactory</code> you are using, the <code>Log</code> instance
177 * you are returned may or may not be local to the current application, and
178 * may or may not be returned again on a subsequent call with the same name
179 * argument.
180 * </p>
181 *
182 * @param name
183 * Logical name of the <code>Log</code> instance to be
184 * returned (the meaning of this name is only known to the
185 * underlying logging implementation that is being wrapped)
186 *
187 * @exception LogConfigurationException
188 * if a suitable <code>Log</code> instance cannot be
189 * returned
190 */
191 public abstract Log getInstance(String name) throws LogConfigurationException;
192
193 /**
194 * Release any internal references to previously created {@link Log}instances
195 * returned by this factory. This is useful in environments like servlet
196 * containers, which implement application reloading by throwing away a
197 * ClassLoader. Dangling references to objects in that class loader would
198 * prevent garbage collection.
199 */
200 public abstract void release();
201
202 /**
203 * Remove any configuration attribute associated with the specified name. If
204 * there is no such attribute, no action is taken.
205 *
206 * @param name
207 * Name of the attribute to remove
208 */
209 public abstract void removeAttribute(String name);
210
211 /**
212 * Set the configuration attribute with the specified name. Calling this with
213 * a <code>null</code> value is equivalent to calling
214 * <code>removeAttribute(name)</code>.
215 *
216 * @param name
217 * Name of the attribute to set
218 * @param value
219 * Value of the attribute to set, or <code>null</code> to
220 * remove any setting for this attribute
221 */
222 public abstract void setAttribute(String name, Object value);
223
224 // --------------------------------------------------------- Static Methods
225
226 /**
227 * <p>
228 * Construct (if necessary) and return a <code>LogFactory</code> instance,
229 * using the following ordered lookup procedure to determine the name of the
230 * implementation class to be loaded.
231 * </p>
232 * <ul>
233 * <li>The <code>org.apache.commons.logging.LogFactory</code> system
234 * property.</li>
235 * <li>The JDK 1.3 Service Discovery mechanism</li>
236 * <li>Use the properties file <code>commons-logging.properties</code>
237 * file, if found in the class path of this class. The configuration file is
238 * in standard <code>java.util.Properties</code> format and contains the
239 * fully qualified name of the implementation class with the key being the
240 * system property defined above.</li>
241 * <li>Fall back to a default implementation class (
242 * <code>org.apache.commons.logging.impl.SLF4FLogFactory</code>).</li>
243 * </ul>
244 *
245 * <p>
246 * <em>NOTE</em>- If the properties file method of identifying the
247 * <code>LogFactory</code> implementation class is utilized, all of the
248 * properties defined in this file will be set as configuration attributes on
249 * the corresponding <code>LogFactory</code> instance.
250 * </p>
251 *
252 * @exception LogConfigurationException
253 * if the implementation class is not available or cannot
254 * be instantiated.
255 */
256 public static LogFactory getFactory() throws LogConfigurationException {
257 return logFactory;
258 }
259
260 /**
261 * Convenience method to return a named logger, without the application having
262 * to care about factories.
263 *
264 * @param clazz
265 * Class from which a log name will be derived
266 *
267 * @exception LogConfigurationException
268 * if a suitable <code>Log</code> instance cannot be
269 * returned
270 */
271 public static Log getLog(Class clazz) throws LogConfigurationException {
272 return (getFactory().getInstance(clazz));
273 }
274
275 /**
276 * Convenience method to return a named logger, without the application having
277 * to care about factories.
278 *
279 * @param name
280 * Logical name of the <code>Log</code> instance to be
281 * returned (the meaning of this name is only known to the
282 * underlying logging implementation that is being wrapped)
283 *
284 * @exception LogConfigurationException
285 * if a suitable <code>Log</code> instance cannot be
286 * returned
287 */
288 public static Log getLog(String name) throws LogConfigurationException {
289 return (getFactory().getInstance(name));
290 }
291
292 /**
293 * Release any internal references to previously created {@link LogFactory}
294 * instances that have been associated with the specified class loader (if
295 * any), after calling the instance method <code>release()</code> on each of
296 * them.
297 *
298 * @param classLoader
299 * ClassLoader for which to release the LogFactory
300 */
301 public static void release(ClassLoader classLoader) {
302 // since SLF4J based JCL does not make use of classloaders, there is nothing
303 // to do here
304 }
305
306 /**
307 * Release any internal references to previously created {@link LogFactory}
308 * instances, after calling the instance method <code>release()</code> on
309 * each of them. This is useful in environments like servlet containers, which
310 * implement application reloading by throwing away a ClassLoader. Dangling
311 * references to objects in that class loader would prevent garbage
312 * collection.
313 */
314 public static void releaseAll() {
315 // since SLF4J based JCL does not make use of classloaders, there is nothing
316 // to do here
317 }
318
319 /**
320 * Returns a string that uniquely identifies the specified object, including
321 * its class.
322 * <p>
323 * The returned string is of form "classname@hashcode", ie is the same as the
324 * return value of the Object.toString() method, but works even when the
325 * specified object's class has overidden the toString method.
326 *
327 * @param o
328 * may be null.
329 * @return a string of form classname@hashcode, or "null" if param o is null.
330 * @since 1.1
331 */
332 public static String objectId(Object o) {
333 if (o == null) {
334 return "null";
335 } else {
336 return o.getClass().getName() + "@" + System.identityHashCode(o);
337 }
338 }
339
340 // protected methods which were added in JCL 1.1. These are not used
341 // by SLF4JLogFactory
342
343 /**
344 * This method exists to ensure signature compatibility.
345 */
346 protected static Object createFactory(String factoryClass, ClassLoader classLoader) {
347 throw new UnsupportedOperationException("Operation [factoryClass] is not supported in jcl-over-slf4j. See also "
348 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
349 }
350
351 /**
352 * This method exists to ensure signature compatibility.
353 */
354 protected static ClassLoader directGetContextClassLoader() {
355 throw new UnsupportedOperationException("Operation [directGetContextClassLoader] is not supported in jcl-over-slf4j. See also "
356 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
357 }
358
359 /**
360 * This method exists to ensure signature compatibility.
361 */
362 protected static ClassLoader getContextClassLoader() throws LogConfigurationException {
363 throw new UnsupportedOperationException("Operation [getContextClassLoader] is not supported in jcl-over-slf4j. See also "
364 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
365 }
366
367 /**
368 * This method exists to ensure signature compatibility.
369 */
370 protected static ClassLoader getClassLoader(Class clazz) {
371 throw new UnsupportedOperationException("Operation [getClassLoader] is not supported in jcl-over-slf4j. See also "
372 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
373 }
374
375 /**
376 * This method exists to ensure signature compatibility.
377 */
378 protected static boolean isDiagnosticsEnabled() {
379 throw new UnsupportedOperationException("Operation [isDiagnosticsEnabled] is not supported in jcl-over-slf4j. See also "
380 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
381 }
382
383 /**
384 * This method exists to ensure signature compatibility.
385 */
386 protected static void logRawDiagnostic(String msg) {
387 throw new UnsupportedOperationException("Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also "
388 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
389 }
390
391 /**
392 * This method exists to ensure signature compatibility.
393 */
394 protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader, final ClassLoader contextClassLoader) {
395 throw new UnsupportedOperationException("Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also "
396 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
397 }
398
399 /**
400 * This method exists to ensure signature compatibility.
401 */
402 protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader) {
403 throw new UnsupportedOperationException("Operation [newFactory] is not supported in jcl-over-slf4j. See also "
404 + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J);
405 }
406
407 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.Serializable;
19 import org.apache.commons.logging.Log;
20
21 /**
22 * <p>
23 * Trivial implementation of Log that throws away all messages. No configurable
24 * system properties are supported.
25 * </p>
26 *
27 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
28 * @author Rod Waldhoff
29 * @version $Id: NoOpLog.java,v 1.8 2004/06/06 21:13:12 rdonkin Exp $
30 */
31 public class NoOpLog implements Log, Serializable {
32 private static final long serialVersionUID = 561423906191706148L;
33
34 /** Convenience constructor */
35 public NoOpLog() {
36 }
37
38 /** Base constructor */
39 public NoOpLog(String name) {
40 }
41
42 /** Do nothing */
43 public void trace(Object message) {
44 }
45
46 /** Do nothing */
47 public void trace(Object message, Throwable t) {
48 }
49
50 /** Do nothing */
51 public void debug(Object message) {
52 }
53
54 /** Do nothing */
55 public void debug(Object message, Throwable t) {
56 }
57
58 /** Do nothing */
59 public void info(Object message) {
60 }
61
62 /** Do nothing */
63 public void info(Object message, Throwable t) {
64 }
65
66 /** Do nothing */
67 public void warn(Object message) {
68 }
69
70 /** Do nothing */
71 public void warn(Object message, Throwable t) {
72 }
73
74 /** Do nothing */
75 public void error(Object message) {
76 }
77
78 /** Do nothing */
79 public void error(Object message, Throwable t) {
80 }
81
82 /** Do nothing */
83 public void fatal(Object message) {
84 }
85
86 /** Do nothing */
87 public void fatal(Object message, Throwable t) {
88 }
89
90 /**
91 * Debug is never enabled.
92 *
93 * @return false
94 */
95 public final boolean isDebugEnabled() {
96 return false;
97 }
98
99 /**
100 * Error is never enabled.
101 *
102 * @return false
103 */
104 public final boolean isErrorEnabled() {
105 return false;
106 }
107
108 /**
109 * Fatal is never enabled.
110 *
111 * @return false
112 */
113 public final boolean isFatalEnabled() {
114 return false;
115 }
116
117 /**
118 * Info is never enabled.
119 *
120 * @return false
121 */
122 public final boolean isInfoEnabled() {
123 return false;
124 }
125
126 /**
127 * Trace is never enabled.
128 *
129 * @return false
130 */
131 public final boolean isTraceEnabled() {
132 return false;
133 }
134
135 /**
136 * Warn is never enabled.
137 *
138 * @return false
139 */
140 public final boolean isWarnEnabled() {
141 return false;
142 }
143
144 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.ObjectStreamException;
19 import java.io.Serializable;
20
21 import org.apache.commons.logging.Log;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24 import org.slf4j.spi.LocationAwareLogger;
25
26 /**
27 * Implementation of {@link Log org.apache.commons.logging.Log} interface which
28 * delegates all processing to a wrapped {@link Logger org.slf4j.Logger}
29 * instance.
30 *
31 * <p>
32 * JCL's FATAL level is mapped to ERROR. All other levels map one to one.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class SLF4JLocationAwareLog implements Log, Serializable {
37
38 private static final long serialVersionUID = -2379157579039314822L;
39
40 // used to store this logger's name to recreate it after serialization
41 protected String name;
42
43 // in both Log4jLogger and Jdk14Logger classes in the original JCL, the
44 // logger instance is transient
45 private transient LocationAwareLogger logger;
46
47 private static final String FQCN = SLF4JLocationAwareLog.class.getName();
48
49 SLF4JLocationAwareLog(LocationAwareLogger logger) {
50 this.logger = logger;
51 this.name = logger.getName();
52 }
53
54 /**
55 * Delegates to the <code>isTraceEnabled<code> method of the wrapped
56 * <code>org.slf4j.Logger</code> instance.
57 */
58 public boolean isTraceEnabled() {
59 return logger.isTraceEnabled();
60 }
61
62 /**
63 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
64 */
65 public boolean isDebugEnabled() {
66 return logger.isDebugEnabled();
67 }
68
69 /**
70 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
71 */
72 public boolean isInfoEnabled() {
73 return logger.isInfoEnabled();
74 }
75
76 /**
77 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
78 */
79 public boolean isWarnEnabled() {
80 return logger.isWarnEnabled();
81 }
82
83 /**
84 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
85 */
86 public boolean isErrorEnabled() {
87 return logger.isErrorEnabled();
88 }
89
90 /**
91 * Delegates to the <code>isErrorEnabled<code> method of the wrapped
92 * <code>org.slf4j.Logger</code> instance.
93 */
94 public boolean isFatalEnabled() {
95 return logger.isErrorEnabled();
96 }
97
98 /**
99 * Converts the input parameter to String and then delegates to the debug
100 * method of the wrapped <code>org.slf4j.Logger</code> instance.
101 *
102 * @param message
103 * the message to log. Converted to {@link String}
104 */
105 public void trace(Object message) {
106 logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, null);
107 }
108
109 /**
110 * Converts the first input parameter to String and then delegates to the
111 * debug method of the wrapped <code>org.slf4j.Logger</code> instance.
112 *
113 * @param message
114 * the message to log. Converted to {@link String}
115 * @param t
116 * the exception to log
117 */
118 public void trace(Object message, Throwable t) {
119 logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, t);
120 }
121
122 /**
123 * Converts the input parameter to String and then delegates to the wrapped
124 * <code>org.slf4j.Logger</code> instance.
125 *
126 * @param message
127 * the message to log. Converted to {@link String}
128 */
129 public void debug(Object message) {
130 logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, null);
131 }
132
133 /**
134 * Converts the first input parameter to String and then delegates to the
135 * wrapped <code>org.slf4j.Logger</code> instance.
136 *
137 * @param message
138 * the message to log. Converted to {@link String}
139 * @param t
140 * the exception to log
141 */
142 public void debug(Object message, Throwable t) {
143 logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, t);
144 }
145
146 /**
147 * Converts the input parameter to String and then delegates to the wrapped
148 * <code>org.slf4j.Logger</code> instance.
149 *
150 * @param message
151 * the message to log. Converted to {@link String}
152 */
153 public void info(Object message) {
154 logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, null);
155 }
156
157 /**
158 * Converts the first input parameter to String and then delegates to the
159 * wrapped <code>org.slf4j.Logger</code> instance.
160 *
161 * @param message
162 * the message to log. Converted to {@link String}
163 * @param t
164 * the exception to log
165 */
166 public void info(Object message, Throwable t) {
167 logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, t);
168 }
169
170 /**
171 * Converts the input parameter to String and then delegates to the wrapped
172 * <code>org.slf4j.Logger</code> instance.
173 *
174 * @param message
175 * the message to log. Converted to {@link String}
176 */
177 public void warn(Object message) {
178 logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, null);
179 }
180
181 /**
182 * Converts the first input parameter to String and then delegates to the
183 * wrapped <code>org.slf4j.Logger</code> instance.
184 *
185 * @param message
186 * the message to log. Converted to {@link String}
187 * @param t
188 * the exception to log
189 */
190 public void warn(Object message, Throwable t) {
191 logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, t);
192 }
193
194 /**
195 * Converts the input parameter to String and then delegates to the wrapped
196 * <code>org.slf4j.Logger</code> instance.
197 *
198 * @param message
199 * the message to log. Converted to {@link String}
200 */
201 public void error(Object message) {
202 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null);
203 }
204
205 /**
206 * Converts the first input parameter to String and then delegates to the
207 * wrapped <code>org.slf4j.Logger</code> instance.
208 *
209 * @param message
210 * the message to log. Converted to {@link String}
211 * @param t
212 * the exception to log
213 */
214 public void error(Object message, Throwable t) {
215 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t);
216 }
217
218 /**
219 * Converts the input parameter to String and then delegates to the error
220 * method of the wrapped <code>org.slf4j.Logger</code> instance.
221 *
222 * @param message
223 * the message to log. Converted to {@link String}
224 */
225 public void fatal(Object message) {
226 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null);
227 }
228
229 /**
230 * Converts the first input parameter to String and then delegates to the
231 * error method of the wrapped <code>org.slf4j.Logger</code> instance.
232 *
233 * @param message
234 * the message to log. Converted to {@link String}
235 * @param t
236 * the exception to log
237 */
238 public void fatal(Object message, Throwable t) {
239 logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t);
240 }
241
242 /**
243 * Replace this instance with a homonymous (same name) logger returned by
244 * LoggerFactory. Note that this method is only called during deserialization.
245 *
246 * @return logger with same name as returned by LoggerFactory
247 * @throws ObjectStreamException
248 */
249 protected Object readResolve() throws ObjectStreamException {
250 Logger logger = LoggerFactory.getLogger(this.name);
251 return new SLF4JLocationAwareLog((LocationAwareLogger) logger);
252 }
253 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.ObjectStreamException;
19 import java.io.Serializable;
20
21 import org.apache.commons.logging.Log;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 /**
26 * Implementation of {@link Log org.apache.commons.logging.Log} interface which
27 * delegates all processing to a wrapped {@link Logger org.slf4j.Logger}
28 * instance.
29 *
30 * <p>
31 * JCL's FATAL level is mapped to ERROR. All other levels map one to one.
32 *
33 * @author Ceki G&uuml;lc&uuml;
34 */
35 public class SLF4JLog implements Log, Serializable {
36
37 private static final long serialVersionUID = 680728617011167209L;
38
39 // used to store this logger's name to recreate it after serialization
40 protected String name;
41
42 // in both Log4jLogger and Jdk14Logger classes in the original JCL, the
43 // logger instance is transient
44 private transient Logger logger;
45
46 SLF4JLog(Logger logger) {
47 this.logger = logger;
48 this.name = logger.getName();
49 }
50
51 /**
52 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
53 */
54 public boolean isDebugEnabled() {
55 return logger.isDebugEnabled();
56 }
57
58 /**
59 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
60 */
61 public boolean isErrorEnabled() {
62 return logger.isErrorEnabled();
63 }
64
65 /**
66 * Delegates to the <code>isErrorEnabled<code> method of the wrapped
67 * <code>org.slf4j.Logger</code> instance.
68 */
69 public boolean isFatalEnabled() {
70 return logger.isErrorEnabled();
71 }
72
73 /**
74 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
75 */
76 public boolean isInfoEnabled() {
77 return logger.isInfoEnabled();
78 }
79
80 /**
81 * Delegates to the <code>isDebugEnabled<code> method of the wrapped
82 * <code>org.slf4j.Logger</code> instance.
83 */
84 public boolean isTraceEnabled() {
85 return logger.isTraceEnabled();
86 }
87
88 /**
89 * Directly delegates to the wrapped <code>org.slf4j.Logger</code> instance.
90 */
91 public boolean isWarnEnabled() {
92 return logger.isWarnEnabled();
93 }
94
95 /**
96 * Converts the input parameter to String and then delegates to the debug
97 * method of the wrapped <code>org.slf4j.Logger</code> instance.
98 *
99 * @param message
100 * the message to log. Converted to {@link String}
101 */
102 public void trace(Object message) {
103 logger.trace(String.valueOf(message));
104 }
105
106 /**
107 * Converts the first input parameter to String and then delegates to the
108 * debug method of the wrapped <code>org.slf4j.Logger</code> instance.
109 *
110 * @param message
111 * the message to log. Converted to {@link String}
112 * @param t
113 * the exception to log
114 */
115 public void trace(Object message, Throwable t) {
116 logger.trace(String.valueOf(message), t);
117 }
118
119 /**
120 * Converts the input parameter to String and then delegates to the wrapped
121 * <code>org.slf4j.Logger</code> instance.
122 *
123 * @param message
124 * the message to log. Converted to {@link String}
125 */
126 public void debug(Object message) {
127 logger.debug(String.valueOf(message));
128 }
129
130 /**
131 * Converts the first input parameter to String and then delegates to the
132 * wrapped <code>org.slf4j.Logger</code> instance.
133 *
134 * @param message
135 * the message to log. Converted to {@link String}
136 * @param t
137 * the exception to log
138 */
139 public void debug(Object message, Throwable t) {
140 logger.debug(String.valueOf(message), t);
141 }
142
143 /**
144 * Converts the input parameter to String and then delegates to the wrapped
145 * <code>org.slf4j.Logger</code> instance.
146 *
147 * @param message
148 * the message to log. Converted to {@link String}
149 */
150 public void info(Object message) {
151 logger.info(String.valueOf(message));
152 }
153
154 /**
155 * Converts the first input parameter to String and then delegates to the
156 * wrapped <code>org.slf4j.Logger</code> instance.
157 *
158 * @param message
159 * the message to log. Converted to {@link String}
160 * @param t
161 * the exception to log
162 */
163 public void info(Object message, Throwable t) {
164 logger.info(String.valueOf(message), t);
165 }
166
167 /**
168 * Converts the input parameter to String and then delegates to the wrapped
169 * <code>org.slf4j.Logger</code> instance.
170 *
171 * @param message
172 * the message to log. Converted to {@link String}
173 */
174 public void warn(Object message) {
175 logger.warn(String.valueOf(message));
176 }
177
178 /**
179 * Converts the first input parameter to String and then delegates to the
180 * wrapped <code>org.slf4j.Logger</code> instance.
181 *
182 * @param message
183 * the message to log. Converted to {@link String}
184 * @param t
185 * the exception to log
186 */
187 public void warn(Object message, Throwable t) {
188 logger.warn(String.valueOf(message), t);
189 }
190
191 /**
192 * Converts the input parameter to String and then delegates to the wrapped
193 * <code>org.slf4j.Logger</code> instance.
194 *
195 * @param message
196 * the message to log. Converted to {@link String}
197 */
198 public void error(Object message) {
199 logger.error(String.valueOf(message));
200 }
201
202 /**
203 * Converts the first input parameter to String and then delegates to the
204 * wrapped <code>org.slf4j.Logger</code> instance.
205 *
206 * @param message
207 * the message to log. Converted to {@link String}
208 * @param t
209 * the exception to log
210 */
211 public void error(Object message, Throwable t) {
212 logger.error(String.valueOf(message), t);
213 }
214
215 /**
216 * Converts the input parameter to String and then delegates to the error
217 * method of the wrapped <code>org.slf4j.Logger</code> instance.
218 *
219 * @param message
220 * the message to log. Converted to {@link String}
221 */
222 public void fatal(Object message) {
223 logger.error(String.valueOf(message));
224 }
225
226 /**
227 * Converts the first input parameter to String and then delegates to the
228 * error method of the wrapped <code>org.slf4j.Logger</code> instance.
229 *
230 * @param message
231 * the message to log. Converted to {@link String}
232 * @param t
233 * the exception to log
234 */
235 public void fatal(Object message, Throwable t) {
236 logger.error(String.valueOf(message), t);
237 }
238
239 /**
240 * Replace this instance with a homonymous (same name) logger returned by
241 * LoggerFactory. Note that this method is only called during deserialization.
242 *
243 * @return logger with same name as returned by LoggerFactory
244 * @throws ObjectStreamException
245 */
246 protected Object readResolve() throws ObjectStreamException {
247 Logger logger = LoggerFactory.getLogger(this.name);
248 return new SLF4JLog(logger);
249 }
250 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogConfigurationException;
20 import org.apache.commons.logging.LogFactory;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23 import org.slf4j.spi.LocationAwareLogger;
24
25 import java.util.ArrayList;
26 import java.util.Enumeration;
27 import java.util.Hashtable;
28 import java.util.List;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31
32 /**
33 * <p>
34 * Concrete subclass of {@link LogFactory} which always delegates to the
35 * {@link LoggerFactory org.slf4j.LoggerFactory} class.
36 *
37 * <p>
38 * This factory generates instances of {@link SLF4JLog}. It will remember
39 * previously created instances for the same name, and will return them on
40 * repeated requests to the <code>getInstance()</code> method.
41 *
42 * <p>
43 * This implementation ignores any configured attributes.
44 * </p>
45 *
46 * @author Rod Waldhoff
47 * @author Craig R. McClanahan
48 * @author Richard A. Sitze
49 * @author Ceki G&uuml;lc&uuml;
50 */
51 @SuppressWarnings("rawtypes")
52 public class SLF4JLogFactory extends LogFactory {
53
54 // ----------------------------------------------------------- Constructors
55
56 /**
57 * The {@link org.apache.commons.logging.Log}instances that have already been
58 * created, keyed by logger name.
59 */
60 ConcurrentMap<String, Log> loggerMap;
61
62 /**
63 * Public no-arguments constructor required by the lookup mechanism.
64 */
65 public SLF4JLogFactory() {
66 loggerMap = new ConcurrentHashMap<String, Log>();
67 }
68
69 // ----------------------------------------------------- Manifest Constants
70
71 /**
72 * The name of the system property identifying our {@link Log}implementation
73 * class.
74 */
75 public static final String LOG_PROPERTY = "org.apache.commons.logging.Log";
76
77 // ----------------------------------------------------- Instance Variables
78
79 /**
80 * Configuration attributes.
81 */
82 protected Hashtable attributes = new Hashtable();
83
84 // --------------------------------------------------------- Public Methods
85
86 /**
87 * Return the configuration attribute with the specified name (if any), or
88 * <code>null</code> if there is no such attribute.
89 *
90 * @param name
91 * Name of the attribute to return
92 */
93 public Object getAttribute(String name) {
94
95 return (attributes.get(name));
96
97 }
98
99 /**
100 * Return an array containing the names of all currently defined configuration
101 * attributes. If there are no such attributes, a zero length array is
102 * returned.
103 */
104 @SuppressWarnings("unchecked")
105 public String[] getAttributeNames() {
106
107 List<String> names = new ArrayList<String>();
108 Enumeration<String> keys = attributes.keys();
109 while (keys.hasMoreElements()) {
110 names.add((String) keys.nextElement());
111 }
112 String results[] = new String[names.size()];
113 for (int i = 0; i < results.length; i++) {
114 results[i] = (String) names.get(i);
115 }
116 return (results);
117
118 }
119
120 /**
121 * Convenience method to derive a name from the specified class and call
122 * <code>getInstance(String)</code> with it.
123 *
124 * @param clazz
125 * Class for which a suitable Log name will be derived
126 *
127 * @exception LogConfigurationException
128 * if a suitable <code>Log</code> instance cannot be returned
129 */
130 public Log getInstance(Class clazz) throws LogConfigurationException {
131 return (getInstance(clazz.getName()));
132 }
133
134 /**
135 * <p>
136 * Construct (if necessary) and return a <code>Log</code> instance, using
137 * the factory's current set of configuration attributes.
138 * </p>
139 *
140 * @param name
141 * Logical name of the <code>Log</code> instance to be returned
142 * (the meaning of this name is only known to the underlying logging
143 * implementation that is being wrapped)
144 *
145 * @exception LogConfigurationException
146 * if a suitable <code>Log</code> instance cannot be returned
147 */
148 public Log getInstance(String name) throws LogConfigurationException {
149 Log instance = loggerMap.get(name);
150 if (instance != null) {
151 return instance;
152 } else {
153 Log newInstance;
154 Logger slf4jLogger = LoggerFactory.getLogger(name);
155 if (slf4jLogger instanceof LocationAwareLogger) {
156 newInstance = new SLF4JLocationAwareLog((LocationAwareLogger) slf4jLogger);
157 } else {
158 newInstance = new SLF4JLog(slf4jLogger);
159 }
160 Log oldInstance = loggerMap.putIfAbsent(name, newInstance);
161 return oldInstance == null ? newInstance : oldInstance;
162 }
163 }
164
165 /**
166 * Release any internal references to previously created
167 * {@link org.apache.commons.logging.Log}instances returned by this factory.
168 * This is useful in environments like servlet containers, which implement
169 * application reloading by throwing away a ClassLoader. Dangling references
170 * to objects in that class loader would prevent garbage collection.
171 */
172 public void release() {
173 // This method is never called by jcl-over-slf4j classes. However,
174 // in certain deployment scenarios, in particular if jcl-over-slf4j.jar
175 // is
176 // in the the web-app class loader and the official commons-logging.jar is
177 // deployed in some parent class loader (e.g. commons/lib), then it is
178 // possible
179 // for the parent class loader to mask the classes shipping in
180 // jcl-over-slf4j.jar.
181 System.out.println("WARN: The method " + SLF4JLogFactory.class + "#release() was invoked.");
182 System.out.println("WARN: Please see http://www.slf4j.org/codes.html#release for an explanation.");
183 System.out.flush();
184 }
185
186 /**
187 * Remove any configuration attribute associated with the specified name. If
188 * there is no such attribute, no action is taken.
189 *
190 * @param name
191 * Name of the attribute to remove
192 */
193 public void removeAttribute(String name) {
194 attributes.remove(name);
195 }
196
197 /**
198 * Set the configuration attribute with the specified name. Calling this with
199 * a <code>null</code> value is equivalent to calling
200 * <code>removeAttribute(name)</code>.
201 *
202 * @param name
203 * Name of the attribute to set
204 * @param value
205 * Value of the attribute to set, or <code>null</code> to remove
206 * any setting for this attribute
207 */
208 @SuppressWarnings("unchecked")
209 public void setAttribute(String name, Object value) {
210
211 if (value == null) {
212 attributes.remove(name);
213 } else {
214 attributes.put(name, value);
215 }
216
217 }
218 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.commons.logging.impl;
17
18 import java.io.InputStream;
19 import java.io.Serializable;
20 import java.lang.reflect.InvocationTargetException;
21 import java.lang.reflect.Method;
22 import java.security.AccessController;
23 import java.security.PrivilegedAction;
24 import java.text.DateFormat;
25 import java.text.SimpleDateFormat;
26 import java.util.Date;
27 import java.util.Properties;
28
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogConfigurationException;
31
32 /**
33 * <p>
34 * Simple implementation of Log that sends all enabled log messages, for all
35 * defined loggers, to System.err. The following system properties are supported
36 * to configure the behavior of this logger:
37 * </p>
38 * <ul>
39 * <li><code>org.apache.commons.logging.simplelog.defaultlog</code> - Default
40 * logging detail level for all instances of SimpleLog. Must be one of ("trace",
41 * "debug", "info", "warn", "error", or "fatal"). If not specified, defaults to
42 * "info".</li>
43 * <li><code>org.apache.commons.logging.simplelog.log.xxxxx</code> - Logging
44 * detail level for a SimpleLog instance named "xxxxx". Must be one of ("trace",
45 * "debug", "info", "warn", "error", or "fatal"). If not specified, the default
46 * logging detail level is used.</li>
47 * <li><code>org.apache.commons.logging.simplelog.showlogname</code> - Set to
48 * <code>true</code> if you want the Log instance name to be included in output
49 * messages. Defaults to <code>false</code>.</li>
50 * <li><code>org.apache.commons.logging.simplelog.showShortLogname</code> - Set
51 * to <code>true</code> if you want the last component of the name to be
52 * included in output messages. Defaults to <code>true</code>.</li>
53 * <li><code>org.apache.commons.logging.simplelog.showdatetime</code> - Set to
54 * <code>true</code> if you want the current date and time to be included in
55 * output messages. Default is <code>false</code>.</li>
56 * <li><code>org.apache.commons.logging.simplelog.dateTimeFormat</code> - The
57 * date and time format to be used in the output messages. The pattern
58 * describing the date and time format is the same that is used in
59 * <code>java.text.SimpleDateFormat</code>. If the format is not specified or is
60 * invalid, the default format is used. The default format is
61 * <code>yyyy/MM/dd HH:mm:ss:SSS zzz</code>.</li>
62 * </ul>
63 *
64 * <p>
65 * In addition to looking for system properties with the names specified above,
66 * this implementation also checks for a class loader resource named
67 * <code>"simplelog.properties"</code>, and includes any matching definitions
68 * from this resource (if it exists).
69 * </p>
70 *
71 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
72 * @author Rod Waldhoff
73 * @author Robert Burrell Donkin
74 *
75 * @version $Id: SimpleLog.java,v 1.21 2004/06/06 20:47:56 rdonkin Exp $
76 */
77 public class SimpleLog implements Log, Serializable {
78
79 private static final long serialVersionUID = 136942970684951178L;
80
81 // ------------------------------------------------------- Class Attributes
82
83 /** All system properties used by <code>SimpleLog</code> start with this */
84 static protected final String systemPrefix = "org.apache.commons.logging.simplelog.";
85
86 /** Properties loaded from simplelog.properties */
87 static protected final Properties simpleLogProps = new Properties();
88
89 /** The default format to use when formating dates */
90 static protected final String DEFAULT_DATE_TIME_FORMAT = "yyyy/MM/dd HH:mm:ss:SSS zzz";
91
92 /** Include the instance name in the log message? */
93 static protected boolean showLogName = false;
94 /**
95 * Include the short name ( last component ) of the logger in the log message.
96 * Defaults to true - otherwise we'll be lost in a flood of messages without
97 * knowing who sends them.
98 */
99 static protected boolean showShortName = true;
100 /** Include the current time in the log message */
101 static protected boolean showDateTime = false;
102 /** The date and time format to use in the log message */
103 static protected String dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
104 /** Used to format times */
105 static protected DateFormat dateFormatter = null;
106
107 // ---------------------------------------------------- Log Level Constants
108
109 /** "Trace" level logging. */
110 public static final int LOG_LEVEL_TRACE = 1;
111 /** "Debug" level logging. */
112 public static final int LOG_LEVEL_DEBUG = 2;
113 /** "Info" level logging. */
114 public static final int LOG_LEVEL_INFO = 3;
115 /** "Warn" level logging. */
116 public static final int LOG_LEVEL_WARN = 4;
117 /** "Error" level logging. */
118 public static final int LOG_LEVEL_ERROR = 5;
119 /** "Fatal" level logging. */
120 public static final int LOG_LEVEL_FATAL = 6;
121
122 /** Enable all logging levels */
123 public static final int LOG_LEVEL_ALL = (LOG_LEVEL_TRACE - 1);
124
125 /** Enable no logging levels */
126 public static final int LOG_LEVEL_OFF = (LOG_LEVEL_FATAL + 1);
127
128 // ------------------------------------------------------------ Initializer
129
130 private static String getStringProperty(String name) {
131 String prop = null;
132 try {
133 prop = System.getProperty(name);
134 } catch (SecurityException e) {
135 ; // Ignore
136 }
137 return (prop == null) ? simpleLogProps.getProperty(name) : prop;
138 }
139
140 private static String getStringProperty(String name, String dephault) {
141 String prop = getStringProperty(name);
142 return (prop == null) ? dephault : prop;
143 }
144
145 private static boolean getBooleanProperty(String name, boolean dephault) {
146 String prop = getStringProperty(name);
147 return (prop == null) ? dephault : "true".equalsIgnoreCase(prop);
148 }
149
150 // Initialize class attributes.
151 // Load properties file, if found.
152 // Override with system properties.
153 static {
154 // Add props from the resource simplelog.properties
155 InputStream in = getResourceAsStream("simplelog.properties");
156 if (null != in) {
157 try {
158 simpleLogProps.load(in);
159 in.close();
160 } catch (java.io.IOException e) {
161 // ignored
162 }
163 }
164
165 showLogName = getBooleanProperty(systemPrefix + "showlogname", showLogName);
166 showShortName = getBooleanProperty(systemPrefix + "showShortLogname", showShortName);
167 showDateTime = getBooleanProperty(systemPrefix + "showdatetime", showDateTime);
168
169 if (showDateTime) {
170 dateTimeFormat = getStringProperty(systemPrefix + "dateTimeFormat", dateTimeFormat);
171 try {
172 dateFormatter = new SimpleDateFormat(dateTimeFormat);
173 } catch (IllegalArgumentException e) {
174 // If the format pattern is invalid - use the default format
175 dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
176 dateFormatter = new SimpleDateFormat(dateTimeFormat);
177 }
178 }
179 }
180
181 // ------------------------------------------------------------- Attributes
182
183 /** The name of this simple log instance */
184 protected String logName = null;
185 /** The current log level */
186 protected int currentLogLevel;
187 /** The short name of this simple log instance */
188 private String shortLogName = null;
189
190 // ------------------------------------------------------------ Constructor
191
192 /**
193 * Construct a simple log with given name.
194 *
195 * @param name
196 * log name
197 */
198 public SimpleLog(String name) {
199
200 logName = name;
201
202 // Set initial log level
203 // Used to be: set default log level to ERROR
204 // IMHO it should be lower, but at least info ( costin ).
205 setLevel(SimpleLog.LOG_LEVEL_INFO);
206
207 // Set log level from properties
208 String lvl = getStringProperty(systemPrefix + "log." + logName);
209 int i = String.valueOf(name).lastIndexOf(".");
210 while (null == lvl && i > -1) {
211 name = name.substring(0, i);
212 lvl = getStringProperty(systemPrefix + "log." + name);
213 i = String.valueOf(name).lastIndexOf(".");
214 }
215
216 if (null == lvl) {
217 lvl = getStringProperty(systemPrefix + "defaultlog");
218 }
219
220 if ("all".equalsIgnoreCase(lvl)) {
221 setLevel(SimpleLog.LOG_LEVEL_ALL);
222 } else if ("trace".equalsIgnoreCase(lvl)) {
223 setLevel(SimpleLog.LOG_LEVEL_TRACE);
224 } else if ("debug".equalsIgnoreCase(lvl)) {
225 setLevel(SimpleLog.LOG_LEVEL_DEBUG);
226 } else if ("info".equalsIgnoreCase(lvl)) {
227 setLevel(SimpleLog.LOG_LEVEL_INFO);
228 } else if ("warn".equalsIgnoreCase(lvl)) {
229 setLevel(SimpleLog.LOG_LEVEL_WARN);
230 } else if ("error".equalsIgnoreCase(lvl)) {
231 setLevel(SimpleLog.LOG_LEVEL_ERROR);
232 } else if ("fatal".equalsIgnoreCase(lvl)) {
233 setLevel(SimpleLog.LOG_LEVEL_FATAL);
234 } else if ("off".equalsIgnoreCase(lvl)) {
235 setLevel(SimpleLog.LOG_LEVEL_OFF);
236 }
237
238 }
239
240 // -------------------------------------------------------- Properties
241
242 /**
243 * <p>
244 * Set logging level.
245 * </p>
246 *
247 * @param currentLogLevel
248 * new logging level
249 */
250 public void setLevel(int currentLogLevel) {
251
252 this.currentLogLevel = currentLogLevel;
253
254 }
255
256 /**
257 * <p>
258 * Get logging level.
259 * </p>
260 */
261 public int getLevel() {
262
263 return currentLogLevel;
264 }
265
266 // -------------------------------------------------------- Logging Methods
267
268 /**
269 * <p>
270 * Do the actual logging. This method assembles the message and then calls
271 * <code>write()</code> to cause it to be written.
272 * </p>
273 *
274 * @param type
275 * One of the LOG_LEVEL_XXX constants defining the log level
276 * @param message
277 * The message itself (typically a String)
278 * @param t
279 * The exception whose stack trace should be logged
280 */
281 protected void log(int type, Object message, Throwable t) {
282 // Use a string buffer for better performance
283 StringBuffer buf = new StringBuffer();
284
285 // Append date-time if so configured
286 if (showDateTime) {
287 buf.append(dateFormatter.format(new Date()));
288 buf.append(" ");
289 }
290
291 // Append a readable representation of the log level
292 switch (type) {
293 case SimpleLog.LOG_LEVEL_TRACE:
294 buf.append("[TRACE] ");
295 break;
296 case SimpleLog.LOG_LEVEL_DEBUG:
297 buf.append("[DEBUG] ");
298 break;
299 case SimpleLog.LOG_LEVEL_INFO:
300 buf.append("[INFO] ");
301 break;
302 case SimpleLog.LOG_LEVEL_WARN:
303 buf.append("[WARN] ");
304 break;
305 case SimpleLog.LOG_LEVEL_ERROR:
306 buf.append("[ERROR] ");
307 break;
308 case SimpleLog.LOG_LEVEL_FATAL:
309 buf.append("[FATAL] ");
310 break;
311 }
312
313 // Append the name of the log instance if so configured
314 if (showShortName) {
315 if (shortLogName == null) {
316 // Cut all but the last component of the name for both styles
317 shortLogName = logName.substring(logName.lastIndexOf(".") + 1);
318 shortLogName = shortLogName.substring(shortLogName.lastIndexOf("/") + 1);
319 }
320 buf.append(String.valueOf(shortLogName)).append(" - ");
321 } else if (showLogName) {
322 buf.append(String.valueOf(logName)).append(" - ");
323 }
324
325 // Append the message
326 buf.append(String.valueOf(message));
327
328 // Append stack trace if not null
329 if (t != null) {
330 buf.append(" <");
331 buf.append(t.toString());
332 buf.append(">");
333
334 java.io.StringWriter sw = new java.io.StringWriter(1024);
335 java.io.PrintWriter pw = new java.io.PrintWriter(sw);
336 t.printStackTrace(pw);
337 pw.close();
338 buf.append(sw.toString());
339 }
340
341 // Print to the appropriate destination
342 write(buf);
343
344 }
345
346 /**
347 * <p>
348 * Write the content of the message accumulated in the specified
349 * <code>StringBuffer</code> to the appropriate output destination. The
350 * default implementation writes to <code>System.err</code>.
351 * </p>
352 *
353 * @param buffer
354 * A <code>StringBuffer</code> containing the accumulated text to be
355 * logged
356 */
357 protected void write(StringBuffer buffer) {
358
359 System.err.println(buffer.toString());
360
361 }
362
363 /**
364 * Is the given log level currently enabled?
365 *
366 * @param logLevel
367 * is this level enabled?
368 */
369 protected boolean isLevelEnabled(int logLevel) {
370 // log level are numerically ordered so can use simple numeric
371 // comparison
372 return (logLevel >= currentLogLevel);
373 }
374
375 // -------------------------------------------------------- Log Implementation
376
377 /**
378 * <p>
379 * Log a message with debug log level.
380 * </p>
381 */
382 public final void debug(Object message) {
383
384 if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
385 log(SimpleLog.LOG_LEVEL_DEBUG, message, null);
386 }
387 }
388
389 /**
390 * <p>
391 * Log an error with debug log level.
392 * </p>
393 */
394 public final void debug(Object message, Throwable t) {
395
396 if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
397 log(SimpleLog.LOG_LEVEL_DEBUG, message, t);
398 }
399 }
400
401 /**
402 * <p>
403 * Log a message with trace log level.
404 * </p>
405 */
406 public final void trace(Object message) {
407
408 if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
409 log(SimpleLog.LOG_LEVEL_TRACE, message, null);
410 }
411 }
412
413 /**
414 * <p>
415 * Log an error with trace log level.
416 * </p>
417 */
418 public final void trace(Object message, Throwable t) {
419
420 if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
421 log(SimpleLog.LOG_LEVEL_TRACE, message, t);
422 }
423 }
424
425 /**
426 * <p>
427 * Log a message with info log level.
428 * </p>
429 */
430 public final void info(Object message) {
431
432 if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
433 log(SimpleLog.LOG_LEVEL_INFO, message, null);
434 }
435 }
436
437 /**
438 * <p>
439 * Log an error with info log level.
440 * </p>
441 */
442 public final void info(Object message, Throwable t) {
443
444 if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
445 log(SimpleLog.LOG_LEVEL_INFO, message, t);
446 }
447 }
448
449 /**
450 * <p>
451 * Log a message with warn log level.
452 * </p>
453 */
454 public final void warn(Object message) {
455
456 if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
457 log(SimpleLog.LOG_LEVEL_WARN, message, null);
458 }
459 }
460
461 /**
462 * <p>
463 * Log an error with warn log level.
464 * </p>
465 */
466 public final void warn(Object message, Throwable t) {
467
468 if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
469 log(SimpleLog.LOG_LEVEL_WARN, message, t);
470 }
471 }
472
473 /**
474 * <p>
475 * Log a message with error log level.
476 * </p>
477 */
478 public final void error(Object message) {
479
480 if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
481 log(SimpleLog.LOG_LEVEL_ERROR, message, null);
482 }
483 }
484
485 /**
486 * <p>
487 * Log an error with error log level.
488 * </p>
489 */
490 public final void error(Object message, Throwable t) {
491
492 if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
493 log(SimpleLog.LOG_LEVEL_ERROR, message, t);
494 }
495 }
496
497 /**
498 * <p>
499 * Log a message with fatal log level.
500 * </p>
501 */
502 public final void fatal(Object message) {
503
504 if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
505 log(SimpleLog.LOG_LEVEL_FATAL, message, null);
506 }
507 }
508
509 /**
510 * <p>
511 * Log an error with fatal log level.
512 * </p>
513 */
514 public final void fatal(Object message, Throwable t) {
515
516 if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
517 log(SimpleLog.LOG_LEVEL_FATAL, message, t);
518 }
519 }
520
521 /**
522 * <p>
523 * Are debug messages currently enabled?
524 * </p>
525 *
526 * <p>
527 * This allows expensive operations such as <code>String</code> concatenation
528 * to be avoided when the message will be ignored by the logger.
529 * </p>
530 */
531 public final boolean isDebugEnabled() {
532
533 return isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG);
534 }
535
536 /**
537 * <p>
538 * Are error messages currently enabled?
539 * </p>
540 *
541 * <p>
542 * This allows expensive operations such as <code>String</code> concatenation
543 * to be avoided when the message will be ignored by the logger.
544 * </p>
545 */
546 public final boolean isErrorEnabled() {
547
548 return isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR);
549 }
550
551 /**
552 * <p>
553 * Are fatal messages currently enabled?
554 * </p>
555 *
556 * <p>
557 * This allows expensive operations such as <code>String</code> concatenation
558 * to be avoided when the message will be ignored by the logger.
559 * </p>
560 */
561 public final boolean isFatalEnabled() {
562
563 return isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL);
564 }
565
566 /**
567 * <p>
568 * Are info messages currently enabled?
569 * </p>
570 *
571 * <p>
572 * This allows expensive operations such as <code>String</code> concatenation
573 * to be avoided when the message will be ignored by the logger.
574 * </p>
575 */
576 public final boolean isInfoEnabled() {
577
578 return isLevelEnabled(SimpleLog.LOG_LEVEL_INFO);
579 }
580
581 /**
582 * <p>
583 * Are trace messages currently enabled?
584 * </p>
585 *
586 * <p>
587 * This allows expensive operations such as <code>String</code> concatenation
588 * to be avoided when the message will be ignored by the logger.
589 * </p>
590 */
591 public final boolean isTraceEnabled() {
592
593 return isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE);
594 }
595
596 /**
597 * <p>
598 * Are warn messages currently enabled?
599 * </p>
600 *
601 * <p>
602 * This allows expensive operations such as <code>String</code> concatenation
603 * to be avoided when the message will be ignored by the logger.
604 * </p>
605 */
606 public final boolean isWarnEnabled() {
607
608 return isLevelEnabled(SimpleLog.LOG_LEVEL_WARN);
609 }
610
611 /**
612 * Return the thread context class loader if available. Otherwise return null.
613 *
614 * The thread context class loader is available for JDK 1.2 or later, if
615 * certain security conditions are met.
616 *
617 * @exception LogConfigurationException
618 * if a suitable class loader cannot be identified.
619 */
620 private static ClassLoader getContextClassLoader() {
621 ClassLoader classLoader = null;
622
623 if (classLoader == null) {
624 try {
625 // Are we running on a JDK 1.2 or later system?
626 Method method = Thread.class.getMethod("getContextClassLoader");
627
628 // Get the thread context class loader (if there is one)
629 try {
630 classLoader = (ClassLoader) method.invoke(Thread.currentThread());
631 } catch (IllegalAccessException e) {
632 ; // ignore
633 } catch (InvocationTargetException e) {
634 /**
635 * InvocationTargetException is thrown by 'invoke' when the method
636 * being invoked (getContextClassLoader) throws an exception.
637 *
638 * getContextClassLoader() throws SecurityException when the context
639 * class loader isn't an ancestor of the calling class's class loader,
640 * or if security permissions are restricted.
641 *
642 * In the first case (not related), we want to ignore and keep going.
643 * We cannot help but also ignore the second with the logic below, but
644 * other calls elsewhere (to obtain a class loader) will trigger this
645 * exception where we can make a distinction.
646 */
647 if (e.getTargetException() instanceof SecurityException) {
648 ; // ignore
649 } else {
650 // Capture 'e.getTargetException()' exception for details
651 // alternate: log 'e.getTargetException()', and pass back 'e'.
652 throw new LogConfigurationException("Unexpected InvocationTargetException", e.getTargetException());
653 }
654 }
655 } catch (NoSuchMethodException e) {
656 // Assume we are running on JDK 1.1
657 ; // ignore
658 }
659 }
660
661 if (classLoader == null) {
662 classLoader = SimpleLog.class.getClassLoader();
663 }
664
665 // Return the selected class loader
666 return classLoader;
667 }
668
669 private static InputStream getResourceAsStream(final String name) {
670 return AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
671 public InputStream run() {
672 ClassLoader threadCL = getContextClassLoader();
673
674 if (threadCL != null) {
675 return threadCL.getResourceAsStream(name);
676 } else {
677 return ClassLoader.getSystemResourceAsStream(name);
678 }
679 }
680 });
681 }
682 }
0 <body>
1
2 <p>SLF4J based implementation of commons-logging wrapper APIs.</p>
3
4 </body>
0 <!--
1
2 Copyright 2001-2004 The Apache Software Foundation.
3
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
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
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.
15
16 -->
17
18 <body>
19 <p>Jakarta Commons Logging implemented over SLF4J.</p>
20
21
22 <h3>Overview</h3>
23
24 <p>This package contains the same public user interface as <a
25 href="http://jakarta.apache.org/commons/logging/">Jakarta Commons
26 Logging (JCL)</a>. It is intended as a 100% compatible drop-in
27 replacement for the original JCL version 1.0.4.
28 </p>
29
30 <p>As the original JCL version 1.0.4, the present version supports
31 various logging APIs. It differs from the original in implementation
32 but not the public API. This implementation uses SLF4J under the
33 covers. As as such, all the logging systems that SLF4J supports,
34 e.g. NOP, Simple, JDK14, nlog4j are supported by this version of JCL.
35 </p>
36
37 <h3>Quick Start Guide</h3>
38
39 <p>For those impatient to just get on with it, the following example
40 illustrates the typical declaration and use of a logger that is named (by
41 convention) after the calling class:
42
43 <pre>
44 import org.apache.commons.logging.Log;
45 import org.apache.commons.logging.LogFactory;
46
47 public class Foo {
48
49 static Log log = LogFactory.getLog(Foo.class);
50
51 public void foo() {
52 ...
53 try {
54 if (log.isDebugEnabled()) {
55 log.debug("About to do something to object " + name);
56 }
57 name.bar();
58 } catch (IllegalStateException e) {
59 log.error("Something bad happened to " + name, e);
60 }
61 ...
62 }
63 </pre>
64
65 <h3>Configuring the Commons Logging Package</h3>
66
67 <p>In this version of JCL, the selection of the logging system to use
68 is chosen by the underlying SLF4J API. Consequently, all JCL-specific
69 configuration parameters are ignored.
70 </p>
71
72 <h4>Choosing a <code>LogFactory</code> Implementation</h4>
73
74 <p>From an application perspective, the first requirement is to
75 retrieve an object reference to the <code>LogFactory</code> instance
76 that will be used to create <code><a href="Log.html">Log</a></code>
77 instances for this application. This is normally accomplished by
78 calling the static <code>getFactory()</code> method. This method
79 always returns the same factory, i.e. a unique instance of the <a
80 href="impl/SLF4FLogFactory.html">SLF4FLogFactory</a> class.
81 </p>
82
83
84
85 <h4>Configuring the Underlying Logging System</h4>
86
87 <p>The basic principle is that the user is totally responsible for the
88 configuration of the underlying logging system.
89 Commons-logging should not change the existing configuration.</p>
90
91 <p>Each individual <a href="Log.html">Log</a> implementation may
92 support its own configuration properties. These will be documented in the
93 class descriptions for the corresponding implementation class.</p>
94
95 <p>Finally, some <code>Log</code> implementations (such as the one for Log4J)
96 require an external configuration file for the entire logging environment.
97 This file should be prepared in a manner that is specific to the actual logging
98 technology being used.</p>
99
100
101 <h3>Using the Logging Package APIs</h3>
102
103 <p>Use of the Logging Package APIs, from the perspective of an application
104 component, consists of the following steps:</p>
105 <ol>
106 <li>Acquire a reference to an instance of
107 <a href="Log.html">org.apache.commons.logging.Log</a>, by calling the
108 factory method
109 <a href="LogFactory.html#getInstance(java.lang.String)">
110 LogFactory.getInstance(String name)</a>. Your application can contain
111 references to multiple loggers that are used for different
112 purposes. A typical scenario for a server application is to have each
113 major component of the server use its own Log instance.</li>
114 <li>Cause messages to be logged (if the corresponding detail level is enabled)
115 by calling appropriate methods (<code>trace()</code>, <code>debug()</code>,
116 <code>info()</code>, <code>warn()</code>, <code>error</code>, and
117 <code>fatal()</code>).</li>
118 </ol>
119
120 <p>For convenience, <code>LogFactory</code> also offers a static method
121 <code>getLog()</code> that combines the typical two-step pattern:</p>
122 <pre>
123 Log log = LogFactory.getFactory().getInstance(Foo.class);
124 </pre>
125 <p>into a single method call:</p>
126 <pre>
127 Log log = LogFactory.getLog(Foo.class);
128 </pre>
129
130 <p>For example, you might use the following technique to initialize and
131 use a <a href="Log.html">Log</a> instance in an application component:</p>
132 <pre>
133 import org.apache.commons.logging.Log;
134 import org.apache.commons.logging.LogFactory;
135
136 public class MyComponent {
137
138 protected static Log log =
139 LogFactory.getLog(MyComponent.class);
140
141 // Called once at startup time
142 public void start() {
143 ...
144 log.info("MyComponent started");
145 ...
146 }
147
148 // Called once at shutdown time
149 public void stop() {
150 ...
151 log.info("MyComponent stopped");
152 ...
153 }
154
155 // Called repeatedly to process a particular argument value
156 // which you want logged if debugging is enabled
157 public void process(String value) {
158 ...
159 // Do the string concatenation only if logging is enabled
160 if (log.isDebugEnabled())
161 log.debug("MyComponent processing " + value);
162 ...
163 }
164
165 }
166 </pre>
167
168 </body>
0 Implementation-Title: jcl-over-slf4j
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: jcl.over.slf4j
3 Bundle-Name: jcl-over-slf4j
4 Bundle-Vendor: SLF4J.ORG
5 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
8 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}
0 org.apache.commons.logging.impl.SLF4JLogFactory
1
2 # Axis gets at JCL through its own mechanism as defined by Commons Discovery, which
3 # in turn follows the instructions found at:
4 # http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service Provider
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.apache.commons.logging;
26
27 import junit.framework.TestCase;
28
29 public class InvokeJCLTest extends TestCase {
30
31 public void testIsEnabledAPI() {
32 // assume that we are running over slf4j-jdk14
33 Log log = LogFactory.getLog(InvokeJCLTest.class);
34 assertFalse(log.isTraceEnabled());
35 assertFalse(log.isDebugEnabled());
36 assertTrue(log.isInfoEnabled());
37 assertTrue(log.isWarnEnabled());
38 assertTrue(log.isErrorEnabled());
39 assertTrue(log.isFatalEnabled());
40 }
41
42 public void testPrintAPI() {
43 Log log = LogFactory.getLog(InvokeJCLTest.class);
44 Exception e = new Exception("just testing");
45
46 log.trace(null);
47 log.trace("trace message");
48
49 log.debug(null);
50 log.debug("debug message");
51
52 log.info(null);
53 log.info("info message");
54
55 log.warn(null);
56 log.warn("warn message");
57
58 log.error(null);
59 log.error("error message");
60
61 log.fatal(null);
62 log.fatal("fatal message");
63
64 log.trace(null, e);
65 log.trace("trace message", e);
66
67 log.debug(null, e);
68 log.debug("debug message", e);
69
70 log.info(null, e);
71 log.info("info message", e);
72
73 log.warn(null, e);
74 log.warn("warn message", e);
75
76 log.error(null, e);
77 log.error("error message", e);
78
79 log.fatal(null, e);
80 log.fatal("fatal message", e);
81 }
82 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.apache.commons.logging.impl;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
28 import java.io.IOException;
29 import java.io.ObjectInputStream;
30 import java.io.ObjectOutputStream;
31
32 import junit.framework.TestCase;
33
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.slf4j.impl.JDK14LoggerFactory;
37 import org.slf4j.spi.LocationAwareLogger;
38
39 public class SerializationTest extends TestCase {
40
41 ObjectInputStream ois;
42 ByteArrayOutputStream baos = new ByteArrayOutputStream();
43 ObjectOutputStream oos;
44
45 public SerializationTest(String name) {
46 super(name);
47 }
48
49 protected void setUp() throws Exception {
50 oos = new ObjectOutputStream(baos);
51 super.setUp();
52 }
53
54 protected void tearDown() throws Exception {
55 super.tearDown();
56 oos.close();
57 }
58
59 public void verify() throws IOException, ClassNotFoundException {
60 ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
61 ois = new ObjectInputStream(bis);
62
63 Log resuscitatedLog = (Log) ois.readObject();
64 // tests that the "private transient Logger logger" field is non-null
65 resuscitatedLog.debug("");
66 resuscitatedLog.isDebugEnabled();
67 }
68
69 public void testSLF4JLog() throws Exception {
70 JDK14LoggerFactory factory = new JDK14LoggerFactory();
71 SLF4JLog log = new SLF4JLog(factory.getLogger("x"));
72 oos.writeObject(log);
73 verify();
74 }
75
76 public void testSmoke() throws Exception {
77 Log log = LogFactory.getLog("testing");
78 oos.writeObject(log);
79 verify();
80 }
81
82 public void testLocationAware() throws Exception {
83 JDK14LoggerFactory factory = new JDK14LoggerFactory();
84 SLF4JLocationAwareLog log = new SLF4JLocationAwareLog((LocationAwareLogger) factory.getLogger("x"));
85 oos.writeObject(log);
86 verify();
87 }
88 }
0 <project
1 xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
5 <modelVersion>4.0.0</modelVersion>
6
7 <parent>
8 <groupId>org.slf4j</groupId>
9 <artifactId>slf4j-parent</artifactId>
10 <version>1.7.12</version>
11 </parent>
12
13 <artifactId>jul-to-slf4j</artifactId>
14
15 <packaging>jar</packaging>
16 <name>JUL to SLF4J bridge</name>
17 <description>JUL to SLF4J bridge</description>
18
19 <url>http://www.slf4j.org</url>
20
21 <dependencies>
22 <dependency>
23 <groupId>org.slf4j</groupId>
24 <artifactId>slf4j-api</artifactId>
25 </dependency>
26 <dependency>
27 <groupId>org.slf4j</groupId>
28 <artifactId>slf4j-log4j12</artifactId>
29 <version>${project.version}</version>
30 <scope>test</scope>
31 </dependency>
32 </dependencies>
33
34 <build>
35 <plugins>
36 <plugin>
37 <groupId>org.apache.maven.plugins</groupId>
38 <artifactId>maven-compiler-plugin</artifactId>
39 <configuration>
40 <source>${required.jdk.version}</source>
41 <target>${required.jdk.version}</target>
42 </configuration>
43 </plugin>
44 <plugin>
45 <groupId>org.apache.maven.plugins</groupId>
46 <artifactId>maven-jar-plugin</artifactId>
47 <configuration>
48 <archive>
49 <manifestEntries>
50 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
51 <Bundle-Description>${project.description}</Bundle-Description>
52 <Implementation-Version>${project.version}
53 </Implementation-Version>
54 </manifestEntries>
55 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
56 </archive>
57 </configuration>
58 </plugin>
59
60 </plugins>
61 </build>
62
63 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import java.text.MessageFormat;
27 import java.util.MissingResourceException;
28 import java.util.ResourceBundle;
29 import java.util.logging.Handler;
30 import java.util.logging.Level;
31 import java.util.logging.LogManager;
32 import java.util.logging.LogRecord;
33
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.slf4j.spi.LocationAwareLogger;
37
38 // Based on http://bugzilla.slf4j.org/show_bug.cgi?id=38
39
40 /**
41 * <p>Bridge/route all JUL log records to the SLF4J API.</p>
42 * <p>Essentially, the idea is to install on the root logger an instance of
43 * <code>SLF4JBridgeHandler</code> as the sole JUL handler in the system. Subsequently, the
44 * SLF4JBridgeHandler instance will redirect all JUL log records are redirected
45 * to the SLF4J API based on the following mapping of levels:
46 * </p>
47 * <pre>
48 * FINEST -&gt; TRACE
49 * FINER -&gt; DEBUG
50 * FINE -&gt; DEBUG
51 * INFO -&gt; INFO
52 * WARNING -&gt; WARN
53 * SEVERE -&gt; ERROR</pre>
54 * <p><b>Programmatic installation:</b></p>
55 * <pre>
56 * // Optionally remove existing handlers attached to j.u.l root logger
57 * SLF4JBridgeHandler.removeHandlersForRootLogger(); // (since SLF4J 1.6.5)
58
59 * // add SLF4JBridgeHandler to j.u.l's root logger, should be done once during
60 * // the initialization phase of your application
61 * SLF4JBridgeHandler.install();</pre>
62 * <p><b>Installation via <em>logging.properties</em> configuration file:</b></p>
63 * <pre>
64 * // register SLF4JBridgeHandler as handler for the j.u.l. root logger
65 * handlers = org.slf4j.bridge.SLF4JBridgeHandler</pre>
66 * <p>Once SLF4JBridgeHandler is installed, logging by j.u.l. loggers will be directed to
67 * SLF4J. Example: </p>
68 * <pre>
69 * import java.util.logging.Logger;
70 * ...
71 * // usual pattern: get a Logger and then log a message
72 * Logger julLogger = Logger.getLogger(&quot;org.wombat&quot;);
73 * julLogger.fine(&quot;hello world&quot;); // this will get redirected to SLF4J</pre>
74 *
75 * <p>Please note that translating a java.util.logging event into SLF4J incurs the
76 * cost of constructing {@link LogRecord} instance regardless of whether the
77 * SLF4J logger is disabled for the given level. <b>Consequently, j.u.l. to
78 * SLF4J translation can seriously increase the cost of disabled logging
79 * statements (60 fold or 6000% increase) and measurably impact the performance of enabled log
80 * statements (20% overall increase).</b> Please note that as of logback-version 0.9.25,
81 * it is possible to completely eliminate the 60 fold translation overhead for disabled
82 * log statements with the help of <a href="http://logback.qos.ch/manual/configuration.html#LevelChangePropagator">LevelChangePropagator</a>.
83 * </p>
84 *
85 * <p>If you are concerned about application performance, then use of <code>SLF4JBridgeHandler</code>
86 * is appropriate only if any one the following two conditions is true:</p>
87 * <ol>
88 * <li>few j.u.l. logging statements are in play</li>
89 * <li>LevelChangePropagator has been installed</li>
90 * </ol>
91 *
92 * @author Christian Stein
93 * @author Joern Huxhorn
94 * @author Ceki G&uuml;lc&uuml;
95 * @author Darryl Smith
96 * @since 1.5.1
97 */
98 public class SLF4JBridgeHandler extends Handler {
99
100 // The caller is java.util.logging.Logger
101 private static final String FQCN = java.util.logging.Logger.class.getName();
102 private static final String UNKNOWN_LOGGER_NAME = "unknown.jul.logger";
103
104 private static final int TRACE_LEVEL_THRESHOLD = Level.FINEST.intValue();
105 private static final int DEBUG_LEVEL_THRESHOLD = Level.FINE.intValue();
106 private static final int INFO_LEVEL_THRESHOLD = Level.INFO.intValue();
107 private static final int WARN_LEVEL_THRESHOLD = Level.WARNING.intValue();
108
109 /**
110 * Adds a SLF4JBridgeHandler instance to jul's root logger.
111 * <p/>
112 * <p/>
113 * This handler will redirect j.u.l. logging to SLF4J. However, only logs enabled
114 * in j.u.l. will be redirected. For example, if a log statement invoking a
115 * j.u.l. logger is disabled, then the corresponding non-event will <em>not</em>
116 * reach SLF4JBridgeHandler and cannot be redirected.
117 */
118 public static void install() {
119 LogManager.getLogManager().getLogger("").addHandler(new SLF4JBridgeHandler());
120 }
121
122 private static java.util.logging.Logger getRootLogger() {
123 return LogManager.getLogManager().getLogger("");
124 }
125
126 /**
127 * Removes previously installed SLF4JBridgeHandler instances. See also
128 * {@link #install()}.
129 *
130 * @throws SecurityException A <code>SecurityException</code> is thrown, if a security manager
131 * exists and if the caller does not have
132 * LoggingPermission("control").
133 */
134 public static void uninstall() throws SecurityException {
135 java.util.logging.Logger rootLogger = getRootLogger();
136 Handler[] handlers = rootLogger.getHandlers();
137 for (int i = 0; i < handlers.length; i++) {
138 if (handlers[i] instanceof SLF4JBridgeHandler) {
139 rootLogger.removeHandler(handlers[i]);
140 }
141 }
142 }
143
144 /**
145 * Returns true if SLF4JBridgeHandler has been previously installed, returns false otherwise.
146 *
147 * @return true if SLF4JBridgeHandler is already installed, false other wise
148 * @throws SecurityException
149 */
150 public static boolean isInstalled() throws SecurityException {
151 java.util.logging.Logger rootLogger = getRootLogger();
152 Handler[] handlers = rootLogger.getHandlers();
153 for (int i = 0; i < handlers.length; i++) {
154 if (handlers[i] instanceof SLF4JBridgeHandler) {
155 return true;
156 }
157 }
158 return false;
159 }
160
161 /**
162 * Invoking this method removes/unregisters/detaches all handlers currently attached to the root logger
163 * @since 1.6.5
164 */
165 public static void removeHandlersForRootLogger() {
166 java.util.logging.Logger rootLogger = getRootLogger();
167 java.util.logging.Handler[] handlers = rootLogger.getHandlers();
168 for (int i = 0; i < handlers.length; i++) {
169 rootLogger.removeHandler(handlers[i]);
170 }
171 }
172
173 /**
174 * Initialize this handler.
175 */
176 public SLF4JBridgeHandler() {
177 }
178
179 /**
180 * No-op implementation.
181 */
182 public void close() {
183 // empty
184 }
185
186 /**
187 * No-op implementation.
188 */
189 public void flush() {
190 // empty
191 }
192
193 /**
194 * Return the Logger instance that will be used for logging.
195 */
196 protected Logger getSLF4JLogger(LogRecord record) {
197 String name = record.getLoggerName();
198 if (name == null) {
199 name = UNKNOWN_LOGGER_NAME;
200 }
201 return LoggerFactory.getLogger(name);
202 }
203
204 protected void callLocationAwareLogger(LocationAwareLogger lal, LogRecord record) {
205 int julLevelValue = record.getLevel().intValue();
206 int slf4jLevel;
207
208 if (julLevelValue <= TRACE_LEVEL_THRESHOLD) {
209 slf4jLevel = LocationAwareLogger.TRACE_INT;
210 } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) {
211 slf4jLevel = LocationAwareLogger.DEBUG_INT;
212 } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) {
213 slf4jLevel = LocationAwareLogger.INFO_INT;
214 } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) {
215 slf4jLevel = LocationAwareLogger.WARN_INT;
216 } else {
217 slf4jLevel = LocationAwareLogger.ERROR_INT;
218 }
219 String i18nMessage = getMessageI18N(record);
220 lal.log(null, FQCN, slf4jLevel, i18nMessage, null, record.getThrown());
221 }
222
223 protected void callPlainSLF4JLogger(Logger slf4jLogger, LogRecord record) {
224 String i18nMessage = getMessageI18N(record);
225 int julLevelValue = record.getLevel().intValue();
226 if (julLevelValue <= TRACE_LEVEL_THRESHOLD) {
227 slf4jLogger.trace(i18nMessage, record.getThrown());
228 } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) {
229 slf4jLogger.debug(i18nMessage, record.getThrown());
230 } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) {
231 slf4jLogger.info(i18nMessage, record.getThrown());
232 } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) {
233 slf4jLogger.warn(i18nMessage, record.getThrown());
234 } else {
235 slf4jLogger.error(i18nMessage, record.getThrown());
236 }
237 }
238
239 /**
240 * Get the record's message, possibly via a resource bundle.
241 *
242 * @param record
243 * @return
244 */
245 private String getMessageI18N(LogRecord record) {
246 String message = record.getMessage();
247
248 if (message == null) {
249 return null;
250 }
251
252 ResourceBundle bundle = record.getResourceBundle();
253 if (bundle != null) {
254 try {
255 message = bundle.getString(message);
256 } catch (MissingResourceException e) {
257 }
258 }
259 Object[] params = record.getParameters();
260 // avoid formatting when there are no or 0 parameters. see also
261 // http://bugzilla.slf4j.org/show_bug.cgi?id=212
262 if (params != null && params.length > 0) {
263 message = MessageFormat.format(message, params);
264 }
265 return message;
266 }
267
268 /**
269 * Publish a LogRecord.
270 * <p/>
271 * The logging request was made initially to a Logger object, which
272 * initialized the LogRecord and forwarded it here.
273 * <p/>
274 * This handler ignores the Level attached to the LogRecord, as SLF4J cares
275 * about discarding log statements.
276 *
277 * @param record Description of the log event. A null record is silently ignored
278 * and is not published.
279 */
280 public void publish(LogRecord record) {
281 // Silently ignore null records.
282 if (record == null) {
283 return;
284 }
285
286 Logger slf4jLogger = getSLF4JLogger(record);
287 String message = record.getMessage(); // can be null!
288 // this is a check to avoid calling the underlying logging system
289 // with a null message. While it is legitimate to invoke j.u.l. with
290 // a null message, other logging frameworks do not support this.
291 // see also http://bugzilla.slf4j.org/show_bug.cgi?id=108
292 if (message == null) {
293 message = "";
294 }
295 if (slf4jLogger instanceof LocationAwareLogger) {
296 callLocationAwareLogger((LocationAwareLogger) slf4jLogger, record);
297 } else {
298 callPlainSLF4JLogger(slf4jLogger, record);
299 }
300 }
301
302 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9
10 <p>Bridge/route all JUL log records to the SLF4J API.</p>
11
12 <hr/>
13 </body>
14 </html>
0 Bundle-ManifestVersion: 2
1 Bundle-SymbolicName: jul.to.slf4j
2 Bundle-Name: jul-to-slf4j
3 Bundle-Vendor: SLF4J.ORG
4 Bundle-RequiredExecutionEnvironment: J2SE-1.5
5 Export-Package: org.slf4j.bridge;version=${parsedVersion.osgiVersion};uses:="org.slf4j,org.slf4j.spi"
6 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},org.slf4j.spi;version=${parsedVersion.osgiVersion}
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.log4j.AppenderSkeleton;
30 import org.apache.log4j.spi.LoggingEvent;
31
32 public class ListAppender extends AppenderSkeleton {
33
34 public List<LoggingEvent> list = new ArrayList<LoggingEvent>();
35
36 public boolean extractLocationInfo = false;
37
38 protected void append(LoggingEvent event) {
39 list.add(event);
40 if (extractLocationInfo) {
41 event.getLocationInformation();
42 }
43 }
44
45 public void close() {
46 }
47
48 public boolean requiresLayout() {
49 return false;
50 }
51
52 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import java.util.logging.Handler;
27 import java.util.logging.LogManager;
28
29 import junit.framework.TestCase;
30
31 import org.apache.log4j.FileAppender;
32 import org.apache.log4j.PatternLayout;
33 import org.slf4j.LoggerFactory;
34
35 public class SLF4JBridgeHandlerPerfTest extends TestCase {
36
37 static String LOGGER_NAME = "yay";
38 static int RUN_LENGTH = 100 * 1000;
39
40 // set to false to test enabled logging performance
41 boolean disabledLogger = true;
42
43 FileAppender fileAppender;
44 org.apache.log4j.Logger log4jRoot;
45 java.util.logging.Logger julRootLogger = LogManager.getLogManager().getLogger("");
46
47 java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(LOGGER_NAME);
48 org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(LOGGER_NAME);
49
50 Handler[] existingHandlers;
51
52 public SLF4JBridgeHandlerPerfTest(String arg0) {
53 super(arg0);
54 }
55
56 protected void setUp() throws Exception {
57 super.setUp();
58 fileAppender = new FileAppender(new PatternLayout("%r [%t] %p %c %x - %m%n"), "target/test-output/toto.log");
59
60 existingHandlers = julRootLogger.getHandlers();
61 for (int i = 0; i < existingHandlers.length; i++) {
62 julRootLogger.removeHandler(existingHandlers[i]);
63 }
64 log4jRoot = org.apache.log4j.Logger.getRootLogger();
65 log4jRoot.addAppender(fileAppender);
66 }
67
68 protected void tearDown() throws Exception {
69 super.tearDown();
70 SLF4JBridgeHandler.uninstall();
71 fileAppender.close();
72 log4jRoot.getLoggerRepository().resetConfiguration();
73 for (int i = 0; i < existingHandlers.length; i++) {
74 julRootLogger.addHandler(existingHandlers[i]);
75 }
76 }
77
78 double julLoggerLoop() {
79 long start = System.nanoTime();
80 for (int i = 0; i < RUN_LENGTH; i++) {
81 julLogger.info("jul");
82 }
83 long end = System.nanoTime();
84 return (end - start) * 1.0 / RUN_LENGTH;
85 }
86
87 double slf4jLoggerLoop() {
88 long start = System.nanoTime();
89 for (int i = 0; i < RUN_LENGTH; i++) {
90 slf4jLogger.info("slf4j");
91 }
92 long end = System.nanoTime();
93 return (end - start) * 1.0 / RUN_LENGTH;
94 }
95
96 public void testPerf() {
97 SLF4JBridgeHandler.install();
98
99 if (disabledLogger) {
100 log4jRoot.setLevel(org.apache.log4j.Level.ERROR);
101 }
102 julLoggerLoop();
103 double julAvg = julLoggerLoop();
104 System.out.println("Average cost per call (JUL->SLF4J->log4j): " + julAvg + " nanos");
105
106 slf4jLoggerLoop();
107 double slf4jAvg = slf4jLoggerLoop();
108 System.out.println("Average cost per call (SLF4J->log4j): " + slf4jAvg + " nanos");
109 System.out.println("Ratio " + (julAvg / slf4jAvg));
110 }
111 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.bridge;
25
26 import java.text.MessageFormat;
27 import java.util.ResourceBundle;
28 import java.util.logging.Level;
29
30 import junit.framework.TestCase;
31
32 import org.apache.log4j.spi.LocationInfo;
33 import org.apache.log4j.spi.LoggingEvent;
34
35 public class SLF4JBridgeHandlerTest extends TestCase {
36
37 static String LOGGER_NAME = "yay";
38
39 ListAppender listAppender = new ListAppender();
40 org.apache.log4j.Logger log4jRoot;
41 java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger("yay");
42
43 public SLF4JBridgeHandlerTest(String arg0) {
44 super(arg0);
45 }
46
47 protected void setUp() throws Exception {
48 super.setUp();
49 listAppender.extractLocationInfo = true;
50 log4jRoot = org.apache.log4j.Logger.getRootLogger();
51 log4jRoot.addAppender(listAppender);
52 log4jRoot.setLevel(org.apache.log4j.Level.TRACE);
53 }
54
55 protected void tearDown() throws Exception {
56 super.tearDown();
57 SLF4JBridgeHandler.uninstall();
58 log4jRoot.getLoggerRepository().resetConfiguration();
59 }
60
61 public void testSmoke() {
62 SLF4JBridgeHandler.install();
63 String msg = "msg";
64 julLogger.info(msg);
65 assertEquals(1, listAppender.list.size());
66 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
67 assertEquals(LOGGER_NAME, le.getLoggerName());
68 assertEquals(msg, le.getMessage());
69
70 // get the location info in the event.
71 // Note that this must have been computed previously
72 // within an appender for the following assertion to
73 // work properly
74 LocationInfo li = le.getLocationInformation();
75 System.out.println(li.fullInfo);
76 assertEquals("SLF4JBridgeHandlerTest.java", li.getFileName());
77 assertEquals("testSmoke", li.getMethodName());
78 }
79
80 public void testLevels() {
81 SLF4JBridgeHandler.install();
82 String msg = "msg";
83 julLogger.setLevel(Level.ALL);
84
85 julLogger.finest(msg);
86 julLogger.finer(msg);
87 julLogger.fine(msg);
88 julLogger.info(msg);
89 julLogger.warning(msg);
90 julLogger.severe(msg);
91
92 assertEquals(6, listAppender.list.size());
93 int i = 0;
94 assertLevel(i++, org.apache.log4j.Level.TRACE);
95 assertLevel(i++, org.apache.log4j.Level.DEBUG);
96 assertLevel(i++, org.apache.log4j.Level.DEBUG);
97 assertLevel(i++, org.apache.log4j.Level.INFO);
98 assertLevel(i++, org.apache.log4j.Level.WARN);
99 assertLevel(i++, org.apache.log4j.Level.ERROR);
100 }
101
102 public void testLogWithResourceBundle() {
103 SLF4JBridgeHandler.install();
104
105 String resourceBundleName = "org.slf4j.bridge.testLogStrings";
106 ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName);
107 String resourceKey = "resource_key";
108 String expectedMsg = bundle.getString(resourceKey);
109 String msg = resourceKey;
110
111 java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("yay", resourceBundleName);
112
113 julResourceBundleLogger.info(msg);
114 assertEquals(1, listAppender.list.size());
115 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
116 assertEquals(LOGGER_NAME, le.getLoggerName());
117 assertEquals(expectedMsg, le.getMessage());
118 }
119
120 public void testLogWithResourceBundleWithParameters() {
121 SLF4JBridgeHandler.install();
122
123 String resourceBundleName = "org.slf4j.bridge.testLogStrings";
124 ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName);
125
126 java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("foo", resourceBundleName);
127
128 String resourceKey1 = "resource_key_1";
129 String expectedMsg1 = bundle.getString(resourceKey1);
130 julResourceBundleLogger.info(resourceKey1); // 1st log
131
132 String resourceKey2 = "resource_key_2";
133 Object[] params2 = new Object[] { "foo", "bar" };
134 String expectedMsg2 = MessageFormat.format(bundle.getString(resourceKey2), params2);
135 julResourceBundleLogger.log(Level.INFO, resourceKey2, params2); // 2nd log
136
137 String resourceKey3 = "invalidKey {0}";
138 Object[] params3 = new Object[] { "John" };
139 String expectedMsg3 = MessageFormat.format(resourceKey3, params3);
140 julResourceBundleLogger.log(Level.INFO, resourceKey3, params3); // 3rd log
141
142 julLogger.log(Level.INFO, resourceKey3, params3); // 4th log
143
144 assertEquals(4, listAppender.list.size());
145
146 LoggingEvent le = null;
147
148 le = (LoggingEvent) listAppender.list.get(0);
149 assertEquals("foo", le.getLoggerName());
150 assertEquals(expectedMsg1, le.getMessage());
151
152 le = (LoggingEvent) listAppender.list.get(1);
153 assertEquals("foo", le.getLoggerName());
154 assertEquals(expectedMsg2, le.getMessage());
155
156 le = (LoggingEvent) listAppender.list.get(2);
157 assertEquals("foo", le.getLoggerName());
158 assertEquals(expectedMsg3, le.getMessage());
159
160 le = (LoggingEvent) listAppender.list.get(3);
161 assertEquals("yay", le.getLoggerName());
162 assertEquals(expectedMsg3, le.getMessage());
163 }
164
165 public void testLogWithPlaceholderNoParameters() {
166 SLF4JBridgeHandler.install();
167 String msg = "msg {non-number-string}";
168 julLogger.logp(Level.INFO, "SLF4JBridgeHandlerTest", "testLogWithPlaceholderNoParameters", msg, new Object[0]);
169
170 assertEquals(1, listAppender.list.size());
171 LoggingEvent le = (LoggingEvent) listAppender.list.get(0);
172 assertEquals(LOGGER_NAME, le.getLoggerName());
173 assertEquals(msg, le.getMessage());
174 }
175
176 void assertLevel(int index, org.apache.log4j.Level expectedLevel) {
177 LoggingEvent le = (LoggingEvent) listAppender.list.get(index);
178 assertEquals(expectedLevel, le.getLevel());
179 }
180 }
0 resource_key=msg
1 resource_key_1=msg
2 resource_key_2=msg {0} {1}
0 <project xmlns="http://maven.apache.org/POM/4.0.0"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.12</version>
10 </parent>
11
12
13 <artifactId>log4j-over-slf4j</artifactId>
14 <packaging>jar</packaging>
15 <name>Log4j Implemented Over SLF4J</name>
16 <description>Log4j implemented over SLF4J</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <licenses>
21 <license>
22 <name>Apache Software Licenses</name>
23 <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
24 </license>
25 </licenses>
26
27 <dependencies>
28 <dependency>
29 <groupId>org.slf4j</groupId>
30 <artifactId>slf4j-api</artifactId>
31 </dependency>
32
33 <dependency>
34 <groupId>org.slf4j</groupId>
35 <artifactId>slf4j-jdk14</artifactId>
36 <scope>test</scope>
37 </dependency>
38 </dependencies>
39
40
41 <build>
42 <plugins>
43
44 <plugin>
45 <groupId>org.apache.maven.plugins</groupId>
46 <artifactId>maven-jar-plugin</artifactId>
47 <configuration>
48 <archive>
49 <manifestEntries>
50 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
51 <Bundle-Description>${project.description}</Bundle-Description>
52 <Implementation-Version>${project.version}</Implementation-Version>
53 </manifestEntries>
54 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
55 </archive>
56 </configuration>
57 </plugin>
58
59 </plugins>
60 </build>
61
62 </project>
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.Filter;
19 import org.apache.log4j.spi.ErrorHandler;
20 import org.apache.log4j.spi.Layout;
21 import org.apache.log4j.spi.LoggingEvent;
22
23 /**
24 * Implement this interface for your own strategies for outputting log
25 * statements.
26 *
27 * @author Ceki G&uuml;lc&uuml;
28 */
29 public interface Appender {
30
31 /**
32 * Add a filter to the end of the filter list.
33 *
34 * @since 0.9.0
35 */
36 void addFilter(Filter newFilter);
37
38 /**
39 * Returns the head Filter. The Filters are organized in a linked list
40 * and so all Filters on this Appender are available through the result.
41 *
42 * @return the head Filter or null, if no Filters are present
43 * @since 1.1
44 */
45 public Filter getFilter();
46
47 /**
48 * Clear the list of filters by removing all the filters in it.
49 *
50 * @since 0.9.0
51 */
52 public void clearFilters();
53
54 /**
55 * Release any resources allocated within the appender such as file
56 * handles, network connections, etc.
57 * <p/>
58 * <p>It is a programming error to append to a closed appender.
59 *
60 * @since 0.8.4
61 */
62 public void close();
63
64 /**
65 * Log in <code>Appender</code> specific way. When appropriate,
66 * Loggers will call the <code>doAppend</code> method of appender
67 * implementations in order to log.
68 */
69 public void doAppend(LoggingEvent event);
70
71 /**
72 * Get the name of this appender. The name uniquely identifies the
73 * appender.
74 */
75 public String getName();
76
77 /**
78 * Set the {@link ErrorHandler} for this appender.
79 *
80 * @since 0.9.0
81 */
82 public void setErrorHandler(ErrorHandler errorHandler);
83
84 /**
85 * Returns the {@link ErrorHandler} for this appender.
86 *
87 * @since 1.1
88 */
89 public ErrorHandler getErrorHandler();
90
91 /**
92 * Set the {@link Layout} for this appender.
93 *
94 * @since 0.8.1
95 */
96 public void setLayout(Layout layout);
97
98 /**
99 * Returns this appenders layout.
100 *
101 * @since 1.1
102 */
103 public Layout getLayout();
104
105 /**
106 * Set the name of this appender. The name is used by other
107 * components to identify this appender.
108 *
109 * @since 0.8.1
110 */
111 public void setName(String name);
112
113 /**
114 * Configurators call this method to determine if the appender
115 * requires a layout. If this method returns <code>true</code>,
116 * meaning that layout is required, then the configurator will
117 * configure an layout using the configuration information at its
118 * disposal. If this method returns <code>false</code>, meaning that
119 * a layout is not required, then layout configuration will be
120 * skipped even if there is available layout configuration
121 * information at the disposal of the configurator..
122 * <p/>
123 * <p>In the rather exceptional case, where the appender
124 * implementation admits a layout but can also work without it, then
125 * the appender should return <code>true</code>.
126 *
127 * @since 0.8.4
128 */
129 public boolean requiresLayout();
130 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 import org.apache.log4j.spi.OptionHandler;
18
19 public class AppenderSkeleton implements OptionHandler {
20
21 public void setLayout(Layout layout) {
22 }
23
24 public void setName(String name) {
25 }
26
27 public void activateOptions() {
28 }
29
30 public void setThreshold(Priority threshold) {
31 }
32 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 /**
19 * A minimal (nop) implementation of BasicConfigurator.
20 */
21 public class BasicConfigurator {
22 public static void configure() {
23 }
24
25 public static void configure(Appender appender) {
26 }
27
28 public static void resetConfiguration() {
29 }
30 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.helpers.NullEnumeration;
19 import org.slf4j.LoggerFactory;
20 import org.slf4j.Marker;
21 import org.slf4j.MarkerFactory;
22 import org.slf4j.spi.LocationAwareLogger;
23
24 import java.util.Enumeration;
25
26 /**
27 * <p>
28 * This class is a minimal implementation of the original
29 * <code>org.apache.log4j.Category</code> class (as found in log4j 1.2) by
30 * delegation of all calls to a {@link org.slf4j.Logger} instance.
31 * </p>
32 *
33 * <p>
34 * Log4j's <code>trace</code>, <code>debug()</code>, <code>info()</code>,
35 * <code>warn()</code>, <code>error()</code> printing methods are directly
36 * mapped to their SLF4J equivalents. Log4j's <code>fatal()</code> printing
37 * method is mapped to SLF4J's <code>error()</code> method with a FATAL marker.
38 *
39 * @author S&eacute;bastien Pennec
40 * @author Ceki G&uuml;lc&uuml;
41 */
42 @SuppressWarnings("rawtypes")
43 public class Category {
44
45 private static final String CATEGORY_FQCN = Category.class.getName();
46
47 private String name;
48
49 protected org.slf4j.Logger slf4jLogger;
50 private org.slf4j.spi.LocationAwareLogger locationAwareLogger;
51
52 private static Marker FATAL_MARKER = MarkerFactory.getMarker("FATAL");
53
54 Category(String name) {
55 this.name = name;
56 slf4jLogger = LoggerFactory.getLogger(name);
57 if (slf4jLogger instanceof LocationAwareLogger) {
58 locationAwareLogger = (LocationAwareLogger) slf4jLogger;
59 }
60 }
61
62 public static Category getInstance(Class clazz) {
63 return Log4jLoggerFactory.getLogger(clazz.getName());
64 }
65
66 public static Category getInstance(String name) {
67 return Log4jLoggerFactory.getLogger(name);
68 }
69
70 public final Category getParent() {
71 return null;
72 }
73
74 /**
75 * Returns the obvious.
76 *
77 * @return
78 */
79 public String getName() {
80 return name;
81 }
82
83 public Appender getAppender(String name) {
84 return null;
85 }
86
87 public Enumeration getAllAppenders() {
88 return NullEnumeration.getInstance();
89 }
90
91 /**
92 * Return the level in effect for this category/logger.
93 *
94 * <p>
95 * The result is computed by simulation.
96 *
97 * @return
98 */
99 public Level getEffectiveLevel() {
100 if (slf4jLogger.isTraceEnabled()) {
101 return Level.TRACE;
102 }
103 if (slf4jLogger.isDebugEnabled()) {
104 return Level.DEBUG;
105 }
106 if (slf4jLogger.isInfoEnabled()) {
107 return Level.INFO;
108 }
109 if (slf4jLogger.isWarnEnabled()) {
110 return Level.WARN;
111 }
112 return Level.ERROR;
113 }
114
115 /**
116 * Returns the assigned {@link Level}, if any, for this Category. This
117 * implementation always returns null.
118 *
119 * @return Level - the assigned Level, can be <code>null</code>.
120 */
121 final public Level getLevel() {
122 return null;
123 }
124
125 /**
126 * @deprecated Please use {@link #getLevel} instead.
127 */
128 final public Level getPriority() {
129 return null;
130 }
131
132 /**
133 * Delegates to {@link org.slf4j.Logger#isDebugEnabled} method in SLF4J
134 */
135 public boolean isDebugEnabled() {
136 return slf4jLogger.isDebugEnabled();
137 }
138
139 /**
140 * Delegates to {@link org.slf4j.Logger#isInfoEnabled} method in SLF4J
141 */
142 public boolean isInfoEnabled() {
143 return slf4jLogger.isInfoEnabled();
144 }
145
146 /**
147 * Delegates tob {@link org.slf4j.Logger#isWarnEnabled} method in SLF4J
148 */
149 public boolean isWarnEnabled() {
150 return slf4jLogger.isWarnEnabled();
151 }
152
153 /**
154 * Delegates to {@link org.slf4j.Logger#isErrorEnabled} method in SLF4J
155 */
156 public boolean isErrorEnabled() {
157 return slf4jLogger.isErrorEnabled();
158 }
159
160 /**
161 * Determines whether the priority passed as parameter is enabled in the
162 * underlying SLF4J logger. Each log4j priority is mapped directly to its
163 * SLF4J equivalent, except for FATAL which is mapped as ERROR.
164 *
165 * @param p
166 * the priority to check against
167 * @return true if this logger is enabled for the given level, false
168 * otherwise.
169 */
170 public boolean isEnabledFor(Priority p) {
171 switch (p.level) {
172 case Level.TRACE_INT:
173 return slf4jLogger.isTraceEnabled();
174 case Level.DEBUG_INT:
175 return slf4jLogger.isDebugEnabled();
176 case Level.INFO_INT:
177 return slf4jLogger.isInfoEnabled();
178 case Level.WARN_INT:
179 return slf4jLogger.isWarnEnabled();
180 case Level.ERROR_INT:
181 return slf4jLogger.isErrorEnabled();
182 case Priority.FATAL_INT:
183 return slf4jLogger.isErrorEnabled();
184 }
185 return false;
186 }
187
188 void differentiatedLog(Marker marker, String fqcn, int level, Object message, Throwable t) {
189
190 String m = convertToString(message);
191 if (locationAwareLogger != null) {
192 locationAwareLogger.log(marker, fqcn, level, m, null, t);
193 } else {
194 switch (level) {
195 case LocationAwareLogger.TRACE_INT:
196 slf4jLogger.trace(marker, m);
197 break;
198 case LocationAwareLogger.DEBUG_INT:
199 slf4jLogger.debug(marker, m);
200 break;
201 case LocationAwareLogger.INFO_INT:
202 slf4jLogger.info(marker, m);
203 break;
204 case LocationAwareLogger.WARN_INT:
205 slf4jLogger.warn(marker, m);
206 break;
207 case LocationAwareLogger.ERROR_INT:
208 slf4jLogger.error(marker, m);
209 break;
210 }
211 }
212 }
213
214 /**
215 * Delegates to {@link org.slf4j.Logger#debug(String)} method of SLF4J.
216 */
217 public void debug(Object message) {
218 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.DEBUG_INT, message, null);
219 }
220
221 /**
222 * Delegates to {@link org.slf4j.Logger#debug(String,Throwable)} method in
223 * SLF4J.
224 */
225 public void debug(Object message, Throwable t) {
226 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.DEBUG_INT, message, t);
227 }
228
229 /**
230 * Delegates to {@link org.slf4j.Logger#info(String)} method in SLF4J.
231 */
232 public void info(Object message) {
233 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.INFO_INT, message, null);
234 }
235
236 /**
237 * Delegates to {@link org.slf4j.Logger#info(String,Throwable)} method in
238 * SLF4J.
239 */
240 public void info(Object message, Throwable t) {
241 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.INFO_INT, message, t);
242 }
243
244 /**
245 * Delegates to {@link org.slf4j.Logger#warn(String)} method in SLF4J.
246 */
247 public void warn(Object message) {
248 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.WARN_INT, message, null);
249 }
250
251 /**
252 * Delegates to {@link org.slf4j.Logger#warn(String,Throwable)} method in
253 * SLF4J.
254 */
255 public void warn(Object message, Throwable t) {
256 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.WARN_INT, message, t);
257 }
258
259 /**
260 * Delegates to {@link org.slf4j.Logger#error(String)} method in SLF4J.
261 */
262 public void error(Object message) {
263 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, null);
264 }
265
266 /**
267 * Delegates to {@link org.slf4j.Logger#error(String,Throwable)} method in
268 * SLF4J.
269 */
270 public void error(Object message, Throwable t) {
271 differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, t);
272 }
273
274 /**
275 * Delegates to {@link org.slf4j.Logger#error(String)} method in SLF4J.
276 */
277 public void fatal(Object message) {
278 differentiatedLog(FATAL_MARKER, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, null);
279 }
280
281 /**
282 * Delegates to {@link org.slf4j.Logger#error(String,Throwable)} method in
283 * SLF4J. In addition, the call is marked with a marker named "FATAL".
284 */
285 public void fatal(Object message, Throwable t) {
286 differentiatedLog(FATAL_MARKER, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, t);
287 }
288
289 protected void forcedLog(String FQCN, Priority p, Object msg, Throwable t) {
290 log(FQCN, p, msg, t);
291 }
292
293 // See also http://bugzilla.slf4j.org/show_bug.cgi?id=168
294 public void log(String FQCN, Priority p, Object msg, Throwable t) {
295 int levelInt = priorityToLevelInt(p);
296 differentiatedLog(null, FQCN, levelInt, msg, t);
297 }
298
299 public void log(Priority p, Object message, Throwable t) {
300 int levelInt = priorityToLevelInt(p);
301 differentiatedLog(null, CATEGORY_FQCN, levelInt, message, t);
302 }
303
304 public void log(Priority p, Object message) {
305 int levelInt = priorityToLevelInt(p);
306 differentiatedLog(null, CATEGORY_FQCN, levelInt, message, null);
307 }
308
309 private int priorityToLevelInt(Priority p) {
310 switch (p.level) {
311 case Level.TRACE_INT:
312 case Level.X_TRACE_INT:
313 return LocationAwareLogger.TRACE_INT;
314 case Priority.DEBUG_INT:
315 return LocationAwareLogger.DEBUG_INT;
316 case Priority.INFO_INT:
317 return LocationAwareLogger.INFO_INT;
318 case Priority.WARN_INT:
319 return LocationAwareLogger.WARN_INT;
320 case Priority.ERROR_INT:
321 return LocationAwareLogger.ERROR_INT;
322 case Priority.FATAL_INT:
323 return LocationAwareLogger.ERROR_INT;
324 default:
325 throw new IllegalStateException("Unknown Priority " + p);
326 }
327 }
328
329 protected final String convertToString(Object message) {
330 if (message == null) {
331 return (String) message;
332 } else {
333 return message.toString();
334 }
335 }
336
337 public void setAdditivity(boolean additive) {
338 // nothing to do
339 }
340
341 public void addAppender(Appender newAppender) {
342 // nothing to do
343 }
344
345 public void setLevel(Level level) {
346 // nothing to do
347 }
348
349 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class ConsoleAppender extends WriterAppender {
18
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class FileAppender extends WriterAppender {
18
19 public FileAppender() {
20 }
21
22 public FileAppender(Layout layout, String filename) {
23 }
24
25 public FileAppender(Layout layout, String filename, boolean append) {
26 }
27
28 public FileAppender(Layout layout, String filename, boolean append, boolean bufferedIO, int bufferSize) {
29 }
30 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Christian Trutz <christian.trutz@belaso.de>
17 package org.apache.log4j;
18
19 /**
20 * This class is a minimal implementation of the original Log4J class.
21 *
22 * @author Christian Trutz <christian.trutz@belaso.de>
23 * */
24 public class Layout {
25
26 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Kitching Simon <Simon.Kitching@orange.ch>
17 // Nicholas Wolff
18
19 package org.apache.log4j;
20
21 import java.io.IOException;
22 import java.io.ObjectInputStream;
23 import java.io.ObjectOutputStream;
24 import java.io.ObjectStreamException;
25 import java.io.Serializable;
26
27 /**
28 Defines the minimum set of levels recognized by the system, that is
29 <code>OFF</code>, <code>FATAL</code>, <code>ERROR</code>,
30 <code>WARN</code>, <code>INFO</code>, <code>DEBUG</code> and
31 <code>ALL</code>.
32
33 <p>The <code>Level</code> class may be subclassed to define a larger
34 level set.
35
36 @author Ceki G&uuml;lc&uuml;
37
38 */
39 public class Level extends Priority implements Serializable {
40
41 /**
42 * TRACE level integer value.
43 * @since 1.2.12
44 */
45 public static final int TRACE_INT = 5000;
46
47 // match jboss' xlevel
48 public static final int X_TRACE_INT = DEBUG_INT - 100;
49
50 /**
51 The <code>OFF</code> has the highest possible rank and is
52 intended to turn off logging. */
53 final static public Level OFF = new Level(OFF_INT, "OFF", 0);
54
55 /**
56 The <code>FATAL</code> level designates very severe error
57 events that will presumably lead the application to abort.
58 */
59 final static public Level FATAL = new Level(FATAL_INT, "FATAL", 0);
60
61 /**
62 The <code>ERROR</code> level designates error events that
63 might still allow the application to continue running. */
64 final static public Level ERROR = new Level(ERROR_INT, "ERROR", 3);
65
66 /**
67 The <code>WARN</code> level designates potentially harmful situations.
68 */
69 final static public Level WARN = new Level(WARN_INT, "WARN", 4);
70
71 /**
72 The <code>INFO</code> level designates informational messages
73 that highlight the progress of the application at coarse-grained
74 level. */
75 final static public Level INFO = new Level(INFO_INT, "INFO", 6);
76
77 /**
78 The <code>DEBUG</code> Level designates fine-grained
79 informational events that are most useful to debug an
80 application. */
81 final static public Level DEBUG = new Level(DEBUG_INT, "DEBUG", 7);
82
83 /**
84 * The <code>TRACE</code> Level designates finer-grained
85 * informational events than the <code>DEBUG</code level.
86 * @since 1.2.12
87 */
88 public static final Level TRACE = new Level(TRACE_INT, "TRACE", 7);
89
90 /**
91 The <code>ALL</code> has the lowest possible rank and is intended to
92 turn on all logging. */
93 final static public Level ALL = new Level(ALL_INT, "ALL", 7);
94
95 /**
96 * Serialization version id.
97 */
98 static final long serialVersionUID = 3491141966387921974L;
99
100 /**
101 Instantiate a Level object.
102 */
103 protected Level(int level, String levelStr, int syslogEquivalent) {
104 super(level, levelStr, syslogEquivalent);
105 }
106
107 /**
108 Convert the string passed as argument to a level. If the
109 conversion fails, then this method returns {@link #DEBUG}.
110 */
111 public static Level toLevel(String sArg) {
112 return (Level) toLevel(sArg, Level.DEBUG);
113 }
114
115 /**
116 Convert an integer passed as argument to a level. If the
117 conversion fails, then this method returns {@link #DEBUG}.
118
119 */
120 public static Level toLevel(int val) {
121 return (Level) toLevel(val, Level.DEBUG);
122 }
123
124 /**
125 Convert an integer passed as argument to a level. If the
126 conversion fails, then this method returns the specified default.
127 */
128 public static Level toLevel(int val, Level defaultLevel) {
129 switch (val) {
130 case ALL_INT:
131 return ALL;
132 case DEBUG_INT:
133 return Level.DEBUG;
134 case INFO_INT:
135 return Level.INFO;
136 case WARN_INT:
137 return Level.WARN;
138 case ERROR_INT:
139 return Level.ERROR;
140 case FATAL_INT:
141 return Level.FATAL;
142 case OFF_INT:
143 return OFF;
144 case TRACE_INT:
145 return Level.TRACE;
146 default:
147 return defaultLevel;
148 }
149 }
150
151 /**
152 Convert the string passed as argument to a level. If the
153 conversion fails, then this method returns the value of
154 <code>defaultLevel</code>.
155 */
156 public static Level toLevel(String sArg, Level defaultLevel) {
157 if (sArg == null)
158 return defaultLevel;
159
160 String s = sArg.toUpperCase();
161
162 if (s.equals("ALL"))
163 return Level.ALL;
164 if (s.equals("DEBUG"))
165 return Level.DEBUG;
166 if (s.equals("INFO"))
167 return Level.INFO;
168 if (s.equals("WARN"))
169 return Level.WARN;
170 if (s.equals("ERROR"))
171 return Level.ERROR;
172 if (s.equals("FATAL"))
173 return Level.FATAL;
174 if (s.equals("OFF"))
175 return Level.OFF;
176 if (s.equals("TRACE"))
177 return Level.TRACE;
178 return defaultLevel;
179 }
180
181 /**
182 * Custom deserialization of Level.
183 * @param s serialization stream.
184 * @throws IOException if IO exception.
185 * @throws ClassNotFoundException if class not found.
186 */
187 private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException {
188 s.defaultReadObject();
189 level = s.readInt();
190 syslogEquivalent = s.readInt();
191 levelStr = s.readUTF();
192 if (levelStr == null) {
193 levelStr = "";
194 }
195 }
196
197 /**
198 * Serialize level.
199 * @param s serialization stream.
200 * @throws IOException if exception during serialization.
201 */
202 private void writeObject(final ObjectOutputStream s) throws IOException {
203 s.defaultWriteObject();
204 s.writeInt(level);
205 s.writeInt(syslogEquivalent);
206 s.writeUTF(levelStr);
207 }
208
209 /**
210 * Resolved deserialized level to one of the stock instances.
211 * May be overriden in classes derived from Level.
212 * @return resolved object.
213 * @throws ObjectStreamException if exception during resolution.
214 */
215 private Object readResolve() throws ObjectStreamException {
216 //
217 // if the deserizalized object is exactly an instance of Level
218 //
219 if (getClass() == Level.class) {
220 return toLevel(level);
221 }
222 //
223 // extension of Level can't substitute stock item
224 //
225 return this;
226 }
227 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.LoggerFactory;
19 import org.slf4j.helpers.Util;
20
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ConcurrentMap;
23
24 /**
25 * This class is a factory that creates and maintains org.apache.log4j.Loggers
26 * wrapping org.slf4j.Loggers.
27 *
28 * It keeps a hashtable of all created org.apache.log4j.Logger instances so that
29 * all newly created instances are not duplicates of existing loggers.
30 *
31 * @author S&eacute;bastien Pennec
32 */
33 class Log4jLoggerFactory {
34
35 // String, Logger
36 private static ConcurrentMap<String, Logger> log4jLoggers = new ConcurrentHashMap<String, Logger>();
37
38 private static final String LOG4J_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#log4jDelegationLoop";
39
40 // check for delegation loops
41 static {
42 try {
43 Class.forName("org.slf4j.impl.Log4jLoggerFactory");
44 String part1 = "Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError. ";
45 String part2 = "See also " + LOG4J_DELEGATION_LOOP_URL + " for more details.";
46
47 Util.report(part1);
48 Util.report(part2);
49 throw new IllegalStateException(part1 + part2);
50 } catch (ClassNotFoundException e) {
51 // this is the good case
52 }
53 }
54
55 public static Logger getLogger(String name) {
56 org.apache.log4j.Logger instance = log4jLoggers.get(name);
57 if (instance != null) {
58 return instance;
59 } else {
60 Logger newInstance = new Logger(name);
61 Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance);
62 return oldInstance == null ? newInstance : oldInstance;
63 }
64 }
65
66 public static Logger getLogger(String name, LoggerFactory loggerFactory) {
67 org.apache.log4j.Logger instance = log4jLoggers.get(name);
68 if (instance != null) {
69 return instance;
70 } else {
71 Logger newInstance = loggerFactory.makeNewLoggerInstance(name);
72 Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance);
73 return oldInstance == null ? newInstance : oldInstance;
74 }
75 }
76 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.LoggerFactory;
19
20 import java.util.Enumeration;
21 import java.util.Vector;
22
23 /**
24 * <p/>
25 * This class is a minimal implementation of the original
26 * <code>org.apache.log4j.LogManager</code> class (as found in log4j 1.2)
27 * delegating all calls to SLF4J.
28 * <p/>
29 * <p/>
30 * This implementation does <b>NOT</b> implement the setRepositorySelector(),
31 * getLoggerRepository(), exists(), getCurrentLoggers(), shutdown() and
32 * resetConfiguration() methods which do not have SLF4J equivalents.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 @SuppressWarnings("rawtypes")
37 public class LogManager {
38
39 public static Logger getRootLogger() {
40 return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
41 }
42
43 public static Logger getLogger(final String name) {
44 return Log4jLoggerFactory.getLogger(name);
45 }
46
47 public static Logger getLogger(final Class clazz) {
48 return Log4jLoggerFactory.getLogger(clazz.getName());
49 }
50
51 /**
52 * Returns a logger instance created by loggerFactory. This method was requested in
53 * <a href="http://bugzilla.slf4j.org/show_bug.cgi?id=234">bug #234</a>. Note that
54 * log4j-over-slf4j does not ship with a LoggerFactory implementation. If this
55 * method is called, the caller must provide his/her own implementation.
56 *
57 * @param name the name of the desired logger
58 * @param loggerFactory an instance of {@link LoggerFactory}
59 * @return returns a logger instance created by loggerFactory
60 * @since 1.6.6
61 */
62 public static Logger getLogger(String name, LoggerFactory loggerFactory) {
63 return loggerFactory.makeNewLoggerInstance(name);
64 }
65
66 /**
67 * This bogus implementation returns an empty enumeration.
68 *
69 * @return
70 */
71 public static Enumeration getCurrentLoggers() {
72 return new Vector().elements();
73 }
74
75 /**
76 * Implemented as NOP.
77 */
78 public static void shutdown() {
79 }
80
81 /**
82 * Implemented as NOP.
83 */
84 public static void resetConfiguration() {
85 }
86 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.apache.log4j.spi.LoggerFactory;
19 import org.slf4j.spi.LocationAwareLogger;
20
21 /**
22 * <p>
23 * This class is a minimal implementation of the original
24 * <code>org.apache.log4j.Logger</code> class (as found in log4j 1.2)
25 * delegating all calls to a {@link org.slf4j.Logger} instance.
26 * </p>
27 *
28 * @author Ceki G&uuml;lc&uuml;
29 * */
30 @SuppressWarnings("rawtypes")
31 public class Logger extends Category {
32
33 private static final String LOGGER_FQCN = Logger.class.getName();
34
35 protected Logger(String name) {
36 super(name);
37 }
38
39 public static Logger getLogger(String name) {
40 return Log4jLoggerFactory.getLogger(name);
41 }
42
43 public static Logger getLogger(String name, LoggerFactory loggerFactory) {
44 return Log4jLoggerFactory.getLogger(name, loggerFactory);
45 }
46
47 public static Logger getLogger(Class clazz) {
48 return getLogger(clazz.getName());
49 }
50
51 /**
52 * Does the obvious.
53 *
54 * @return
55 */
56 public static Logger getRootLogger() {
57 return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
58 }
59
60 /**
61 * Delegates to {@link org.slf4j.Logger#isTraceEnabled}
62 * method of SLF4J.
63 */
64 public boolean isTraceEnabled() {
65 return slf4jLogger.isTraceEnabled();
66 }
67
68 /**
69 * Delegates to {@link org.slf4j.Logger#trace(String)} method in SLF4J.
70 */
71 public void trace(Object message) {
72 differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, null);
73 }
74
75 /**
76 * Delegates to {@link org.slf4j.Logger#trace(String,Throwable)}
77 * method in SLF4J.
78 */
79 public void trace(Object message, Throwable t) {
80 differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, null);
81 }
82
83 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import java.util.Hashtable;
19 import java.util.Map;
20
21 public class MDC {
22
23 public static void put(String key, String value) {
24 org.slf4j.MDC.put(key, value);
25 }
26
27 public static void put(String key, Object value) {
28 if (value != null) {
29 put(key, value.toString());
30 } else {
31 put(key, null);
32 }
33 }
34
35 public static Object get(String key) {
36 return org.slf4j.MDC.get(key);
37 }
38
39 public static void remove(String key) {
40 org.slf4j.MDC.remove(key);
41 }
42
43 public static void clear() {
44 org.slf4j.MDC.clear();
45 }
46
47 /**
48 * This method is not part of the Log4J public API. However it
49 * has been called by other projects. This method is here temporarily
50 * until projects who are depending on this method release fixes.
51 */
52 @SuppressWarnings({ "rawtypes", "unchecked" })
53 @Deprecated
54 public static Hashtable getContext() {
55 Map map = org.slf4j.MDC.getCopyOfContextMap();
56
57 if (map != null) {
58 return new Hashtable(map);
59 } else {
60 return new Hashtable();
61 }
62 }
63 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import org.slf4j.MDC;
19
20 import java.util.Stack;
21
22 /**
23 * A log4j's NDC implemented in terms of SLF4J MDC primitives.
24 *
25 * @since SLF4J 1.6.0
26 */
27
28 public class NDC {
29
30 public final static String PREFIX = "NDC";
31
32 public static void clear() {
33 int depth = getDepth();
34 for (int i = 0; i < depth; i++) {
35 String key = PREFIX + i;
36 MDC.remove(key);
37 }
38 }
39
40 @SuppressWarnings("rawtypes")
41 public static Stack cloneStack() {
42 return null;
43 }
44
45 @SuppressWarnings("rawtypes")
46 public static void inherit(Stack stack) {
47 }
48
49 static public String get() {
50 return null;
51 }
52
53 public static int getDepth() {
54 int i = 0;
55 while (true) {
56 String val = MDC.get(PREFIX + i);
57 if (val != null) {
58 i++;
59 } else {
60 break;
61 }
62 }
63 return i;
64 }
65
66 public static String pop() {
67 int next = getDepth();
68 if (next == 0) {
69 return "";
70 }
71 int last = next - 1;
72 String key = PREFIX + last;
73 String val = MDC.get(key);
74 MDC.remove(key);
75 return val;
76 }
77
78 public static String peek() {
79 int next = getDepth();
80 if (next == 0) {
81 return "";
82 }
83 int last = next - 1;
84 String key = PREFIX + last;
85 String val = MDC.get(key);
86 return val;
87 }
88
89 public static void push(String message) {
90 int next = getDepth();
91 MDC.put(PREFIX + next, message);
92 }
93
94 static public void remove() {
95 clear();
96 }
97
98 static public void setMaxDepth(int maxDepth) {
99 }
100
101 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Christian Trutz <christian.trutz@belaso.de>
17 package org.apache.log4j;
18
19 /**
20 * This class is a minimal implementation of the original Log4J class.
21 *
22 * @author Christian Trutz <christian.trutz@belaso.de>
23 * */
24 public class PatternLayout extends Layout {
25
26 public PatternLayout() {
27 super();
28 }
29
30 public PatternLayout(String pattern) {
31 super();
32 }
33
34 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Kitching Simon <Simon.Kitching@orange.ch>
17
18 package org.apache.log4j;
19
20 // Contributors: Kitching Simon <Simon.Kitching@OOOrange.ch>
21
22 /**
23 <font color="#AA4444">Refrain from using this class directly, use
24 the {@link Level} class instead</font>.
25
26 @author Ceki G&uuml;lc&uuml; */
27 public class Priority {
28
29 transient int level;
30 transient String levelStr;
31 transient int syslogEquivalent;
32
33 public final static int OFF_INT = Integer.MAX_VALUE;
34 public final static int FATAL_INT = 50000;
35 public final static int ERROR_INT = 40000;
36 public final static int WARN_INT = 30000;
37 public final static int INFO_INT = 20000;
38 public final static int DEBUG_INT = 10000;
39 // public final static int FINE_INT = DEBUG_INT;
40 public final static int ALL_INT = Integer.MIN_VALUE;
41
42 /**
43 * @deprecated Use {@link Level#FATAL} instead.
44 */
45 final static public Priority FATAL = new Level(FATAL_INT, "FATAL", 0);
46
47 /**
48 * @deprecated Use {@link Level#ERROR} instead.
49 */
50 final static public Priority ERROR = new Level(ERROR_INT, "ERROR", 3);
51
52 /**
53 * @deprecated Use {@link Level#WARN} instead.
54 */
55 final static public Priority WARN = new Level(WARN_INT, "WARN", 4);
56
57 /**
58 * @deprecated Use {@link Level#INFO} instead.
59 */
60 final static public Priority INFO = new Level(INFO_INT, "INFO", 6);
61
62 /**
63 * @deprecated Use {@link Level#DEBUG} instead.
64 */
65 final static public Priority DEBUG = new Level(DEBUG_INT, "DEBUG", 7);
66
67 /**
68 * Default constructor for deserialization.
69 */
70 protected Priority() {
71 level = DEBUG_INT;
72 levelStr = "DEBUG";
73 syslogEquivalent = 7;
74 }
75
76 /**
77 Instantiate a level object.
78 */
79 protected Priority(int level, String levelStr, int syslogEquivalent) {
80 this.level = level;
81 this.levelStr = levelStr;
82 this.syslogEquivalent = syslogEquivalent;
83 }
84
85 /**
86 Two priorities are equal if their level fields are equal.
87 @since 1.2
88 */
89 public boolean equals(Object o) {
90 if (o instanceof Priority) {
91 Priority r = (Priority) o;
92 return (this.level == r.level);
93 } else {
94 return false;
95 }
96 }
97
98 /**
99 Return the syslog equivalent of this priority as an integer.
100 */
101 public final int getSyslogEquivalent() {
102 return syslogEquivalent;
103 }
104
105 /**
106 Returns <code>true</code> if this level has a higher or equal
107 level than the level passed as argument, <code>false</code>
108 otherwise.
109
110 <p>You should think twice before overriding the default
111 implementation of <code>isGreaterOrEqual</code> method.
112
113 */
114 public boolean isGreaterOrEqual(Priority r) {
115 return level >= r.level;
116 }
117
118 /**
119 Return all possible priorities as an array of Level objects in
120 descending order.
121
122 @deprecated This method will be removed with no replacement.
123 */
124 public static Priority[] getAllPossiblePriorities() {
125 return new Priority[] { Priority.FATAL, Priority.ERROR, Level.WARN, Priority.INFO, Priority.DEBUG };
126 }
127
128 /**
129 Returns the string representation of this priority.
130 */
131 final public String toString() {
132 return levelStr;
133 }
134
135 /**
136 Returns the integer representation of this level.
137 */
138 public final int toInt() {
139 return level;
140 }
141
142 /**
143 * @deprecated Please use the {@link Level#toLevel(String)} method instead.
144 */
145 public static Priority toPriority(String sArg) {
146 return Level.toLevel(sArg);
147 }
148
149 /**
150 * @deprecated Please use the {@link Level#toLevel(int)} method instead.
151 */
152 public static Priority toPriority(int val) {
153 return toPriority(val, Priority.DEBUG);
154 }
155
156 /**
157 * @deprecated Please use the {@link Level#toLevel(int, Level)} method instead.
158 */
159 public static Priority toPriority(int val, Priority defaultPriority) {
160 return Level.toLevel(val, (Level) defaultPriority);
161 }
162
163 /**
164 * @deprecated Please use the {@link Level#toLevel(String, Level)} method instead.
165 */
166 public static Priority toPriority(String sArg, Priority defaultPriority) {
167 return Level.toLevel(sArg, (Level) defaultPriority);
168 }
169 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j;
17
18 import java.net.URL;
19 import java.util.Properties;
20
21 import org.apache.log4j.spi.Configurator;
22 import org.apache.log4j.spi.LoggerRepository;
23
24 /**
25 * An nop implementation of PropertyConfigurator.
26 */
27 public class PropertyConfigurator implements Configurator {
28 public static void configure(Properties properties) {
29 }
30
31 public static void configure(String configFilename) {
32 }
33
34 public static void configure(java.net.URL configURL) {
35 }
36
37 public static void configureAndWatch(String configFilename) {
38 }
39
40 public static void configureAndWatch(String configFilename, long delay) {
41 }
42
43 public void doConfigure(Properties properties, LoggerRepository hierarchy) {
44 }
45
46 public void doConfigure(String configFileName, LoggerRepository hierarchy) {
47 }
48
49 public void doConfigure(URL configURL, LoggerRepository hierarchy) {
50 }
51 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 // Contributors: Christian Trutz <christian.trutz@belaso.de>
17 package org.apache.log4j;
18
19 import java.io.IOException;
20
21 /**
22 * This class is a minimal implementation of the original Log4J class.
23 *
24 * @author Christian Trutz <christian.trutz@belaso.de>
25 * */
26 public class RollingFileAppender {
27
28 public RollingFileAppender() {
29 super();
30 }
31
32 public RollingFileAppender(Layout layout, String filename) throws IOException {
33 super();
34 }
35
36 public RollingFileAppender(Layout layout, String filename, boolean append) throws IOException {
37 super();
38 }
39
40 public void setMaxBackupIndex(int maxBackups) {
41 // nothing to do
42 }
43
44 public void setMaximumFileSize(long maxFileSize) {
45 // nothing to do
46 }
47
48 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class SimpleLayout extends Layout {
18 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j;
16
17 public class WriterAppender extends AppenderSkeleton {
18
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.helpers;
17
18 /**
19 This class used to output log statements from within the log4j package.
20
21 <p>Log4j components cannot make log4j logging calls. However, it is
22 sometimes useful for the user to learn about what log4j is
23 doing. You can enable log4j internal logging by defining the
24 <b>log4j.configDebug</b> variable.
25
26 <p>All log4j internal debug calls go to <code>System.out</code>
27 where as internal error messages are sent to
28 <code>System.err</code>. All internal messages are prepended with
29 the string "log4j: ".
30
31 @since 0.8.2
32 @author Ceki G&uuml;lc&uuml;
33 */
34 public class LogLog {
35
36 /**
37 Defining this value makes log4j print log4j-internal debug
38 statements to <code>System.out</code>.
39
40 <p> The value of this string is <b>log4j.debug</b>.
41
42 <p>Note that the search for all option names is case sensitive. */
43 public static final String DEBUG_KEY = "log4j.debug";
44
45 /**
46 Defining this value makes log4j components print log4j-internal
47 debug statements to <code>System.out</code>.
48
49 <p> The value of this string is <b>log4j.configDebug</b>.
50
51 <p>Note that the search for all option names is case sensitive.
52
53 @deprecated Use {@link #DEBUG_KEY} instead.
54 */
55 public static final String CONFIG_DEBUG_KEY = "log4j.configDebug";
56
57 protected static boolean debugEnabled = false;
58
59 /**
60 In quietMode not even errors generate any output.
61 */
62 private static boolean quietMode = false;
63
64 private static final String PREFIX = "log4j: ";
65 private static final String ERR_PREFIX = "log4j:ERROR ";
66 private static final String WARN_PREFIX = "log4j:WARN ";
67
68 static {
69 }
70
71 /**
72 Allows to enable/disable log4j internal logging.
73 */
74 static public void setInternalDebugging(boolean enabled) {
75 debugEnabled = enabled;
76 }
77
78 /**
79 This method is used to output log4j internal debug
80 statements. Output goes to <code>System.out</code>.
81 */
82 public static void debug(String msg) {
83 if (debugEnabled && !quietMode) {
84 System.out.println(PREFIX + msg);
85 }
86 }
87
88 /**
89 This method is used to output log4j internal debug
90 statements. Output goes to <code>System.out</code>.
91 */
92 public static void debug(String msg, Throwable t) {
93 if (debugEnabled && !quietMode) {
94 System.out.println(PREFIX + msg);
95 if (t != null)
96 t.printStackTrace(System.out);
97 }
98 }
99
100 /**
101 This method is used to output log4j internal error
102 statements. There is no way to disable error statements.
103 Output goes to <code>System.err</code>.
104 */
105 public static void error(String msg) {
106 if (quietMode)
107 return;
108 System.err.println(ERR_PREFIX + msg);
109 }
110
111 /**
112 This method is used to output log4j internal error
113 statements. There is no way to disable error statements.
114 Output goes to <code>System.err</code>.
115 */
116 public static void error(String msg, Throwable t) {
117 if (quietMode)
118 return;
119
120 System.err.println(ERR_PREFIX + msg);
121 if (t != null) {
122 t.printStackTrace();
123 }
124 }
125
126 /**
127 In quite mode no LogLog generates strictly no output, not even
128 for errors.
129
130 @param quietMode A true for not
131 */
132 public static void setQuietMode(boolean quietMode) {
133 LogLog.quietMode = quietMode;
134 }
135
136 /**
137 This method is used to output log4j internal warning
138 statements. There is no way to disable warning statements.
139 Output goes to <code>System.err</code>. */
140 public static void warn(String msg) {
141 if (quietMode)
142 return;
143
144 System.err.println(WARN_PREFIX + msg);
145 }
146
147 /**
148 This method is used to output log4j internal warnings. There is
149 no way to disable warning statements. Output goes to
150 <code>System.err</code>. */
151 public static void warn(String msg, Throwable t) {
152 if (quietMode)
153 return;
154
155 System.err.println(WARN_PREFIX + msg);
156 if (t != null) {
157 t.printStackTrace();
158 }
159 }
160 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 package org.apache.log4j.helpers;
18
19 import java.util.Enumeration;
20 import java.util.NoSuchElementException;
21
22 /**
23 * An always-empty Enumerator.
24 *
25 * @author Anders Kristensen
26 * @since version 1.0
27 */
28 @SuppressWarnings("rawtypes")
29 public class NullEnumeration implements Enumeration {
30 private static final NullEnumeration instance = new NullEnumeration();
31
32 private NullEnumeration() {
33 }
34
35 public static NullEnumeration getInstance() {
36 return instance;
37 }
38
39 public boolean hasMoreElements() {
40 return false;
41 }
42
43 public Object nextElement() {
44 throw new NoSuchElementException();
45 }
46 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>An rather minimal but sufficient implementation redirecting all
12 calls to a log4j logger to a logback logger.</p>
13
14 </body>
15 </html>
16
17
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.spi.LoggerRepository;
19 import java.net.URL;
20
21 /**
22 Implemented by classes capable of configuring log4j using a URL.
23
24 @since 1.0
25 @author Anders Kristensen
26 */
27 public interface Configurator {
28
29 /**
30 Special level value signifying inherited behaviour. The current
31 value of this string constant is <b>inherited</b>. {@link #NULL}
32 is a synonym. */
33 public static final String INHERITED = "inherited";
34
35 /**
36 Special level signifying inherited behaviour, same as {@link
37 #INHERITED}. The current value of this string constant is
38 <b>null</b>. */
39 public static final String NULL = "null";
40
41 /**
42 Interpret a resource pointed by a URL and set up log4j accordingly.
43
44 The configuration is done relative to the <code>hierarchy</code>
45 parameter.
46
47 @param url The URL to parse
48 @param repository The hierarchy to operation upon.
49 */
50 void doConfigure(URL url, LoggerRepository repository);
51 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 /**
19 * Created by IntelliJ IDEA.
20 * User: ceki
21 * Date: 19 oct. 2010
22 * Time: 11:46:24
23 * To change this template use File | Settings | File Templates.
24 */
25 public class ErrorHandler {
26 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 public class Filter {
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.*;
19
20 /**
21 Listen to events occuring within a {@link
22 org.apache.log4j.Hierarchy Hierarchy}.
23
24 @author Ceki G&uuml;lc&uuml;
25 @since 1.2
26
27 */
28 public interface HierarchyEventListener {
29
30 // public
31 // void categoryCreationEvent(Category cat);
32
33 public void addAppenderEvent(Category cat, Appender appender);
34
35 public void removeAppenderEvent(Category cat, Appender appender);
36
37 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 public class Layout {
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.Logger;
19
20 /**
21
22 Implement this interface to create new instances of Logger or
23 a sub-class of Logger.
24
25 <p>See <code>examples/subclass/MyLogger.java</code> for an example.
26
27 @author Ceki G&uuml;lc&uuml;
28 @since version 0.8.5
29
30 */
31 public interface LoggerFactory {
32
33 public Logger makeNewLoggerInstance(String name);
34
35 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 import org.apache.log4j.*;
19
20 import java.util.Enumeration;
21
22 /**
23 * A <code>LoggerRepository</code> is used to create and retrieve
24 * <code>Loggers</code>. The relation between loggers in a repository
25 * depends on the repository but typically loggers are arranged in a
26 * named hierarchy.
27 * <p/>
28 * <p>In addition to the creational methods, a
29 * <code>LoggerRepository</code> can be queried for existing loggers,
30 * can act as a point of registry for events related to loggers.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 * @since 1.2
34 */
35 public interface LoggerRepository {
36
37 /**
38 * Add a {@link HierarchyEventListener} event to the repository.
39 */
40 public void addHierarchyEventListener(HierarchyEventListener listener);
41
42 /**
43 * Returns whether this repository is disabled for a given
44 * level. The answer depends on the repository threshold and the
45 * <code>level</code> parameter. See also {@link #setThreshold}
46 * method.
47 */
48 boolean isDisabled(int level);
49
50 /**
51 * Set the repository-wide threshold. All logging requests below the
52 * threshold are immediately dropped. By default, the threshold is
53 * set to <code>Level.ALL</code> which has the lowest possible rank.
54 */
55 public void setThreshold(Level level);
56
57 /**
58 * Another form of {@link #setThreshold(Level)} accepting a string
59 * parameter instead of a <code>Level</code>.
60 */
61 public void setThreshold(String val);
62
63 public void emitNoAppenderWarning(Category cat);
64
65 /**
66 * Get the repository-wide threshold. See {@link
67 * #setThreshold(Level)} for an explanation.
68 */
69 public Level getThreshold();
70
71 public Logger getLogger(String name);
72
73 public Logger getLogger(String name, LoggerFactory factory);
74
75 public Logger getRootLogger();
76
77 public abstract Logger exists(String name);
78
79 public abstract void shutdown();
80
81 @SuppressWarnings("rawtypes")
82 public Enumeration getCurrentLoggers();
83
84 /**
85 * Deprecated. Please use {@link #getCurrentLoggers} instead.
86 */
87 @SuppressWarnings("rawtypes")
88 public Enumeration getCurrentCategories();
89
90 public abstract void fireAddAppenderEvent(Category logger, Appender appender);
91
92 public abstract void resetConfiguration();
93
94 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.spi;
17
18 public class LoggingEvent {
19 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.apache.log4j.spi;
16
17 public interface OptionHandler {
18
19 void activateOptions();
20
21 }
0 /*
1 * Copyright 2001-2004 The Apache Software Foundation.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package org.apache.log4j.xml;
17
18 import org.apache.log4j.spi.Configurator;
19 import org.apache.log4j.spi.LoggerRepository;
20
21 import javax.xml.parsers.FactoryConfigurationError;
22 import java.io.InputStream;
23 import java.io.Reader;
24 import java.net.URL;
25 import java.util.Properties;
26
27 import org.w3c.dom.Element;
28
29 public class DOMConfigurator implements Configurator {
30
31 public static void configure(Element element) {
32 }
33
34 public static void configure(String filename) throws FactoryConfigurationError {
35 }
36
37 static public void configure(URL url) throws FactoryConfigurationError {
38 }
39
40 static public void configureAndWatch(String configFilename) {
41 }
42
43 public static void configureAndWatch(String configFilename, long delay) {
44 }
45
46 public void doConfigure(Element element, LoggerRepository repository) {
47 }
48
49 public void doConfigure(InputStream inputStream, LoggerRepository repository) throws FactoryConfigurationError {
50 }
51
52 public void doConfigure(Reader reader, LoggerRepository repository) throws FactoryConfigurationError {
53 }
54
55 public void doConfigure(String filename, LoggerRepository repository) {
56 }
57
58 public void doConfigure(URL url, LoggerRepository repository) {
59 }
60
61 public static String subst(String value, Properties props) {
62 return value;
63 }
64
65 }
0 Implementation-Title: log4j-over-slf4j
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: log4j.over.slf4j
3 Bundle-Name: log4j-over-slf4j
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.apache.log4j;version=${log4j.version},org.apache.log4j.helpers;version=${log4j.version},org.apache.log4j.spi;version=${log4j.version},org.apache.log4j.xml;version=${log4j.version}
7 Import-Package: org.slf4j;version=${slf4j.api.minimum.compatible.version}, org.slf4j.helpers;version=${slf4j.api.minimum.compatible.version}, org.slf4j.spi;version=${slf4j.api.minimum.compatible.version}
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.apache.log4j;
25
26 import junit.framework.TestCase;
27
28 /**
29 * @author Ceki G&uuml;c&uuml;
30 */
31 public class NDCTest extends TestCase {
32
33 public void setUp() {
34 assertEquals(0, NDC.getDepth());
35 }
36
37 public void tearDown() {
38 NDC.clear();
39 }
40
41 public void testSmoke() {
42 NDC.push("a");
43 String back = NDC.pop();
44 assertEquals("a", back);
45 }
46
47 public void testPop() {
48 NDC.push("peek");
49 String back = NDC.peek();
50 assertEquals("peek", back);
51 }
52
53 public void testClear() {
54 NDC.push("clear");
55 NDC.clear();
56 assertEquals(0, NDC.getDepth());
57 }
58
59 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.apache.log4j;
25
26 import org.apache.log4j.Logger;
27
28 import junit.framework.TestCase;
29
30 public class Trivial extends TestCase {
31
32 public void testSmoke() {
33 Logger l = Logger.getLogger("a");
34 l.trace("t");
35 l.debug("d");
36 l.info("i");
37 l.warn("w");
38 l.error("e");
39 l.fatal("f");
40
41 Exception e = new Exception("testing");
42 l.trace("t", e);
43 l.debug("d", e);
44 l.info("i", e);
45 l.warn("w", e);
46 l.error("e", e);
47 l.fatal("f", e);
48 }
49
50 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.dummy;
25
26 import java.util.logging.Level;
27 import java.util.logging.LogRecord;
28
29 import junit.framework.TestCase;
30
31 import org.apache.log4j.Category;
32 import org.apache.log4j.Logger;
33
34 public class Bug131 extends TestCase {
35
36 public void testBug131() {
37
38 ListHandler listHandler = new ListHandler();
39 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
40 root.addHandler(listHandler);
41 root.setLevel(Level.FINEST);
42 Logger log4jLogger = Logger.getLogger("a");
43 Category log4jCategory = Logger.getLogger("b");
44
45 int n = 0;
46
47 log4jLogger.trace("msg" + (n++));
48 log4jLogger.debug("msg" + (n++));
49 log4jLogger.info("msg" + (n++));
50 log4jLogger.warn("msg" + (n++));
51 log4jLogger.error("msg" + (n++));
52 log4jLogger.fatal("msg" + (n++));
53
54 log4jCategory.debug("msg" + (n++));
55 log4jCategory.info("msg" + (n++));
56 log4jCategory.warn("msg" + (n++));
57 log4jCategory.error("msg" + (n++));
58 log4jCategory.fatal("msg" + (n++));
59
60 assertEquals(n, listHandler.list.size());
61
62 for (int i = 0; i < n; i++) {
63 LogRecord logRecord = (LogRecord) listHandler.list.get(i);
64 assertEquals("testBug131", logRecord.getSourceMethodName());
65 }
66 }
67 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.dummy;
25
26 import java.util.logging.Level;
27 import java.util.logging.LogRecord;
28
29 import junit.framework.TestCase;
30
31 import org.apache.log4j.Category;
32 import org.apache.log4j.Logger;
33
34 public class Bug139 extends TestCase {
35
36 public void test() {
37 ListHandler listHandler = new ListHandler();
38 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
39 root.addHandler(listHandler);
40 root.setLevel(Level.FINEST);
41 Logger log4jLogger = Logger.getLogger("a");
42 Category log4jCategory = Logger.getLogger("b");
43
44 int n = 0;
45
46 log4jLogger.log(org.apache.log4j.Level.DEBUG, "hello" + (++n));
47 log4jCategory.log(org.apache.log4j.Level.DEBUG, "world" + (++n));
48
49 assertEquals(n, listHandler.list.size());
50
51 for (int i = 0; i < n; i++) {
52 LogRecord logRecord = (LogRecord) listHandler.list.get(i);
53 assertEquals("test", logRecord.getSourceMethodName());
54 }
55 }
56 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.dummy;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.logging.Handler;
29 import java.util.logging.LogRecord;
30
31 public class ListHandler extends Handler {
32
33 List<LogRecord> list = new ArrayList<LogRecord>();
34
35 public void close() throws SecurityException {
36
37 }
38
39 public void flush() {
40
41 }
42
43 public void publish(LogRecord logRecord) {
44 logRecord.getSourceClassName();
45 list.add(logRecord);
46 }
47
48 }
0 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2
3 <modelVersion>4.0.0</modelVersion>
4
5 <parent>
6 <groupId>org.slf4j</groupId>
7 <artifactId>slf4j-parent</artifactId>
8 <version>1.7.12</version>
9 </parent>
10
11 <artifactId>osgi-over-slf4j</artifactId>
12
13 <packaging>bundle</packaging>
14 <name>OSGi LogService implemented over SLF4J</name>
15
16 <url>http://www.slf4j.org</url>
17 <description>
18 OSGi LogService implementation over SLF4J
19 </description>
20
21 <dependencies>
22 <dependency>
23 <groupId>org.osgi</groupId>
24 <artifactId>org.osgi.core</artifactId>
25 <version>4.2.0</version>
26 <scope>provided</scope>
27 </dependency>
28 <dependency>
29 <groupId>org.osgi</groupId>
30 <artifactId>org.osgi.enterprise</artifactId>
31 <version>4.2.0</version>
32 <scope>provided</scope>
33 </dependency>
34
35 <dependency>
36 <groupId>org.slf4j</groupId>
37 <artifactId>slf4j-simple</artifactId>
38 <version>${project.version}</version>
39 <scope>provided</scope>
40 </dependency>
41 </dependencies>
42 <build>
43 <plugins>
44 <plugin>
45 <groupId>org.apache.felix</groupId>
46 <artifactId>maven-bundle-plugin</artifactId>
47 <version>2.3.7</version>
48 <extensions>true</extensions>
49 <configuration>
50 <instructions>
51 <Export-Package>org.osgi.service.log</Export-Package>
52 <Bundle-Activator>org.slf4j.osgi.logservice.impl.Activator</Bundle-Activator>
53 </instructions>
54 </configuration>
55 </plugin>
56 </plugins>
57 </build>
58 </project>
0 /*
1 * Copyright (c) 2004-2005 QOS.ch
2 *
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, and/or sell copies of the Software, and to permit persons
10 * to whom the Software is furnished to do so, provided that the above
11 * copyright notice(s) and this permission notice appear in all copies of
12 * the Software and that both the above copyright notice(s) and this
13 * permission notice appear in supporting documentation.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
18 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
20 * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
21 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
22 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
23 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 *
25 * Except as contained in this notice, the name of a copyright holder
26 * shall not be used in advertising or otherwise to promote the sale, use
27 * or other dealings in this Software without prior written authorization
28 * of the copyright holder.
29 *
30 */
31
32 package org.slf4j.osgi.logservice.impl;
33
34 import java.util.Properties;
35
36 import org.osgi.framework.BundleActivator;
37 import org.osgi.framework.BundleContext;
38 import org.osgi.framework.ServiceFactory;
39 import org.osgi.service.log.LogService;
40
41 /**
42 * <code>Activator</code> implements a simple bundle that registers a
43 * {@link LogServiceFactory} for the creation of {@link LogService} implementations.
44 *
45 * @author John Conlon
46 * @author Matt Bishop
47 **/
48 public class Activator implements BundleActivator {
49 /**
50 *
51 * Implements <code>BundleActivator.start()</code> to register a
52 * LogServiceFactory.
53 *
54 * @param bundleContext the framework context for the bundle
55 * @throws Exception
56 */
57 public void start(BundleContext bundleContext) throws Exception {
58
59 Properties props = new Properties();
60 props.put("description", "An SLF4J LogService implementation.");
61 ServiceFactory factory = new LogServiceFactory();
62 bundleContext.registerService(LogService.class.getName(), factory, props);
63 }
64
65 /**
66 *
67 * Implements <code>BundleActivator.stop()</code>.
68 *
69 * @param bundleContext the framework context for the bundle
70 * @throws Exception
71 */
72 public void stop(BundleContext bundleContext) throws Exception {
73
74 // Note: It is not required that we remove the service here, since
75 // the framework will do it automatically.
76 }
77 }
0 /*
1 * Copyright (c) 2004-2005 QOS.ch
2 *
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, and/or sell copies of the Software, and to permit persons
10 * to whom the Software is furnished to do so, provided that the above
11 * copyright notice(s) and this permission notice appear in all copies of
12 * the Software and that both the above copyright notice(s) and this
13 * permission notice appear in supporting documentation.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
18 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
20 * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
21 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
22 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
23 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 *
25 * Except as contained in this notice, the name of a copyright holder
26 * shall not be used in advertising or otherwise to promote the sale, use
27 * or other dealings in this Software without prior written authorization
28 * of the copyright holder.
29 *
30 */
31
32 package org.slf4j.osgi.logservice.impl;
33
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.ServiceFactory;
36 import org.osgi.framework.ServiceRegistration;
37
38 /**
39 * <code>LogServiceFactory</code> creates LogService implementations.
40 *
41 * @author John Conlon
42 * @version $Rev$, $Date$
43 */
44 public class LogServiceFactory implements ServiceFactory {
45 /*
46 * (non-Javadoc)
47 *
48 * @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle,
49 * org.osgi.framework.ServiceRegistration)
50 */
51 public Object getService(Bundle bundle, ServiceRegistration arg1) {
52 return new LogServiceImpl(bundle);
53 }
54
55 /*
56 * (non-Javadoc)
57 *
58 * @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle,
59 * org.osgi.framework.ServiceRegistration, java.lang.Object)
60 */
61 public void ungetService(Bundle bundle, ServiceRegistration arg1, Object arg2) {
62 // nothing to do.
63 }
64 }
0 /*
1 * Copyright (c) 2004-2005 QOS.ch
2 *
3 * All rights reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, and/or sell copies of the Software, and to permit persons
10 * to whom the Software is furnished to do so, provided that the above
11 * copyright notice(s) and this permission notice appear in all copies of
12 * the Software and that both the above copyright notice(s) and this
13 * permission notice appear in supporting documentation.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
18 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
20 * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
21 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
22 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
23 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 *
25 * Except as contained in this notice, the name of a copyright holder
26 * shall not be used in advertising or otherwise to promote the sale, use
27 * or other dealings in this Software without prior written authorization
28 * of the copyright holder.
29 *
30 */
31
32 package org.slf4j.osgi.logservice.impl;
33
34 import org.osgi.framework.Bundle;
35 import org.osgi.framework.ServiceReference;
36 import org.osgi.framework.Version;
37 import org.osgi.service.log.LogService;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42 * <code>LogServiceImpl</code> is a simple OSGi LogService implementation that delegates to a slf4j
43 * Logger.
44 *
45 * @author John Conlon
46 * @author Matt Bishop
47 */
48 public class LogServiceImpl implements LogService {
49
50 private static final String UNKNOWN = "[Unknown]";
51
52 private final Logger delegate;
53
54 /**
55 * Creates a new instance of LogServiceImpl.
56 *
57 * @param bundle The bundle to create a new LogService for.
58 */
59 public LogServiceImpl(Bundle bundle) {
60
61 String name = bundle.getSymbolicName();
62 Version version = bundle.getVersion();
63 if (version == null) {
64 version = Version.emptyVersion;
65 }
66 delegate = LoggerFactory.getLogger(name + '.' + version);
67 }
68
69 /*
70 * (non-Javadoc)
71 *
72 * @see org.osgi.service.log.LogService#log(int, java.lang.String)
73 */
74 public void log(int level, String message) {
75
76 switch (level) {
77 case LOG_DEBUG:
78 delegate.debug(message);
79 break;
80 case LOG_ERROR:
81 delegate.error(message);
82 break;
83 case LOG_INFO:
84 delegate.info(message);
85 break;
86 case LOG_WARNING:
87 delegate.warn(message);
88 break;
89 default:
90 break;
91 }
92 }
93
94 /*
95 * (non-Javadoc)
96 *
97 * @see org.osgi.service.log.LogService#log(int, java.lang.String, java.lang.Throwable)
98 */
99 public void log(int level, String message, Throwable exception) {
100
101 switch (level) {
102 case LOG_DEBUG:
103 delegate.debug(message, exception);
104 break;
105 case LOG_ERROR:
106 delegate.error(message, exception);
107 break;
108 case LOG_INFO:
109 delegate.info(message, exception);
110 break;
111 case LOG_WARNING:
112 delegate.warn(message, exception);
113 break;
114 default:
115 break;
116 }
117 }
118
119 /*
120 * (non-Javadoc)
121 *
122 * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String)
123 */
124 public void log(ServiceReference sr, int level, String message) {
125
126 switch (level) {
127 case LOG_DEBUG:
128 if (delegate.isDebugEnabled()) {
129 delegate.debug(createMessage(sr, message));
130 }
131 break;
132 case LOG_ERROR:
133 if (delegate.isErrorEnabled()) {
134 delegate.error(createMessage(sr, message));
135 }
136 break;
137 case LOG_INFO:
138 if (delegate.isInfoEnabled()) {
139 delegate.info(createMessage(sr, message));
140 }
141 break;
142 case LOG_WARNING:
143 if (delegate.isWarnEnabled()) {
144 delegate.warn(createMessage(sr, message));
145 }
146 break;
147 default:
148 break;
149 }
150 }
151
152 /**
153 * Formats the log message to indicate the service sending it, if known.
154 *
155 * @param sr the ServiceReference sending the message.
156 * @param message The message to log.
157 * @return The formatted log message.
158 */
159 private String createMessage(ServiceReference sr, String message) {
160
161 StringBuilder output = new StringBuilder();
162 if (sr != null) {
163 output.append('[').append(sr.toString()).append(']');
164 } else {
165 output.append(UNKNOWN);
166 }
167 output.append(message);
168
169 return output.toString();
170 }
171
172 /*
173 * (non-Javadoc)
174 *
175 * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String,
176 * java.lang.Throwable)
177 */
178 public void log(ServiceReference sr, int level, String message, Throwable exception) {
179
180 switch (level) {
181 case LOG_DEBUG:
182 if (delegate.isDebugEnabled()) {
183 delegate.debug(createMessage(sr, message), exception);
184 }
185 break;
186 case LOG_ERROR:
187 if (delegate.isErrorEnabled()) {
188 delegate.error(createMessage(sr, message), exception);
189 }
190 break;
191 case LOG_INFO:
192 if (delegate.isInfoEnabled()) {
193 delegate.info(createMessage(sr, message), exception);
194 }
195 break;
196 case LOG_WARNING:
197 if (delegate.isWarnEnabled()) {
198 delegate.warn(createMessage(sr, message), exception);
199 }
200 break;
201 default:
202 break;
203 }
204 }
205 }
0 <?xml version="1.0" encoding="UTF-8"?>
1 <project xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
5 <modelVersion>4.0.0</modelVersion>
6
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.12</version>
10
11 <packaging>pom</packaging>
12 <name>SLF4J</name>
13 <description>Top SLF4J project pom.xml file</description>
14 <url>http://www.slf4j.org</url>
15
16 <organization>
17 <name>QOS.ch</name>
18 <url>http://www.qos.ch</url>
19 </organization>
20 <inceptionYear>2005</inceptionYear>
21
22 <licenses>
23 <license>
24 <name>MIT License</name>
25 <url>http://www.opensource.org/licenses/mit-license.php</url>
26 <distribution>repo</distribution>
27 </license>
28 </licenses>
29
30 <scm>
31 <url>https://github.com/ceki/slf4j</url>
32 <connection>git@github.com:qos-ch/slf4j.git</connection>
33 </scm>
34
35 <properties>
36 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
37 <required.jdk.version>1.5</required.jdk.version>
38 <slf4j.api.minimum.compatible.version>1.6.0</slf4j.api.minimum.compatible.version>
39 <cal10n.version>0.8.1</cal10n.version>
40 <log4j.version>1.2.17</log4j.version>
41 <logback.version>1.0.13</logback.version>
42 <junit.version>4.10</junit.version>
43 <maven-site-plugin.version>3.3</maven-site-plugin.version>
44 <javadoc.plugin.version>2.10.2</javadoc.plugin.version>
45 </properties>
46
47 <developers>
48 <developer>
49 <id>ceki</id>
50 <name>Ceki Gulcu</name>
51 <email>ceki@qos.ch</email>
52 </developer>
53 </developers>
54
55 <modules>
56 <module>slf4j-api</module>
57 <!--<module>slf4j-scala-api</module>-->
58 <module>slf4j-simple</module>
59 <module>slf4j-nop</module>
60 <module>slf4j-jdk14</module>
61 <module>slf4j-log4j12</module>
62 <module>slf4j-jcl</module>
63 <module>slf4j-android</module>
64 <module>slf4j-ext</module>
65 <module>jcl-over-slf4j</module>
66 <module>log4j-over-slf4j</module>
67 <module>jul-to-slf4j</module>
68 <module>osgi-over-slf4j</module>
69 <module>integration</module>
70 <module>slf4j-site</module>
71 <module>slf4j-migrator</module>
72 </modules>
73
74 <dependencies>
75 <dependency>
76 <groupId>junit</groupId>
77 <artifactId>junit</artifactId>
78 <version>${junit.version}</version>
79 <scope>test</scope>
80 </dependency>
81 </dependencies>
82
83
84 <dependencyManagement>
85 <dependencies>
86
87 <dependency>
88 <groupId>org.slf4j</groupId>
89 <artifactId>slf4j-api</artifactId>
90 <version>${project.version}</version>
91 </dependency>
92
93 <dependency>
94 <groupId>org.slf4j</groupId>
95 <artifactId>slf4j-jdk14</artifactId>
96 <version>${project.version}</version>
97 </dependency>
98
99 <dependency>
100 <groupId>log4j</groupId>
101 <artifactId>log4j</artifactId>
102 <version>${log4j.version}</version>
103 </dependency>
104
105 <dependency>
106 <groupId>ch.qos.cal10n</groupId>
107 <artifactId>cal10n-api</artifactId>
108 <version>${cal10n.version}</version>
109 </dependency>
110
111 </dependencies>
112 </dependencyManagement>
113
114
115 <build>
116 <extensions>
117 <extension>
118 <groupId>org.apache.maven.wagon</groupId>
119 <artifactId>wagon-ssh</artifactId>
120 <version>2.0</version>
121 </extension>
122 </extensions>
123
124 <resources>
125 <resource>
126 <directory>src/main/resources</directory>
127 <filtering>true</filtering>
128 </resource>
129 </resources>
130
131 <plugins>
132 <plugin>
133 <groupId>org.apache.maven.plugins</groupId>
134 <artifactId>maven-compiler-plugin</artifactId>
135 <version>2.3.2</version>
136 <configuration>
137 <source>1.5</source>
138 <target>1.5</target>
139 </configuration>
140 </plugin>
141
142 <plugin>
143 <groupId>org.apache.maven.plugins</groupId>
144 <artifactId>maven-jar-plugin</artifactId>
145 <version>2.3.1</version>
146 </plugin>
147
148 <plugin>
149 <groupId>org.apache.maven.plugins</groupId>
150 <artifactId>maven-surefire-plugin</artifactId>
151 <version>2.10</version>
152 <configuration>
153 <forkMode>once</forkMode>
154 <reportFormat>plain</reportFormat>
155 <trimStackTrace>false</trimStackTrace>
156 <excludes>
157 <exclude>**/AllTest.java</exclude>
158 <exclude>**/PackageTest.java</exclude>
159 </excludes>
160 </configuration>
161 </plugin>
162
163 <plugin>
164 <groupId>org.apache.maven.plugins</groupId>
165 <artifactId>maven-source-plugin</artifactId>
166 <version>2.1.2</version>
167 <executions>
168 <execution>
169 <phase>package</phase>
170 <goals>
171 <goal>jar</goal>
172 </goals>
173 </execution>
174 </executions>
175 </plugin>
176
177 <plugin>
178 <groupId>org.apache.maven.plugins</groupId>
179 <artifactId>maven-assembly-plugin</artifactId>
180 <version>2.2</version>
181 <configuration>
182 <descriptors>
183 <descriptor>src/main/assembly/source.xml</descriptor>
184 </descriptors>
185 <finalName>slf4j-${project.version}</finalName>
186 <appendAssemblyId>false</appendAssemblyId>
187 <outputDirectory>target/site/dist/</outputDirectory>
188 </configuration>
189 </plugin>
190
191 <!-- as suggested in http://bugzilla.slf4j.org/show_bug.cgi?id=152 -->
192 <plugin>
193 <groupId>org.codehaus.mojo</groupId>
194 <artifactId>build-helper-maven-plugin</artifactId>
195 <version>1.7</version>
196 <executions>
197 <execution>
198 <id>parse-version</id>
199 <goals>
200 <goal>parse-version</goal>
201 </goals>
202 </execution>
203 </executions>
204 </plugin>
205
206 <!-- ====== site plugin ===== -->
207 <plugin>
208 <groupId>org.apache.maven.plugins</groupId>
209 <artifactId>maven-site-plugin</artifactId>
210 <version>${maven-site-plugin.version}</version>
211 <configuration>
212 <reportPlugins>
213
214 <plugin>
215 <groupId>org.apache.maven.plugins</groupId>
216 <artifactId>maven-jxr-plugin</artifactId>
217 <version>2.3</version>
218 <configuration>
219 <aggregate>true</aggregate>
220 <javadocDir>target/site/apidocs/</javadocDir>
221 <linkJavadoc>true</linkJavadoc>
222 </configuration>
223 </plugin>
224
225 <plugin>
226 <groupId>org.apache.maven.plugins</groupId>
227 <artifactId>maven-javadoc-plugin</artifactId>
228 <version>${javadoc.plugin.version}</version>
229 <configuration>
230 <!--<aggregate>true</aggregate>-->
231 <excludePackageNames>org.slf4j.migrator:org.slf4j.migrator.*</excludePackageNames>
232 <links>
233 <link>
234 http://java.sun.com/j2se/1.5.0/docs/api
235 </link>
236 </links>
237 <groups>
238 <group>
239 <title>SLF4J packages</title>
240 <packages>org.slf4j:org.slf4j.*</packages>
241 </group>
242
243 <group>
244 <title>SLF4J extensions</title>
245 <packages>
246 org.slf4j.cal10n:org.slf4j.profiler:org.slf4j.ext:org.slf4j.instrumentation:org.slf4j.agent
247 </packages>
248 </group>
249
250 <group>
251 <title>Jakarta Commons Logging packages</title>
252 <packages>org.apache.commons.*</packages>
253 </group>
254
255 <group>
256 <title>java.util.logging (JUL) to SLF4J bridge</title>
257 <packages>org.slf4j.bridge</packages>
258 </group>
259
260 <group>
261 <title>Apache log4j</title>
262 <packages>org.apache.log4j:org.apache.log4j.*</packages>
263 </group>
264 </groups>
265 </configuration>
266 </plugin>
267
268 </reportPlugins>
269 </configuration>
270 </plugin>
271 </plugins>
272
273 </build>
274
275 <profiles>
276 <profile>
277 <id>skipTests</id>
278 <properties>
279 <maven.test.skip>true</maven.test.skip>
280 </properties>
281 </profile>
282
283 <profile>
284 <id>javadocjar</id>
285 <build>
286 <plugins>
287 <plugin>
288 <groupId>org.apache.maven.plugins</groupId>
289 <artifactId>maven-javadoc-plugin</artifactId>
290 <version>${javadoc.plugin.version}</version>
291 <executions>
292 <execution>
293 <id>attach-javadocs</id>
294 <goals>
295 <goal>jar</goal>
296 </goals>
297 </execution>
298 </executions>
299 </plugin>
300 </plugins>
301 </build>
302 </profile>
303
304 <profile>
305 <id>license</id>
306 <build>
307 <plugins>
308 <plugin>
309 <groupId>com.google.code.maven-license-plugin</groupId>
310 <artifactId>maven-license-plugin</artifactId>
311 <configuration>
312 <header>src/main/licenseHeader.txt</header>
313 <quiet>false</quiet>
314 <failIfMissing>true</failIfMissing>
315 <aggregate>true</aggregate>
316 <includes>
317 <include>src/**/*.java</include>
318 </includes>
319 <useDefaultExcludes>true</useDefaultExcludes>
320 <useDefaultMapping>true</useDefaultMapping>
321 <properties>
322 <year>1999</year>
323 </properties>
324 <headerDefinitions>
325 <headerDefinition>src/main/javadocHeaders.xml</headerDefinition>
326 </headerDefinitions>
327 </configuration>
328 </plugin>
329 </plugins>
330 </build>
331
332 <pluginRepositories>
333 <pluginRepository>
334 <id>mc-release</id>
335 <name>Local Maven repository of releases</name>
336 <url>http://mc-repo.googlecode.com/svn/maven2/releases</url>
337 <snapshots>
338 <enabled>false</enabled>
339 </snapshots>
340 <releases>
341 <enabled>true</enabled>
342 </releases>
343 </pluginRepository>
344 </pluginRepositories>
345 </profile>
346
347 <profile>
348 <id>sign-artifacts</id>
349 <build>
350 <plugins>
351 <plugin>
352 <groupId>org.apache.maven.plugins</groupId>
353 <artifactId>maven-gpg-plugin</artifactId>
354 <version>1.1</version>
355 <executions>
356 <execution>
357 <id>sign-artifacts</id>
358 <phase>verify</phase>
359 <goals>
360 <goal>sign</goal>
361 </goals>
362 </execution>
363 </executions>
364 </plugin>
365 </plugins>
366 </build>
367 </profile>
368
369 </profiles>
370
371 <pluginRepositories>
372 </pluginRepositories>
373
374 <distributionManagement>
375 <site>
376 <id>pixie</id>
377 <url>scp://pixie.qos.ch/var/www/www.slf4j.org/htdocs/</url>
378 </site>
379
380 <repository>
381 <!--<id>pixie</id>-->
382 <!--<url>scp://pixie.qos.ch/var/mvnrepo/</url>-->
383 <id>sonatype-nexus-staging</id>
384 <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
385 </repository>
386
387 </distributionManagement>
388
389 </project>
0 <project xmlns="http://maven.apache.org/POM/4.0.0"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <parent>
5 <groupId>org.slf4j</groupId>
6 <artifactId>slf4j-parent</artifactId>
7 <version>1.7.12</version>
8 </parent>
9
10 <modelVersion>4.0.0</modelVersion>
11
12 <artifactId>slf4j-android</artifactId>
13 <packaging>jar</packaging>
14 <name>SLF4J Android Binding</name>
15 <description>SLF4J Android Binding</description>
16 <url>http://www.slf4j.org</url>
17
18 <dependencies>
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-api</artifactId>
22 <version>${project.version}</version>
23 </dependency>
24
25 <dependency>
26 <groupId>com.google.android</groupId>
27 <artifactId>android</artifactId>
28 <version>1.5_r4</version>
29 <scope>provided</scope>
30 </dependency>
31 </dependencies>
32
33 <build>
34 <plugins>
35 <plugin>
36 <groupId>org.apache.maven.plugins</groupId>
37 <artifactId>maven-jar-plugin</artifactId>
38 <configuration>
39 <archive>
40 <manifestEntries>
41 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
42 <Bundle-Description>${project.description}</Bundle-Description>
43 <Implementation-Version>${project.version}</Implementation-Version>
44 </manifestEntries>
45 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
46 </archive>
47 </configuration>
48 </plugin>
49
50 <plugin>
51 <!-- Google Android requires class compatibility set to 5.0 -->
52 <groupId>org.apache.maven.plugins</groupId>
53 <artifactId>maven-compiler-plugin</artifactId>
54 <configuration>
55 <source>${required.jdk.version}</source>
56 <target>${required.jdk.version}</target>
57 </configuration>
58 </plugin>
59 </plugins>
60 </build>
61
62 </project>
0 /*
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import android.util.Log;
27 import org.slf4j.helpers.FormattingTuple;
28 import org.slf4j.helpers.MarkerIgnoringBase;
29 import org.slf4j.helpers.MessageFormatter;
30
31 /**
32 * <p>A simple implementation that delegates all log requests to the Google Android
33 * logging facilities. Note that this logger does not support {@link org.slf4j.Marker}.
34 * Methods taking marker data as parameter simply invoke the eponymous method
35 * without the Marker argument, discarding any marker data in the process.</p>
36 *
37 * <p>The logging levels specified for SLF4J can be almost directly mapped to
38 * the levels that exist in the Google Android platform. The following table
39 * shows the mapping implemented by this logger.</p>
40 *
41 * <table border="1">
42 * <tr><th><b>SLF4J<b></th><th><b>Android</b></th></tr>
43 * <tr><td>TRACE</td><td>{@link android.util.Log#VERBOSE}</td></tr>
44 * <tr><td>DEBUG</td><td>{@link android.util.Log#DEBUG}</td></tr>
45 * <tr><td>INFO</td><td>{@link android.util.Log#INFO}</td></tr>
46 * <tr><td>WARN</td><td>{@link android.util.Log#WARN}</td></tr>
47 * <tr><td>ERROR</td><td>{@link android.util.Log#ERROR}</td></tr>
48 * </table>
49 *
50 * <p>Use loggers as usual:
51 * <ul>
52 * <li>
53 * Declare a logger<br/>
54 * <code>private static final Logger logger = LoggerFactory.getLogger(MyClass.class);</code>
55 * </li>
56 * <li>
57 * Invoke logging methods, e.g.,<br/>
58 * <code>logger.debug("Some log message. Details: {}", someObject);</code><br/>
59 * <code>logger.debug("Some log message with varargs. Details: {}, {}, {}", someObject1, someObject2, someObject3);</code>
60 * </li>
61 * </ul>
62 * </p>
63 *
64 * <p>Logger instances created using the LoggerFactory are named either according to the name
65 * or the fully qualified class name of the class given as a parameter.
66 * Each logger name will be used as the log message tag on the Android platform.
67 * However, tag names cannot be longer than 23 characters so if logger name exceeds this limit then
68 * it will be truncated by the LoggerFactory. The following examples illustrate this.
69 * <table border="1">
70 * <tr><th><b>Original Name<b></th><th><b>Truncated Name</b></th></tr>
71 * <tr><td>org.example.myproject.mypackage.MyClass</td><td>o*.e*.m*.m*.MyClass</td></tr>
72 * <tr><td>o.e.myproject.mypackage.MyClass</td><td>o.e.m*.m*.MyClass</td></tr>
73 * <tr><td>org.example.ThisNameIsWayTooLongAndWillBeTruncated</td><td>*LongAndWillBeTruncated</td></tr>
74 * <tr><td>ThisNameIsWayTooLongAndWillBeTruncated</td><td>*LongAndWillBeTruncated</td></tr>
75 * </table>
76 * </p>
77 *
78 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
79 */
80 class AndroidLoggerAdapter extends MarkerIgnoringBase {
81 private static final long serialVersionUID = -1227274521521287937L;
82
83
84 /**
85 * Package access allows only {@link AndroidLoggerFactory} to instantiate
86 * SimpleLogger instances.
87 */
88 AndroidLoggerAdapter(String tag) {
89 this.name = tag;
90 }
91
92 /**
93 * Is this logger instance enabled for the VERBOSE level?
94 *
95 * @return True if this Logger is enabled for level VERBOSE, false otherwise.
96 */
97 public boolean isTraceEnabled() {
98 return isLoggable(Log.VERBOSE);
99 }
100
101 /**
102 * Log a message object at level VERBOSE.
103 *
104 * @param msg
105 * - the message object to be logged
106 */
107 public void trace(String msg) {
108 log(Log.VERBOSE, msg, null);
109 }
110
111 /**
112 * Log a message at level VERBOSE according to the specified format and
113 * argument.
114 *
115 * <p>
116 * This form avoids superfluous object creation when the logger is disabled
117 * for level VERBOSE.
118 * </p>
119 *
120 * @param format
121 * the format string
122 * @param arg
123 * the argument
124 */
125 public void trace(String format, Object arg) {
126 formatAndLog(Log.VERBOSE, format, arg);
127 }
128
129 /**
130 * Log a message at level VERBOSE according to the specified format and
131 * arguments.
132 *
133 * <p>
134 * This form avoids superfluous object creation when the logger is disabled
135 * for the VERBOSE level.
136 * </p>
137 *
138 * @param format
139 * the format string
140 * @param arg1
141 * the first argument
142 * @param arg2
143 * the second argument
144 */
145 public void trace(String format, Object arg1, Object arg2) {
146 formatAndLog(Log.VERBOSE, format, arg1, arg2);
147 }
148
149 /**
150 * Log a message at level VERBOSE according to the specified format and
151 * arguments.
152 *
153 * <p>
154 * This form avoids superfluous object creation when the logger is disabled
155 * for the VERBOSE level.
156 * </p>
157 *
158 * @param format
159 * the format string
160 * @param argArray
161 * an array of arguments
162 */
163 public void trace(String format, Object... argArray) {
164 formatAndLog(Log.VERBOSE, format, argArray);
165 }
166
167 /**
168 * Log an exception (throwable) at level VERBOSE with an accompanying message.
169 *
170 * @param msg
171 * the message accompanying the exception
172 * @param t
173 * the exception (throwable) to log
174 */
175 public void trace(String msg, Throwable t) {
176 log(Log.VERBOSE, msg, t);
177 }
178
179 /**
180 * Is this logger instance enabled for the DEBUG level?
181 *
182 * @return True if this Logger is enabled for level DEBUG, false otherwise.
183 */
184 public boolean isDebugEnabled() {
185 return isLoggable(Log.DEBUG);
186 }
187
188 /**
189 * Log a message object at level DEBUG.
190 *
191 * @param msg
192 * - the message object to be logged
193 */
194 public void debug(String msg) {
195 log(Log.DEBUG, msg, null);
196 }
197
198 /**
199 * Log a message at level DEBUG according to the specified format and argument.
200 *
201 * <p>
202 * This form avoids superfluous object creation when the logger is disabled
203 * for level DEBUG.
204 * </p>
205 *
206 * @param format
207 * the format string
208 * @param arg
209 * the argument
210 */
211 public void debug(String format, Object arg) {
212 formatAndLog(Log.DEBUG, format, arg);
213 }
214
215 /**
216 * Log a message at level DEBUG according to the specified format and
217 * arguments.
218 *
219 * <p>
220 * This form avoids superfluous object creation when the logger is disabled
221 * for the DEBUG level.
222 * </p>
223 *
224 * @param format
225 * the format string
226 * @param arg1
227 * the first argument
228 * @param arg2
229 * the second argument
230 */
231 public void debug(String format, Object arg1, Object arg2) {
232 formatAndLog(Log.DEBUG, format, arg1, arg2);
233 }
234
235 /**
236 * Log a message at level DEBUG according to the specified format and
237 * arguments.
238 *
239 * <p>
240 * This form avoids superfluous object creation when the logger is disabled
241 * for the DEBUG level.
242 * </p>
243 *
244 * @param format
245 * the format string
246 * @param argArray
247 * an array of arguments
248 */
249 public void debug(String format, Object... argArray) {
250 formatAndLog(Log.DEBUG, format, argArray);
251 }
252
253 /**
254 * Log an exception (throwable) at level DEBUG with an accompanying message.
255 *
256 * @param msg
257 * the message accompanying the exception
258 * @param t
259 * the exception (throwable) to log
260 */
261 public void debug(String msg, Throwable t) {
262 log(Log.VERBOSE, msg, t);
263 }
264
265 /**
266 * Is this logger instance enabled for the INFO level?
267 *
268 * @return True if this Logger is enabled for the INFO level, false otherwise.
269 */
270 public boolean isInfoEnabled() {
271 return isLoggable(Log.INFO);
272 }
273
274 /**
275 * Log a message object at the INFO level.
276 *
277 * @param msg
278 * - the message object to be logged
279 */
280 public void info(String msg) {
281 log(Log.INFO, msg, null);
282 }
283
284 /**
285 * Log a message at level INFO according to the specified format and argument.
286 *
287 * <p>
288 * This form avoids superfluous object creation when the logger is disabled
289 * for the INFO level.
290 * </p>
291 *
292 * @param format
293 * the format string
294 * @param arg
295 * the argument
296 */
297 public void info(String format, Object arg) {
298 formatAndLog(Log.INFO, format, arg);
299 }
300
301 /**
302 * Log a message at the INFO level according to the specified format and
303 * arguments.
304 *
305 * <p>
306 * This form avoids superfluous object creation when the logger is disabled
307 * for the INFO level.
308 * </p>
309 *
310 * @param format
311 * the format string
312 * @param arg1
313 * the first argument
314 * @param arg2
315 * the second argument
316 */
317 public void info(String format, Object arg1, Object arg2) {
318 formatAndLog(Log.INFO, format, arg1, arg2);
319 }
320
321 /**
322 * Log a message at level INFO according to the specified format and
323 * arguments.
324 *
325 * <p>
326 * This form avoids superfluous object creation when the logger is disabled
327 * for the INFO level.
328 * </p>
329 *
330 * @param format
331 * the format string
332 * @param argArray
333 * an array of arguments
334 */
335 public void info(String format, Object... argArray) {
336 formatAndLog(Log.INFO, format, argArray);
337 }
338
339 /**
340 * Log an exception (throwable) at the INFO level with an accompanying
341 * message.
342 *
343 * @param msg
344 * the message accompanying the exception
345 * @param t
346 * the exception (throwable) to log
347 */
348 public void info(String msg, Throwable t) {
349 log(Log.INFO, msg, t);
350 }
351
352 /**
353 * Is this logger instance enabled for the WARN level?
354 *
355 * @return True if this Logger is enabled for the WARN level, false
356 * otherwise.
357 */
358 public boolean isWarnEnabled() {
359 return isLoggable(Log.WARN);
360 }
361
362 /**
363 * Log a message object at the WARN level.
364 *
365 * @param msg
366 * - the message object to be logged
367 */
368 public void warn(String msg) {
369 log(Log.WARN, msg, null);
370 }
371
372 /**
373 * Log a message at the WARN level according to the specified format and
374 * argument.
375 *
376 * <p>
377 * This form avoids superfluous object creation when the logger is disabled
378 * for the WARN level.
379 * </p>
380 *
381 * @param format
382 * the format string
383 * @param arg
384 * the argument
385 */
386 public void warn(String format, Object arg) {
387 formatAndLog(Log.WARN, format, arg);
388 }
389
390 /**
391 * Log a message at the WARN level according to the specified format and
392 * arguments.
393 *
394 * <p>
395 * This form avoids superfluous object creation when the logger is disabled
396 * for the WARN level.
397 * </p>
398 *
399 * @param format
400 * the format string
401 * @param arg1
402 * the first argument
403 * @param arg2
404 * the second argument
405 */
406 public void warn(String format, Object arg1, Object arg2) {
407 formatAndLog(Log.WARN, format, arg1, arg2);
408 }
409
410 /**
411 * Log a message at level WARN according to the specified format and
412 * arguments.
413 *
414 * <p>
415 * This form avoids superfluous object creation when the logger is disabled
416 * for the WARN level.
417 * </p>
418 *
419 * @param format
420 * the format string
421 * @param argArray
422 * an array of arguments
423 */
424 public void warn(String format, Object... argArray) {
425 formatAndLog(Log.WARN, format, argArray);
426 }
427
428 /**
429 * Log an exception (throwable) at the WARN level with an accompanying
430 * message.
431 *
432 * @param msg
433 * the message accompanying the exception
434 * @param t
435 * the exception (throwable) to log
436 */
437 public void warn(String msg, Throwable t) {
438 log(Log.WARN, msg, t);
439 }
440
441 /**
442 * Is this logger instance enabled for level ERROR?
443 *
444 * @return True if this Logger is enabled for level ERROR, false otherwise.
445 */
446 public boolean isErrorEnabled() {
447 return isLoggable(Log.ERROR);
448 }
449
450 /**
451 * Log a message object at the ERROR level.
452 *
453 * @param msg
454 * - the message object to be logged
455 */
456 public void error(String msg) {
457 log(Log.ERROR, msg, null);
458 }
459
460 /**
461 * Log a message at the ERROR level according to the specified format and
462 * argument.
463 *
464 * <p>
465 * This form avoids superfluous object creation when the logger is disabled
466 * for the ERROR level.
467 * </p>
468 *
469 * @param format
470 * the format string
471 * @param arg
472 * the argument
473 */
474 public void error(String format, Object arg) {
475 formatAndLog(Log.ERROR, format, arg);
476 }
477
478 /**
479 * Log a message at the ERROR level according to the specified format and
480 * arguments.
481 *
482 * <p>
483 * This form avoids superfluous object creation when the logger is disabled
484 * for the ERROR level.
485 * </p>
486 *
487 * @param format
488 * the format string
489 * @param arg1
490 * the first argument
491 * @param arg2
492 * the second argument
493 */
494 public void error(String format, Object arg1, Object arg2) {
495 formatAndLog(Log.ERROR, format, arg1, arg2);
496 }
497
498 /**
499 * Log a message at level ERROR according to the specified format and
500 * arguments.
501 *
502 * <p>
503 * This form avoids superfluous object creation when the logger is disabled
504 * for the ERROR level.
505 * </p>
506 *
507 * @param format
508 * the format string
509 * @param argArray
510 * an array of arguments
511 */
512 public void error(String format, Object... argArray) {
513 formatAndLog(Log.ERROR, format, argArray);
514 }
515
516 /**
517 * Log an exception (throwable) at the ERROR level with an accompanying
518 * message.
519 *
520 * @param msg
521 * the message accompanying the exception
522 * @param t
523 * the exception (throwable) to log
524 */
525 public void error(String msg, Throwable t) {
526 log(Log.ERROR, msg, t);
527 }
528
529 private void formatAndLog(int priority, String format, Object... argArray) {
530 if (isLoggable(priority)) {
531 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
532 _log(priority, ft.getMessage(), ft.getThrowable());
533 }
534 }
535
536 private void log(int priority, String message, Throwable throwable) {
537 if (isLoggable(priority)) {
538 _log(priority, message, throwable);
539 }
540 }
541
542 private boolean isLoggable(int priority) {
543 return Log.isLoggable(name, priority);
544 }
545
546 private void _log(int priority, String message, Throwable throwable) {
547 if (throwable != null) {
548 message += '\n' + Log.getStackTraceString(throwable);
549 }
550 Log.println(priority, name, message);
551 }
552 }
0 /*
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.Logger;
28
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31
32 /**
33 * AndroidLoggerFactory is an implementation of {@link ILoggerFactory} returning
34 * the appropriately named {@link AndroidLoggerFactory} instance.
35 *
36 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
37 */
38 class AndroidLoggerFactory implements ILoggerFactory {
39 static final String ANONYMOUS_TAG = "null";
40 static final int TAG_MAX_LENGTH = 23;
41
42 private final ConcurrentMap<String, Logger> loggerMap = new ConcurrentHashMap<String, Logger>();
43
44 /**
45 * Return an appropriate {@link AndroidLoggerAdapter} instance by name.
46 */
47 public Logger getLogger(String name) {
48 String tag = loggerNameToTag(name);
49 Logger logger = loggerMap.get(tag);
50 if (logger == null) {
51 Logger newInstance = new AndroidLoggerAdapter(tag);
52 Logger oldInstance = loggerMap.putIfAbsent(tag, newInstance);
53 logger = oldInstance == null ? newInstance : oldInstance;
54 }
55 return logger;
56 }
57
58 /**
59 * Tag names cannot be longer than {@value #TAG_MAX_LENGTH} characters on Android platform.
60 *
61 * Returns the short logger tag (up to {@value #TAG_MAX_LENGTH} characters) for the given logger name.
62 * Traditionally loggers are named by fully-qualified Java classes; this
63 * method attempts to return a concise identifying part of such names.
64 *
65 * See also:
66 * android/system/core/include/cutils/property.h
67 * android/frameworks/base/core/jni/android_util_Log.cpp
68 * dalvik.system.DalvikLogging
69 *
70 */
71 static String loggerNameToTag(String loggerName) {
72 // Anonymous logger
73 if (loggerName == null) {
74 return ANONYMOUS_TAG;
75 }
76
77 int length = loggerName.length();
78 if (length <= TAG_MAX_LENGTH) {
79 return loggerName;
80 }
81
82 int tagLength = 0;
83 int lastTokenIndex = 0;
84 int lastPeriodIndex;
85 StringBuilder tagName = new StringBuilder(TAG_MAX_LENGTH + 3);
86 while ((lastPeriodIndex = loggerName.indexOf('.', lastTokenIndex)) != -1) {
87 tagName.append(loggerName.charAt(lastTokenIndex));
88 // token of one character appended as is otherwise truncate it to one character
89 int tokenLength = lastPeriodIndex - lastTokenIndex;
90 if (tokenLength > 1) {
91 tagName.append('*');
92 }
93 tagName.append('.');
94 lastTokenIndex = lastPeriodIndex + 1;
95
96 // check if name is already too long
97 tagLength = tagName.length();
98 if (tagLength > TAG_MAX_LENGTH) {
99 return getSimpleName(loggerName);
100 }
101 }
102
103 // Either we had no useful dot location at all
104 // or last token would exceed TAG_MAX_LENGTH
105 int tokenLength = length - lastTokenIndex;
106 if (tagLength == 0 || (tagLength + tokenLength) > TAG_MAX_LENGTH) {
107 return getSimpleName(loggerName);
108 }
109
110 // last token (usually class name) appended as is
111 tagName.append(loggerName, lastTokenIndex, length);
112 return tagName.toString();
113 }
114
115 private static String getSimpleName(String loggerName) {
116 // Take leading part and append '*' to indicate that it was truncated
117 int length = loggerName.length();
118 int lastPeriodIndex = loggerName.lastIndexOf('.');
119 return lastPeriodIndex != -1 && length - (lastPeriodIndex + 1) <= TAG_MAX_LENGTH
120 ? loggerName.substring(lastPeriodIndex + 1)
121 : '*' + loggerName.substring(length - TAG_MAX_LENGTH + 1);
122 }
123 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
36 */
37 public class StaticLoggerBinder implements LoggerFactoryBinder {
38
39 /**
40 * The unique instance of this class.
41 */
42 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticLoggerBinder singleton
48 */
49 public static StaticLoggerBinder getSingleton() {
50 return SINGLETON;
51 }
52
53 /**
54 * Declare the version of the SLF4J API this implementation is compiled against.
55 * The value of this field is usually modified with each release.
56 */
57 // to avoid constant folding by the compiler, this field must *not* be final
58 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
59
60
61 private static final String loggerFactoryClassStr = AndroidLoggerFactory.class.getName();
62
63 /**
64 * The ILoggerFactory instance returned by the {@link #getLoggerFactory} method
65 * should always be the same object
66 */
67 private final ILoggerFactory loggerFactory;
68
69 private StaticLoggerBinder() {
70 loggerFactory = new AndroidLoggerFactory();
71 }
72
73 public ILoggerFactory getLoggerFactory() {
74 return loggerFactory;
75 }
76
77 public String getLoggerFactoryClassStr() {
78 return loggerFactoryClassStr;
79 }
80 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29
30 /**
31 * This implementation is bound to {@link NOPMDCAdapter}.
32 *
33 * @author Ceki G&uuml;lc&uuml;
34 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
35 */
36 public class StaticMDCBinder {
37
38 /**
39 * The unique instance of this class.
40 */
41 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
42
43 private StaticMDCBinder() {
44 }
45
46 /**
47 * Currently this method always returns an instance of
48 * {@link NOPMDCAdapter}.
49 */
50 public MDCAdapter getMDCA() {
51 return new NOPMDCAdapter();
52 }
53
54 public String getMDCAdapterClassStr() {
55 return NOPMDCAdapter.class.getName();
56 }
57 }
0 /**
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 * @author Andrey Korzhevskiy <a.korzhevskiy@gmail.com>
38 */
39 public class StaticMarkerBinder implements MarkerFactoryBinder {
40
41 /**
42 * The unique instance of this class.
43 */
44 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
45
46 final IMarkerFactory markerFactory = new BasicMarkerFactory();
47
48 private StaticMarkerBinder() {
49 }
50
51 /**
52 * Currently this method always returns an instance of
53 * {@link BasicMarkerFactory}.
54 */
55 public IMarkerFactory getMarkerFactory() {
56 return markerFactory;
57 }
58
59 /**
60 * Currently, this method returns the class name of
61 * {@link BasicMarkerFactory}.
62 */
63 public String getMarkerFactoryClassStr() {
64 return BasicMarkerFactory.class.getName();
65 }
66 }
0 Implementation-Title: slf4j-android
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.android
3 Bundle-Name: slf4j-android
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}
8 Fragment-Host: slf4j.api
0 /*
1 * Copyright (c) 2004-2013 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.junit.Test;
27
28 import static junit.framework.Assert.assertEquals;
29
30 public class AndroidLoggerFactoryTest {
31 @Test
32 public void shortLoggerNames() {
33 assertEquals("o.test.p.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.p.TestClass"));
34 assertEquals("ex.test.TestClass", AndroidLoggerFactory.loggerNameToTag("ex.test.TestClass"));
35 assertEquals("MyClass", AndroidLoggerFactory.loggerNameToTag("MyClass"));
36 }
37
38 @Test
39 public void emptyLoggerNames() {
40 assertEquals(AndroidLoggerFactory.ANONYMOUS_TAG, AndroidLoggerFactory.loggerNameToTag(null));
41 assertEquals("", AndroidLoggerFactory.loggerNameToTag(""));
42 }
43
44 @Test
45 public void simpleLoggerName() {
46 assertEquals("o*.t*.p*.TestClass", AndroidLoggerFactory.loggerNameToTag("org.test.package.TestClass"));
47 }
48
49 @Test
50 public void loggerNameWithOneCharPackage() {
51 assertEquals("o.t*.p*.p*.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.project.package.TestClass"));
52 assertEquals("o.t*.p*.p.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.project.p.TestClass"));
53 }
54
55 @Test
56 public void longLoggerName() {
57 assertEquals("AndroidLoggerFactory", AndroidLoggerFactory.loggerNameToTag("org.slf4j.impl.AndroidLoggerFactory"));
58 }
59
60 @Test
61 public void veryLongLoggerName() {
62 assertEquals("*meAndShouldBeTruncated", AndroidLoggerFactory.loggerNameToTag("IAmAVeryLongLoggerNameAndShouldBeTruncated"));
63 }
64
65 @Test
66 public void oneWordLoggerName() {
67 assertEquals("TestClass", AndroidLoggerFactory.loggerNameToTag("TestClass"));
68 }
69
70 @Test
71 public void weirdLoggerNames() {
72 assertEquals("WeirdLoggerName.", AndroidLoggerFactory.loggerNameToTag("WeirdLoggerName."));
73 assertEquals(".WeirdLoggerName", AndroidLoggerFactory.loggerNameToTag(".WeirdLoggerName"));
74 assertEquals(".WeirdLoggerName.", AndroidLoggerFactory.loggerNameToTag(".WeirdLoggerName."));
75 assertEquals(".", AndroidLoggerFactory.loggerNameToTag("."));
76 assertEquals("..", AndroidLoggerFactory.loggerNameToTag(".."));
77 }
78 }
0 <project xmlns="http://maven.apache.org/POM/4.0.0"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.12</version>
10 </parent>
11
12 <artifactId>slf4j-api</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J API Module</name>
16 <description>The slf4j API</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <dependencies>
21 </dependencies>
22
23 <build>
24 <plugins>
25 <plugin>
26 <groupId>org.apache.maven.plugins</groupId>
27 <artifactId>maven-surefire-plugin</artifactId>
28 <configuration>
29 <forkMode>once</forkMode>
30 <reportFormat>plain</reportFormat>
31 <trimStackTrace>false</trimStackTrace>
32 <excludes>
33 <exclude>**/AllTest.java</exclude>
34 <exclude>**/PackageTest.java</exclude>
35 </excludes>
36 </configuration>
37 </plugin>
38
39 <plugin>
40 <groupId>org.apache.maven.plugins</groupId>
41 <artifactId>maven-jar-plugin</artifactId>
42 <configuration>
43 <archive>
44 <manifestEntries>
45 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
46 <Bundle-Description>${project.description}</Bundle-Description>
47 <Implementation-Version>${project.version}</Implementation-Version>
48 </manifestEntries>
49 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
50 </archive>
51 </configuration>
52 <executions>
53 <execution>
54 <id>bundle-test-jar</id>
55 <phase>package</phase>
56 <goals>
57 <goal>jar</goal>
58 <goal>test-jar</goal>
59 </goals>
60 </execution>
61 </executions>
62 </plugin>
63
64 <plugin>
65 <groupId>org.apache.maven.plugins</groupId>
66 <artifactId>maven-antrun-plugin</artifactId>
67 <executions>
68 <execution>
69 <phase>process-classes</phase>
70 <goals>
71 <goal>run</goal>
72 </goals>
73 </execution>
74 </executions>
75 <configuration>
76 <tasks>
77 <echo>Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder</echo>
78 <delete dir="target/classes/org/slf4j/impl"/>
79 </tasks>
80 </configuration>
81 </plugin>
82
83 </plugins>
84
85 </build>
86
87 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 /**
27 * <code>ILoggerFactory</code> instances manufacture {@link Logger}
28 * instances by name.
29 *
30 * <p>Most users retrieve {@link Logger} instances through the static
31 * {@link LoggerFactory#getLogger(String)} method. An instance of of this
32 * interface is bound internally with {@link LoggerFactory} class at
33 * compile time.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public interface ILoggerFactory {
38
39 /**
40 * Return an appropriate {@link Logger} instance as specified by the
41 * <code>name</code> parameter.
42 *
43 * <p>If the name parameter is equal to {@link Logger#ROOT_LOGGER_NAME}, that is
44 * the string value "ROOT" (case insensitive), then the root logger of the
45 * underlying logging system is returned.
46 *
47 * <p>Null-valued name arguments are considered invalid.
48 *
49 * <p>Certain extremely simple logging systems, e.g. NOP, may always
50 * return the same logger instance regardless of the requested name.
51 *
52 * @param name the name of the Logger to return
53 * @return a Logger instance
54 */
55 public Logger getLogger(String name);
56 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 /**
27 * Implementations of this interface are used to manufacture {@link Marker}
28 * instances.
29 *
30 * <p>See the section <a href="http://slf4j.org/faq.html#3">Implementing
31 * the SLF4J API</a> in the FAQ for details on how to make your logging
32 * system conform to SLF4J.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public interface IMarkerFactory {
37
38 /**
39 * Manufacture a {@link Marker} instance by name. If the instance has been
40 * created earlier, return the previously created instance.
41 *
42 * <p>Null name values are not allowed.
43 *
44 * @param name the name of the marker to be created, null value is
45 * not allowed.
46 *
47 * @return a Marker instance
48 */
49 Marker getMarker(String name);
50
51 /**
52 * Checks if the marker with the name already exists. If name is null, then false
53 * is returned.
54 *
55 * @param name logger name to check for
56 * @return true id the marker exists, false otherwise.
57 */
58 boolean exists(String name);
59
60 /**
61 * Detach an existing marker.
62 * <p>
63 * Note that after a marker is detached, there might still be "dangling" references
64 * to the detached marker.
65 *
66 *
67 * @param name The name of the marker to detach
68 * @return whether the marker could be detached or not
69 */
70 boolean detachMarker(String name);
71
72 /**
73 * Create a marker which is detached (even at birth) from this IMarkerFactory.
74 *
75 * @param name marker name
76 * @return a dangling marker
77 * @since 1.5.1
78 */
79 Marker getDetachedMarker(String name);
80 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j;
26
27 /**
28 * The org.slf4j.Logger interface is the main user entry point of SLF4J API.
29 * It is expected that logging takes place through concrete implementations
30 * of this interface.
31 * <p/>
32 * <h3>Typical usage pattern:</h3>
33 * <pre>
34 * import org.slf4j.Logger;
35 * import org.slf4j.LoggerFactory;
36 *
37 * public class Wombat {
38 *
39 * <span style="color:green">final static Logger logger = LoggerFactory.getLogger(Wombat.class);</span>
40 * Integer t;
41 * Integer oldT;
42 *
43 * public void setTemperature(Integer temperature) {
44 * oldT = t;
45 * t = temperature;
46 * <span style="color:green">logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);</span>
47 * if(temperature.intValue() > 50) {
48 * <span style="color:green">logger.info("Temperature has risen above 50 degrees.");</span>
49 * }
50 * }
51 * }
52 * </pre>
53 *
54 * Be sure to read the FAQ entry relating to <a href="../../../faq.html#logging_performance">parameterized
55 * logging</a>. Note that logging statements can be parameterized in
56 * <a href="../../../faq.html#paramException">presence of an exception/throwable</a>.
57 *
58 * <p>Once you are comfortable using loggers, i.e. instances of this interface, consider using
59 * <a href="MDC.html">MDC</a> as well as <a href="Marker.html">Markers</a>.</p>
60 *
61 * @author Ceki G&uuml;lc&uuml;
62 */
63 public interface Logger {
64
65 /**
66 * Case insensitive String constant used to retrieve the name of the root logger.
67 *
68 * @since 1.3
69 */
70 final public String ROOT_LOGGER_NAME = "ROOT";
71
72 /**
73 * Return the name of this <code>Logger</code> instance.
74 * @return name of this logger instance
75 */
76 public String getName();
77
78 /**
79 * Is the logger instance enabled for the TRACE level?
80 *
81 * @return True if this Logger is enabled for the TRACE level,
82 * false otherwise.
83 * @since 1.4
84 */
85 public boolean isTraceEnabled();
86
87 /**
88 * Log a message at the TRACE level.
89 *
90 * @param msg the message string to be logged
91 * @since 1.4
92 */
93 public void trace(String msg);
94
95 /**
96 * Log a message at the TRACE level according to the specified format
97 * and argument.
98 * <p/>
99 * <p>This form avoids superfluous object creation when the logger
100 * is disabled for the TRACE level. </p>
101 *
102 * @param format the format string
103 * @param arg the argument
104 * @since 1.4
105 */
106 public void trace(String format, Object arg);
107
108 /**
109 * Log a message at the TRACE level according to the specified format
110 * and arguments.
111 * <p/>
112 * <p>This form avoids superfluous object creation when the logger
113 * is disabled for the TRACE level. </p>
114 *
115 * @param format the format string
116 * @param arg1 the first argument
117 * @param arg2 the second argument
118 * @since 1.4
119 */
120 public void trace(String format, Object arg1, Object arg2);
121
122 /**
123 * Log a message at the TRACE level according to the specified format
124 * and arguments.
125 * <p/>
126 * <p>This form avoids superfluous string concatenation when the logger
127 * is disabled for the TRACE level. However, this variant incurs the hidden
128 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
129 * even if this logger is disabled for TRACE. The variants taking {@link #trace(String, Object) one} and
130 * {@link #trace(String, Object, Object) two} arguments exist solely in order to avoid this hidden cost.</p>
131 *
132 * @param format the format string
133 * @param arguments a list of 3 or more arguments
134 * @since 1.4
135 */
136 public void trace(String format, Object... arguments);
137
138 /**
139 * Log an exception (throwable) at the TRACE level with an
140 * accompanying message.
141 *
142 * @param msg the message accompanying the exception
143 * @param t the exception (throwable) to log
144 * @since 1.4
145 */
146 public void trace(String msg, Throwable t);
147
148 /**
149 * Similar to {@link #isTraceEnabled()} method except that the
150 * marker data is also taken into account.
151 *
152 * @param marker The marker data to take into consideration
153 * @return True if this Logger is enabled for the TRACE level,
154 * false otherwise.
155 *
156 * @since 1.4
157 */
158 public boolean isTraceEnabled(Marker marker);
159
160 /**
161 * Log a message with the specific Marker at the TRACE level.
162 *
163 * @param marker the marker data specific to this log statement
164 * @param msg the message string to be logged
165 * @since 1.4
166 */
167 public void trace(Marker marker, String msg);
168
169 /**
170 * This method is similar to {@link #trace(String, Object)} method except that the
171 * marker data is also taken into consideration.
172 *
173 * @param marker the marker data specific to this log statement
174 * @param format the format string
175 * @param arg the argument
176 * @since 1.4
177 */
178 public void trace(Marker marker, String format, Object arg);
179
180 /**
181 * This method is similar to {@link #trace(String, Object, Object)}
182 * method except that the marker data is also taken into
183 * consideration.
184 *
185 * @param marker the marker data specific to this log statement
186 * @param format the format string
187 * @param arg1 the first argument
188 * @param arg2 the second argument
189 * @since 1.4
190 */
191 public void trace(Marker marker, String format, Object arg1, Object arg2);
192
193 /**
194 * This method is similar to {@link #trace(String, Object...)}
195 * method except that the marker data is also taken into
196 * consideration.
197 *
198 * @param marker the marker data specific to this log statement
199 * @param format the format string
200 * @param argArray an array of arguments
201 * @since 1.4
202 */
203 public void trace(Marker marker, String format, Object... argArray);
204
205 /**
206 * This method is similar to {@link #trace(String, Throwable)} method except that the
207 * marker data is also taken into consideration.
208 *
209 * @param marker the marker data specific to this log statement
210 * @param msg the message accompanying the exception
211 * @param t the exception (throwable) to log
212 * @since 1.4
213 */
214 public void trace(Marker marker, String msg, Throwable t);
215
216 /**
217 * Is the logger instance enabled for the DEBUG level?
218 *
219 * @return True if this Logger is enabled for the DEBUG level,
220 * false otherwise.
221 */
222 public boolean isDebugEnabled();
223
224 /**
225 * Log a message at the DEBUG level.
226 *
227 * @param msg the message string to be logged
228 */
229 public void debug(String msg);
230
231 /**
232 * Log a message at the DEBUG level according to the specified format
233 * and argument.
234 * <p/>
235 * <p>This form avoids superfluous object creation when the logger
236 * is disabled for the DEBUG level. </p>
237 *
238 * @param format the format string
239 * @param arg the argument
240 */
241 public void debug(String format, Object arg);
242
243 /**
244 * Log a message at the DEBUG level according to the specified format
245 * and arguments.
246 * <p/>
247 * <p>This form avoids superfluous object creation when the logger
248 * is disabled for the DEBUG level. </p>
249 *
250 * @param format the format string
251 * @param arg1 the first argument
252 * @param arg2 the second argument
253 */
254 public void debug(String format, Object arg1, Object arg2);
255
256 /**
257 * Log a message at the DEBUG level according to the specified format
258 * and arguments.
259 * <p/>
260 * <p>This form avoids superfluous string concatenation when the logger
261 * is disabled for the DEBUG level. However, this variant incurs the hidden
262 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
263 * even if this logger is disabled for DEBUG. The variants taking
264 * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
265 * arguments exist solely in order to avoid this hidden cost.</p>
266 *
267 * @param format the format string
268 * @param arguments a list of 3 or more arguments
269 */
270 public void debug(String format, Object... arguments);
271
272 /**
273 * Log an exception (throwable) at the DEBUG level with an
274 * accompanying message.
275 *
276 * @param msg the message accompanying the exception
277 * @param t the exception (throwable) to log
278 */
279 public void debug(String msg, Throwable t);
280
281 /**
282 * Similar to {@link #isDebugEnabled()} method except that the
283 * marker data is also taken into account.
284 *
285 * @param marker The marker data to take into consideration
286 * @return True if this Logger is enabled for the DEBUG level,
287 * false otherwise.
288 */
289 public boolean isDebugEnabled(Marker marker);
290
291 /**
292 * Log a message with the specific Marker at the DEBUG level.
293 *
294 * @param marker the marker data specific to this log statement
295 * @param msg the message string to be logged
296 */
297 public void debug(Marker marker, String msg);
298
299 /**
300 * This method is similar to {@link #debug(String, Object)} method except that the
301 * marker data is also taken into consideration.
302 *
303 * @param marker the marker data specific to this log statement
304 * @param format the format string
305 * @param arg the argument
306 */
307 public void debug(Marker marker, String format, Object arg);
308
309 /**
310 * This method is similar to {@link #debug(String, Object, Object)}
311 * method except that the marker data is also taken into
312 * consideration.
313 *
314 * @param marker the marker data specific to this log statement
315 * @param format the format string
316 * @param arg1 the first argument
317 * @param arg2 the second argument
318 */
319 public void debug(Marker marker, String format, Object arg1, Object arg2);
320
321 /**
322 * This method is similar to {@link #debug(String, Object...)}
323 * method except that the marker data is also taken into
324 * consideration.
325 *
326 * @param marker the marker data specific to this log statement
327 * @param format the format string
328 * @param arguments a list of 3 or more arguments
329 */
330 public void debug(Marker marker, String format, Object... arguments);
331
332 /**
333 * This method is similar to {@link #debug(String, Throwable)} method except that the
334 * marker data is also taken into consideration.
335 *
336 * @param marker the marker data specific to this log statement
337 * @param msg the message accompanying the exception
338 * @param t the exception (throwable) to log
339 */
340 public void debug(Marker marker, String msg, Throwable t);
341
342 /**
343 * Is the logger instance enabled for the INFO level?
344 *
345 * @return True if this Logger is enabled for the INFO level,
346 * false otherwise.
347 */
348 public boolean isInfoEnabled();
349
350 /**
351 * Log a message at the INFO level.
352 *
353 * @param msg the message string to be logged
354 */
355 public void info(String msg);
356
357 /**
358 * Log a message at the INFO level according to the specified format
359 * and argument.
360 * <p/>
361 * <p>This form avoids superfluous object creation when the logger
362 * is disabled for the INFO level. </p>
363 *
364 * @param format the format string
365 * @param arg the argument
366 */
367 public void info(String format, Object arg);
368
369 /**
370 * Log a message at the INFO level according to the specified format
371 * and arguments.
372 * <p/>
373 * <p>This form avoids superfluous object creation when the logger
374 * is disabled for the INFO level. </p>
375 *
376 * @param format the format string
377 * @param arg1 the first argument
378 * @param arg2 the second argument
379 */
380 public void info(String format, Object arg1, Object arg2);
381
382 /**
383 * Log a message at the INFO level according to the specified format
384 * and arguments.
385 * <p/>
386 * <p>This form avoids superfluous string concatenation when the logger
387 * is disabled for the INFO level. However, this variant incurs the hidden
388 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
389 * even if this logger is disabled for INFO. The variants taking
390 * {@link #info(String, Object) one} and {@link #info(String, Object, Object) two}
391 * arguments exist solely in order to avoid this hidden cost.</p>
392 *
393 * @param format the format string
394 * @param arguments a list of 3 or more arguments
395 */
396 public void info(String format, Object... arguments);
397
398 /**
399 * Log an exception (throwable) at the INFO level with an
400 * accompanying message.
401 *
402 * @param msg the message accompanying the exception
403 * @param t the exception (throwable) to log
404 */
405 public void info(String msg, Throwable t);
406
407 /**
408 * Similar to {@link #isInfoEnabled()} method except that the marker
409 * data is also taken into consideration.
410 *
411 * @param marker The marker data to take into consideration
412 * @return true if this logger is warn enabled, false otherwise
413 */
414 public boolean isInfoEnabled(Marker marker);
415
416 /**
417 * Log a message with the specific Marker at the INFO level.
418 *
419 * @param marker The marker specific to this log statement
420 * @param msg the message string to be logged
421 */
422 public void info(Marker marker, String msg);
423
424 /**
425 * This method is similar to {@link #info(String, Object)} method except that the
426 * marker data is also taken into consideration.
427 *
428 * @param marker the marker data specific to this log statement
429 * @param format the format string
430 * @param arg the argument
431 */
432 public void info(Marker marker, String format, Object arg);
433
434 /**
435 * This method is similar to {@link #info(String, Object, Object)}
436 * method except that the marker data is also taken into
437 * consideration.
438 *
439 * @param marker the marker data specific to this log statement
440 * @param format the format string
441 * @param arg1 the first argument
442 * @param arg2 the second argument
443 */
444 public void info(Marker marker, String format, Object arg1, Object arg2);
445
446 /**
447 * This method is similar to {@link #info(String, Object...)}
448 * method except that the marker data is also taken into
449 * consideration.
450 *
451 * @param marker the marker data specific to this log statement
452 * @param format the format string
453 * @param arguments a list of 3 or more arguments
454 */
455 public void info(Marker marker, String format, Object... arguments);
456
457 /**
458 * This method is similar to {@link #info(String, Throwable)} method
459 * except that the marker data is also taken into consideration.
460 *
461 * @param marker the marker data for this log statement
462 * @param msg the message accompanying the exception
463 * @param t the exception (throwable) to log
464 */
465 public void info(Marker marker, String msg, Throwable t);
466
467 /**
468 * Is the logger instance enabled for the WARN level?
469 *
470 * @return True if this Logger is enabled for the WARN level,
471 * false otherwise.
472 */
473 public boolean isWarnEnabled();
474
475 /**
476 * Log a message at the WARN level.
477 *
478 * @param msg the message string to be logged
479 */
480 public void warn(String msg);
481
482 /**
483 * Log a message at the WARN level according to the specified format
484 * and argument.
485 * <p/>
486 * <p>This form avoids superfluous object creation when the logger
487 * is disabled for the WARN level. </p>
488 *
489 * @param format the format string
490 * @param arg the argument
491 */
492 public void warn(String format, Object arg);
493
494 /**
495 * Log a message at the WARN level according to the specified format
496 * and arguments.
497 * <p/>
498 * <p>This form avoids superfluous string concatenation when the logger
499 * is disabled for the WARN level. However, this variant incurs the hidden
500 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
501 * even if this logger is disabled for WARN. The variants taking
502 * {@link #warn(String, Object) one} and {@link #warn(String, Object, Object) two}
503 * arguments exist solely in order to avoid this hidden cost.</p>
504 *
505 * @param format the format string
506 * @param arguments a list of 3 or more arguments
507 */
508 public void warn(String format, Object... arguments);
509
510 /**
511 * Log a message at the WARN level according to the specified format
512 * and arguments.
513 * <p/>
514 * <p>This form avoids superfluous object creation when the logger
515 * is disabled for the WARN level. </p>
516 *
517 * @param format the format string
518 * @param arg1 the first argument
519 * @param arg2 the second argument
520 */
521 public void warn(String format, Object arg1, Object arg2);
522
523 /**
524 * Log an exception (throwable) at the WARN level with an
525 * accompanying message.
526 *
527 * @param msg the message accompanying the exception
528 * @param t the exception (throwable) to log
529 */
530 public void warn(String msg, Throwable t);
531
532 /**
533 * Similar to {@link #isWarnEnabled()} method except that the marker
534 * data is also taken into consideration.
535 *
536 * @param marker The marker data to take into consideration
537 * @return True if this Logger is enabled for the WARN level,
538 * false otherwise.
539 */
540 public boolean isWarnEnabled(Marker marker);
541
542 /**
543 * Log a message with the specific Marker at the WARN level.
544 *
545 * @param marker The marker specific to this log statement
546 * @param msg the message string to be logged
547 */
548 public void warn(Marker marker, String msg);
549
550 /**
551 * This method is similar to {@link #warn(String, Object)} method except that the
552 * marker data is also taken into consideration.
553 *
554 * @param marker the marker data specific to this log statement
555 * @param format the format string
556 * @param arg the argument
557 */
558 public void warn(Marker marker, String format, Object arg);
559
560 /**
561 * This method is similar to {@link #warn(String, Object, Object)}
562 * method except that the marker data is also taken into
563 * consideration.
564 *
565 * @param marker the marker data specific to this log statement
566 * @param format the format string
567 * @param arg1 the first argument
568 * @param arg2 the second argument
569 */
570 public void warn(Marker marker, String format, Object arg1, Object arg2);
571
572 /**
573 * This method is similar to {@link #warn(String, Object...)}
574 * method except that the marker data is also taken into
575 * consideration.
576 *
577 * @param marker the marker data specific to this log statement
578 * @param format the format string
579 * @param arguments a list of 3 or more arguments
580 */
581 public void warn(Marker marker, String format, Object... arguments);
582
583 /**
584 * This method is similar to {@link #warn(String, Throwable)} method
585 * except that the marker data is also taken into consideration.
586 *
587 * @param marker the marker data for this log statement
588 * @param msg the message accompanying the exception
589 * @param t the exception (throwable) to log
590 */
591 public void warn(Marker marker, String msg, Throwable t);
592
593 /**
594 * Is the logger instance enabled for the ERROR level?
595 *
596 * @return True if this Logger is enabled for the ERROR level,
597 * false otherwise.
598 */
599 public boolean isErrorEnabled();
600
601 /**
602 * Log a message at the ERROR level.
603 *
604 * @param msg the message string to be logged
605 */
606 public void error(String msg);
607
608 /**
609 * Log a message at the ERROR level according to the specified format
610 * and argument.
611 * <p/>
612 * <p>This form avoids superfluous object creation when the logger
613 * is disabled for the ERROR level. </p>
614 *
615 * @param format the format string
616 * @param arg the argument
617 */
618 public void error(String format, Object arg);
619
620 /**
621 * Log a message at the ERROR level according to the specified format
622 * and arguments.
623 * <p/>
624 * <p>This form avoids superfluous object creation when the logger
625 * is disabled for the ERROR level. </p>
626 *
627 * @param format the format string
628 * @param arg1 the first argument
629 * @param arg2 the second argument
630 */
631 public void error(String format, Object arg1, Object arg2);
632
633 /**
634 * Log a message at the ERROR level according to the specified format
635 * and arguments.
636 * <p/>
637 * <p>This form avoids superfluous string concatenation when the logger
638 * is disabled for the ERROR level. However, this variant incurs the hidden
639 * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method,
640 * even if this logger is disabled for ERROR. The variants taking
641 * {@link #error(String, Object) one} and {@link #error(String, Object, Object) two}
642 * arguments exist solely in order to avoid this hidden cost.</p>
643 *
644 * @param format the format string
645 * @param arguments a list of 3 or more arguments
646 */
647 public void error(String format, Object... arguments);
648
649 /**
650 * Log an exception (throwable) at the ERROR level with an
651 * accompanying message.
652 *
653 * @param msg the message accompanying the exception
654 * @param t the exception (throwable) to log
655 */
656 public void error(String msg, Throwable t);
657
658 /**
659 * Similar to {@link #isErrorEnabled()} method except that the
660 * marker data is also taken into consideration.
661 *
662 * @param marker The marker data to take into consideration
663 * @return True if this Logger is enabled for the ERROR level,
664 * false otherwise.
665 */
666 public boolean isErrorEnabled(Marker marker);
667
668 /**
669 * Log a message with the specific Marker at the ERROR level.
670 *
671 * @param marker The marker specific to this log statement
672 * @param msg the message string to be logged
673 */
674 public void error(Marker marker, String msg);
675
676 /**
677 * This method is similar to {@link #error(String, Object)} method except that the
678 * marker data is also taken into consideration.
679 *
680 * @param marker the marker data specific to this log statement
681 * @param format the format string
682 * @param arg the argument
683 */
684 public void error(Marker marker, String format, Object arg);
685
686 /**
687 * This method is similar to {@link #error(String, Object, Object)}
688 * method except that the marker data is also taken into
689 * consideration.
690 *
691 * @param marker the marker data specific to this log statement
692 * @param format the format string
693 * @param arg1 the first argument
694 * @param arg2 the second argument
695 */
696 public void error(Marker marker, String format, Object arg1, Object arg2);
697
698 /**
699 * This method is similar to {@link #error(String, Object...)}
700 * method except that the marker data is also taken into
701 * consideration.
702 *
703 * @param marker the marker data specific to this log statement
704 * @param format the format string
705 * @param arguments a list of 3 or more arguments
706 */
707 public void error(Marker marker, String format, Object... arguments);
708
709 /**
710 * This method is similar to {@link #error(String, Throwable)}
711 * method except that the marker data is also taken into
712 * consideration.
713 *
714 * @param marker the marker data specific to this log statement
715 * @param msg the message accompanying the exception
716 * @param t the exception (throwable) to log
717 */
718 public void error(Marker marker, String msg, Throwable t);
719
720 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.IOException;
27 import java.net.URL;
28 import java.util.Arrays;
29 import java.util.Enumeration;
30 import java.util.Iterator;
31 import java.util.LinkedHashSet;
32 import java.util.List;
33 import java.util.Set;
34
35 import org.slf4j.helpers.NOPLoggerFactory;
36 import org.slf4j.helpers.SubstituteLogger;
37 import org.slf4j.helpers.SubstituteLoggerFactory;
38 import org.slf4j.helpers.Util;
39 import org.slf4j.impl.StaticLoggerBinder;
40
41 /**
42 * The <code>LoggerFactory</code> is a utility class producing Loggers for
43 * various logging APIs, most notably for log4j, logback and JDK 1.4 logging.
44 * Other implementations such as {@link org.slf4j.impl.NOPLogger NOPLogger} and
45 * {@link org.slf4j.impl.SimpleLogger SimpleLogger} are also supported.
46 * <p/>
47 * <p/>
48 * <code>LoggerFactory</code> is essentially a wrapper around an
49 * {@link ILoggerFactory} instance bound with <code>LoggerFactory</code> at
50 * compile time.
51 * <p/>
52 * <p/>
53 * Please note that all methods in <code>LoggerFactory</code> are static.
54 *
55 *
56 * @author Alexander Dorokhine
57 * @author Robert Elliot
58 * @author Ceki G&uuml;lc&uuml;
59 *
60 */
61 public final class LoggerFactory {
62
63 static final String CODES_PREFIX = "http://www.slf4j.org/codes.html";
64
65 static final String NO_STATICLOGGERBINDER_URL = CODES_PREFIX + "#StaticLoggerBinder";
66 static final String MULTIPLE_BINDINGS_URL = CODES_PREFIX + "#multiple_bindings";
67 static final String NULL_LF_URL = CODES_PREFIX + "#null_LF";
68 static final String VERSION_MISMATCH = CODES_PREFIX + "#version_mismatch";
69 static final String SUBSTITUTE_LOGGER_URL = CODES_PREFIX + "#substituteLogger";
70 static final String LOGGER_NAME_MISMATCH_URL = CODES_PREFIX + "#loggerNameMismatch";
71
72 static final String UNSUCCESSFUL_INIT_URL = CODES_PREFIX + "#unsuccessfulInit";
73 static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory could not be successfully initialized. See also " + UNSUCCESSFUL_INIT_URL;
74
75 static final int UNINITIALIZED = 0;
76 static final int ONGOING_INITIALIZATION = 1;
77 static final int FAILED_INITIALIZATION = 2;
78 static final int SUCCESSFUL_INITIALIZATION = 3;
79 static final int NOP_FALLBACK_INITIALIZATION = 4;
80
81 static int INITIALIZATION_STATE = UNINITIALIZED;
82 static SubstituteLoggerFactory TEMP_FACTORY = new SubstituteLoggerFactory();
83 static NOPLoggerFactory NOP_FALLBACK_FACTORY = new NOPLoggerFactory();
84
85 // Support for detecting mismatched logger names.
86 static final String DETECT_LOGGER_NAME_MISMATCH_PROPERTY = "slf4j.detectLoggerNameMismatch";
87 static boolean DETECT_LOGGER_NAME_MISMATCH = Boolean.getBoolean(DETECT_LOGGER_NAME_MISMATCH_PROPERTY);
88
89 /**
90 * It is LoggerFactory's responsibility to track version changes and manage
91 * the compatibility list.
92 * <p/>
93 * <p/>
94 * It is assumed that all versions in the 1.6 are mutually compatible.
95 */
96 static private final String[] API_COMPATIBILITY_LIST = new String[] { "1.6", "1.7" };
97
98 // private constructor prevents instantiation
99 private LoggerFactory() {
100 }
101
102 /**
103 * Force LoggerFactory to consider itself uninitialized.
104 * <p/>
105 * <p/>
106 * This method is intended to be called by classes (in the same package) for
107 * testing purposes. This method is internal. It can be modified, renamed or
108 * removed at any time without notice.
109 * <p/>
110 * <p/>
111 * You are strongly discouraged from calling this method in production code.
112 */
113 static void reset() {
114 INITIALIZATION_STATE = UNINITIALIZED;
115 TEMP_FACTORY = new SubstituteLoggerFactory();
116 }
117
118 private final static void performInitialization() {
119 bind();
120 if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
121 versionSanityCheck();
122 }
123 }
124
125 private static boolean messageContainsOrgSlf4jImplStaticLoggerBinder(String msg) {
126 if (msg == null)
127 return false;
128 if (msg.indexOf("org/slf4j/impl/StaticLoggerBinder") != -1)
129 return true;
130 if (msg.indexOf("org.slf4j.impl.StaticLoggerBinder") != -1)
131 return true;
132 return false;
133 }
134
135 private final static void bind() {
136 try {
137 Set<URL> staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet();
138 reportMultipleBindingAmbiguity(staticLoggerBinderPathSet);
139 // the next line does the binding
140 StaticLoggerBinder.getSingleton();
141 INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;
142 reportActualBinding(staticLoggerBinderPathSet);
143 fixSubstitutedLoggers();
144 } catch (NoClassDefFoundError ncde) {
145 String msg = ncde.getMessage();
146 if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) {
147 INITIALIZATION_STATE = NOP_FALLBACK_INITIALIZATION;
148 Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".");
149 Util.report("Defaulting to no-operation (NOP) logger implementation");
150 Util.report("See " + NO_STATICLOGGERBINDER_URL + " for further details.");
151 } else {
152 failedBinding(ncde);
153 throw ncde;
154 }
155 } catch (java.lang.NoSuchMethodError nsme) {
156 String msg = nsme.getMessage();
157 if (msg != null && msg.indexOf("org.slf4j.impl.StaticLoggerBinder.getSingleton()") != -1) {
158 INITIALIZATION_STATE = FAILED_INITIALIZATION;
159 Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding.");
160 Util.report("Your binding is version 1.5.5 or earlier.");
161 Util.report("Upgrade your binding to version 1.6.x.");
162 }
163 throw nsme;
164 } catch (Exception e) {
165 failedBinding(e);
166 throw new IllegalStateException("Unexpected initialization failure", e);
167 }
168 }
169
170 static void failedBinding(Throwable t) {
171 INITIALIZATION_STATE = FAILED_INITIALIZATION;
172 Util.report("Failed to instantiate SLF4J LoggerFactory", t);
173 }
174
175 private final static void fixSubstitutedLoggers() {
176 List<SubstituteLogger> loggers = TEMP_FACTORY.getLoggers();
177
178 if (loggers.isEmpty()) {
179 return;
180 }
181
182 Util.report("The following set of substitute loggers may have been accessed");
183 Util.report("during the initialization phase. Logging calls during this");
184 Util.report("phase were not honored. However, subsequent logging calls to these");
185 Util.report("loggers will work as normally expected.");
186 Util.report("See also " + SUBSTITUTE_LOGGER_URL);
187 for (SubstituteLogger subLogger : loggers) {
188 subLogger.setDelegate(getLogger(subLogger.getName()));
189 Util.report(subLogger.getName());
190 }
191
192 TEMP_FACTORY.clear();
193 }
194
195 private final static void versionSanityCheck() {
196 try {
197 String requested = StaticLoggerBinder.REQUESTED_API_VERSION;
198
199 boolean match = false;
200 for (int i = 0; i < API_COMPATIBILITY_LIST.length; i++) {
201 if (requested.startsWith(API_COMPATIBILITY_LIST[i])) {
202 match = true;
203 }
204 }
205 if (!match) {
206 Util.report("The requested version " + requested + " by your slf4j binding is not compatible with "
207 + Arrays.asList(API_COMPATIBILITY_LIST).toString());
208 Util.report("See " + VERSION_MISMATCH + " for further details.");
209 }
210 } catch (java.lang.NoSuchFieldError nsfe) {
211 // given our large user base and SLF4J's commitment to backward
212 // compatibility, we cannot cry here. Only for implementations
213 // which willingly declare a REQUESTED_API_VERSION field do we
214 // emit compatibility warnings.
215 } catch (Throwable e) {
216 // we should never reach here
217 Util.report("Unexpected problem occured during version sanity check", e);
218 }
219 }
220
221 // We need to use the name of the StaticLoggerBinder class, but we can't reference
222 // the class itself.
223 private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class";
224
225 private static Set<URL> findPossibleStaticLoggerBinderPathSet() {
226 // use Set instead of list in order to deal with bug #138
227 // LinkedHashSet appropriate here because it preserves insertion order during iteration
228 Set<URL> staticLoggerBinderPathSet = new LinkedHashSet<URL>();
229 try {
230 ClassLoader loggerFactoryClassLoader = LoggerFactory.class.getClassLoader();
231 Enumeration<URL> paths;
232 if (loggerFactoryClassLoader == null) {
233 paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
234 } else {
235 paths = loggerFactoryClassLoader.getResources(STATIC_LOGGER_BINDER_PATH);
236 }
237 while (paths.hasMoreElements()) {
238 URL path = (URL) paths.nextElement();
239 staticLoggerBinderPathSet.add(path);
240 }
241 } catch (IOException ioe) {
242 Util.report("Error getting resources from path", ioe);
243 }
244 return staticLoggerBinderPathSet;
245 }
246
247 private static boolean isAmbiguousStaticLoggerBinderPathSet(Set<URL> staticLoggerBinderPathSet) {
248 return staticLoggerBinderPathSet.size() > 1;
249 }
250
251 /**
252 * Prints a warning message on the console if multiple bindings were found on the class path.
253 * No reporting is done otherwise.
254 *
255 */
256 private static void reportMultipleBindingAmbiguity(Set<URL> staticLoggerBinderPathSet) {
257 if (isAmbiguousStaticLoggerBinderPathSet(staticLoggerBinderPathSet)) {
258 Util.report("Class path contains multiple SLF4J bindings.");
259 Iterator<URL> iterator = staticLoggerBinderPathSet.iterator();
260 while (iterator.hasNext()) {
261 URL path = (URL) iterator.next();
262 Util.report("Found binding in [" + path + "]");
263 }
264 Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation.");
265 }
266 }
267
268 private static void reportActualBinding(Set<URL> staticLoggerBinderPathSet) {
269 if (isAmbiguousStaticLoggerBinderPathSet(staticLoggerBinderPathSet)) {
270 Util.report("Actual binding is of type [" + StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr() + "]");
271 }
272 }
273
274 /**
275 * Return a logger named according to the name parameter using the statically
276 * bound {@link ILoggerFactory} instance.
277 *
278 * @param name The name of the logger.
279 * @return logger
280 */
281 public static Logger getLogger(String name) {
282 ILoggerFactory iLoggerFactory = getILoggerFactory();
283 return iLoggerFactory.getLogger(name);
284 }
285
286 /**
287 * Return a logger named corresponding to the class passed as parameter, using
288 * the statically bound {@link ILoggerFactory} instance.
289 *
290 * <p>In case the the <code>clazz</code> parameter differs from the name of
291 * the caller as computed internally by SLF4J, a logger name mismatch warning will be
292 * printed but only if the <code>slf4j.detectLoggerNameMismatch</code> system property is
293 * set to true. By default, this property is not set and no warnings will be printed
294 * even in case of a logger name mismatch.
295 *
296 * @param clazz the returned logger will be named after clazz
297 * @return logger
298 *
299 *
300 * @see <a href="http://www.slf4j.org/codes.html#loggerNameMismatch">Detected logger name mismatch</a>
301 */
302 public static Logger getLogger(Class<?> clazz) {
303 Logger logger = getLogger(clazz.getName());
304 if (DETECT_LOGGER_NAME_MISMATCH) {
305 Class<?> autoComputedCallingClass = Util.getCallingClass();
306 if (nonMatchingClasses(clazz, autoComputedCallingClass)) {
307 Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(),
308 autoComputedCallingClass.getName()));
309 Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation");
310 }
311 }
312 return logger;
313 }
314
315 private static boolean nonMatchingClasses(Class<?> clazz, Class<?> autoComputedCallingClass) {
316 return !autoComputedCallingClass.isAssignableFrom(clazz);
317 }
318
319 /**
320 * Return the {@link ILoggerFactory} instance in use.
321 * <p/>
322 * <p/>
323 * ILoggerFactory instance is bound with this class at compile time.
324 *
325 * @return the ILoggerFactory instance in use
326 */
327 public static ILoggerFactory getILoggerFactory() {
328 if (INITIALIZATION_STATE == UNINITIALIZED) {
329 INITIALIZATION_STATE = ONGOING_INITIALIZATION;
330 performInitialization();
331 }
332 switch (INITIALIZATION_STATE) {
333 case SUCCESSFUL_INITIALIZATION:
334 return StaticLoggerBinder.getSingleton().getLoggerFactory();
335 case NOP_FALLBACK_INITIALIZATION:
336 return NOP_FALLBACK_FACTORY;
337 case FAILED_INITIALIZATION:
338 throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG);
339 case ONGOING_INITIALIZATION:
340 // support re-entrant behavior.
341 // See also http://bugzilla.slf4j.org/show_bug.cgi?id=106
342 return TEMP_FACTORY;
343 }
344 throw new IllegalStateException("Unreachable code");
345 }
346 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.Closeable;
27 import java.util.Map;
28
29 import org.slf4j.helpers.NOPMDCAdapter;
30 import org.slf4j.helpers.BasicMDCAdapter;
31 import org.slf4j.helpers.Util;
32 import org.slf4j.impl.StaticMDCBinder;
33 import org.slf4j.spi.MDCAdapter;
34
35 /**
36 * This class hides and serves as a substitute for the underlying logging
37 * system's MDC implementation.
38 *
39 * <p>
40 * If the underlying logging system offers MDC functionality, then SLF4J's MDC,
41 * i.e. this class, will delegate to the underlying system's MDC. Note that at
42 * this time, only two logging systems, namely log4j and logback, offer MDC
43 * functionality. For java.util.logging which does not support MDC,
44 * {@link BasicMDCAdapter} will be used. For other systems, i.e slf4j-simple
45 * and slf4j-nop, {@link NOPMDCAdapter} will be used.
46 *
47 * <p>
48 * Thus, as a SLF4J user, you can take advantage of MDC in the presence of log4j,
49 * logback, or java.util.logging, but without forcing these systems as
50 * dependencies upon your users.
51 *
52 * <p>
53 * For more information on MDC please see the <a
54 * href="http://logback.qos.ch/manual/mdc.html">chapter on MDC</a> in the
55 * logback manual.
56 *
57 * <p>
58 * Please note that all methods in this class are static.
59 *
60 * @author Ceki G&uuml;lc&uuml;
61 * @since 1.4.1
62 */
63 public class MDC {
64
65 static final String NULL_MDCA_URL = "http://www.slf4j.org/codes.html#null_MDCA";
66 static final String NO_STATIC_MDC_BINDER_URL = "http://www.slf4j.org/codes.html#no_static_mdc_binder";
67 static MDCAdapter mdcAdapter;
68
69 /**
70 * An adapter to remove the key when done.
71 */
72 public static class MDCCloseable implements Closeable {
73 private final String key;
74
75 private MDCCloseable(String key) {
76 this.key = key;
77 }
78
79 public void close() {
80 MDC.remove(this.key);
81 }
82 }
83
84 private MDC() {
85 }
86
87 static {
88 try {
89 mdcAdapter = StaticMDCBinder.SINGLETON.getMDCA();
90 } catch (NoClassDefFoundError ncde) {
91 mdcAdapter = new NOPMDCAdapter();
92 String msg = ncde.getMessage();
93 if (msg != null && msg.indexOf("StaticMDCBinder") != -1) {
94 Util.report("Failed to load class \"org.slf4j.impl.StaticMDCBinder\".");
95 Util.report("Defaulting to no-operation MDCAdapter implementation.");
96 Util.report("See " + NO_STATIC_MDC_BINDER_URL + " for further details.");
97 } else {
98 throw ncde;
99 }
100 } catch (Exception e) {
101 // we should never get here
102 Util.report("MDC binding unsuccessful.", e);
103 }
104 }
105
106 /**
107 * Put a diagnostic context value (the <code>val</code> parameter) as identified with the
108 * <code>key</code> parameter into the current thread's diagnostic context map. The
109 * <code>key</code> parameter cannot be null. The <code>val</code> parameter
110 * can be null only if the underlying implementation supports it.
111 *
112 * <p>
113 * This method delegates all work to the MDC of the underlying logging system.
114 *
115 * @param key non-null key
116 * @param val value to put in the map
117 *
118 * @throws IllegalArgumentException
119 * in case the "key" parameter is null
120 */
121 public static void put(String key, String val) throws IllegalArgumentException {
122 if (key == null) {
123 throw new IllegalArgumentException("key parameter cannot be null");
124 }
125 if (mdcAdapter == null) {
126 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
127 }
128 mdcAdapter.put(key, val);
129 }
130
131 /**
132 * Put a diagnostic context value (the <code>val</code> parameter) as identified with the
133 * <code>key</code> parameter into the current thread's diagnostic context map. The
134 * <code>key</code> parameter cannot be null. The <code>val</code> parameter
135 * can be null only if the underlying implementation supports it.
136 *
137 * <p>
138 * This method delegates all work to the MDC of the underlying logging system.
139 * <p>
140 * This method return a <code>Closeable</code> object who can remove <code>key</code> when
141 * <code>close</code> is called.
142 *
143 * <p>
144 * Useful with Java 7 for example :
145 * <code>
146 * try(MDC.MDCCloseable closeable = MDC.putCloseable(key, value)) {
147 * ....
148 * }
149 * </code>
150 *
151 * @param key non-null key
152 * @param val value to put in the map
153 * @return a <code>Closeable</code> who can remove <code>key</code> when <code>close</code>
154 * is called.
155 *
156 * @throws IllegalArgumentException
157 * in case the "key" parameter is null
158 */
159 public static MDCCloseable putCloseable(String key, String val) throws IllegalArgumentException {
160 put(key, val);
161 return new MDCCloseable(key);
162 }
163
164 /**
165 * Get the diagnostic context identified by the <code>key</code> parameter. The
166 * <code>key</code> parameter cannot be null.
167 *
168 * <p>
169 * This method delegates all work to the MDC of the underlying logging system.
170 *
171 * @param key
172 * @return the string value identified by the <code>key</code> parameter.
173 * @throws IllegalArgumentException
174 * in case the "key" parameter is null
175 */
176 public static String get(String key) throws IllegalArgumentException {
177 if (key == null) {
178 throw new IllegalArgumentException("key parameter cannot be null");
179 }
180
181 if (mdcAdapter == null) {
182 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
183 }
184 return mdcAdapter.get(key);
185 }
186
187 /**
188 * Remove the diagnostic context identified by the <code>key</code> parameter using
189 * the underlying system's MDC implementation. The <code>key</code> parameter
190 * cannot be null. This method does nothing if there is no previous value
191 * associated with <code>key</code>.
192 *
193 * @param key
194 * @throws IllegalArgumentException
195 * in case the "key" parameter is null
196 */
197 public static void remove(String key) throws IllegalArgumentException {
198 if (key == null) {
199 throw new IllegalArgumentException("key parameter cannot be null");
200 }
201
202 if (mdcAdapter == null) {
203 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
204 }
205 mdcAdapter.remove(key);
206 }
207
208 /**
209 * Clear all entries in the MDC of the underlying implementation.
210 */
211 public static void clear() {
212 if (mdcAdapter == null) {
213 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
214 }
215 mdcAdapter.clear();
216 }
217
218 /**
219 * Return a copy of the current thread's context map, with keys and values of
220 * type String. Returned value may be null.
221 *
222 * @return A copy of the current thread's context map. May be null.
223 * @since 1.5.1
224 */
225 public static Map<String, String> getCopyOfContextMap() {
226 if (mdcAdapter == null) {
227 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
228 }
229 return mdcAdapter.getCopyOfContextMap();
230 }
231
232 /**
233 * Set the current thread's context map by first clearing any existing map and
234 * then copying the map passed as parameter. The context map passed as
235 * parameter must only contain keys and values of type String.
236 *
237 * @param contextMap
238 * must contain only keys and values of type String
239 * @since 1.5.1
240 */
241 public static void setContextMap(Map<String, String> contextMap) {
242 if (mdcAdapter == null) {
243 throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL);
244 }
245 mdcAdapter.setContextMap(contextMap);
246 }
247
248 /**
249 * Returns the MDCAdapter instance currently in use.
250 *
251 * @return the MDcAdapter instance currently in use.
252 * @since 1.4.2
253 */
254 public static MDCAdapter getMDCAdapter() {
255 return mdcAdapter;
256 }
257
258 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.Serializable;
27 import java.util.Iterator;
28
29 /**
30 * Markers are named objects used to enrich log statements. Conforming logging
31 * system Implementations of SLF4J determine how information conveyed by markers
32 * are used, if at all. In particular, many conforming logging systems ignore
33 * marker data.
34 *
35 * <p>
36 * Markers can contain references to other markers, which in turn may contain
37 * references of their own.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 */
41 public interface Marker extends Serializable {
42
43 /**
44 * This constant represents any marker, including a null marker.
45 */
46 public final String ANY_MARKER = "*";
47
48 /**
49 * This constant represents any non-null marker.
50 */
51 public final String ANY_NON_NULL_MARKER = "+";
52
53 /**
54 * Get the name of this Marker.
55 *
56 * @return name of marker
57 */
58 public String getName();
59
60 /**
61 * Add a reference to another Marker.
62 *
63 * @param reference
64 * a reference to another marker
65 * @throws IllegalArgumentException
66 * if 'reference' is null
67 */
68 public void add(Marker reference);
69
70 /**
71 * Remove a marker reference.
72 *
73 * @param reference
74 * the marker reference to remove
75 * @return true if reference could be found and removed, false otherwise.
76 */
77 public boolean remove(Marker reference);
78
79 /**
80 * @deprecated Replaced by {@link #hasReferences()}.
81 */
82 public boolean hasChildren();
83
84 /**
85 * Does this marker have any references?
86 *
87 * @return true if this marker has one or more references, false otherwise.
88 */
89 public boolean hasReferences();
90
91 /**
92 * Returns an Iterator which can be used to iterate over the references of this
93 * marker. An empty iterator is returned when this marker has no references.
94 *
95 * @return Iterator over the references of this marker
96 */
97 public Iterator<Marker> iterator();
98
99 /**
100 * Does this marker contain a reference to the 'other' marker? Marker A is defined
101 * to contain marker B, if A == B or if B is referenced by A, or if B is referenced
102 * by any one of A's references (recursively).
103 *
104 * @param other
105 * The marker to test for inclusion.
106 * @throws IllegalArgumentException
107 * if 'other' is null
108 * @return Whether this marker contains the other marker.
109 */
110 public boolean contains(Marker other);
111
112 /**
113 * Does this marker contain the marker named 'name'?
114 *
115 * If 'name' is null the returned value is always false.
116 *
117 * @param name The marker name to test for inclusion.
118 * @return Whether this marker contains the other marker.
119 */
120 public boolean contains(String name);
121
122 /**
123 * Markers are considered equal if they have the same name.
124 *
125 * @param o
126 * @return true, if this.name equals o.name
127 *
128 * @since 1.5.1
129 */
130 public boolean equals(Object o);
131
132 /**
133 * Compute the hash code based on the name of this marker.
134 * Note that markers are considered equal if they have the same name.
135 *
136 * @return the computed hashCode
137 * @since 1.5.1
138 */
139 public int hashCode();
140
141 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import org.slf4j.helpers.BasicMarkerFactory;
27 import org.slf4j.helpers.Util;
28 import org.slf4j.impl.StaticMarkerBinder;
29
30 /**
31 * MarkerFactory is a utility class producing {@link Marker} instances as
32 * appropriate for the logging system currently in use.
33 *
34 * <p>
35 * This class is essentially implemented as a wrapper around an
36 * {@link IMarkerFactory} instance bound at compile time.
37 *
38 * <p>
39 * Please note that all methods in this class are static.
40 *
41 * @author Ceki G&uuml;lc&uuml;
42 */
43 public class MarkerFactory {
44 static IMarkerFactory markerFactory;
45
46 private MarkerFactory() {
47 }
48
49 static {
50 try {
51 markerFactory = StaticMarkerBinder.SINGLETON.getMarkerFactory();
52 } catch (NoClassDefFoundError e) {
53 markerFactory = new BasicMarkerFactory();
54
55 } catch (Exception e) {
56 // we should never get here
57 Util.report("Unexpected failure while binding MarkerFactory", e);
58 }
59 }
60
61 /**
62 * Return a Marker instance as specified by the name parameter using the
63 * previously bound {@link IMarkerFactory}instance.
64 *
65 * @param name
66 * The name of the {@link Marker} object to return.
67 * @return marker
68 */
69 public static Marker getMarker(String name) {
70 return markerFactory.getMarker(name);
71 }
72
73 /**
74 * Create a marker which is detached (even at birth) from the MarkerFactory.
75 *
76 * @param name the name of the marker
77 * @return a dangling marker
78 * @since 1.5.1
79 */
80 public static Marker getDetachedMarker(String name) {
81 return markerFactory.getDetachedMarker(name);
82 }
83
84 /**
85 * Return the {@link IMarkerFactory}instance in use.
86 *
87 * <p>The IMarkerFactory instance is usually bound with this class at
88 * compile time.
89 *
90 * @return the IMarkerFactory instance in use
91 */
92 public static IMarkerFactory getIMarkerFactory() {
93 return markerFactory;
94 }
95 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.spi.MDCAdapter;
27
28 import java.util.*;
29 import java.util.Map;
30
31 /**
32 * Basic MDC implementation, which can be used with logging systems that lack
33 * out-of-the-box MDC support.
34 *
35 * This code was initially inspired by logback's LogbackMDCAdapter. However,
36 * LogbackMDCAdapter has evolved and is now considerably more sophisticated.
37 *
38 * @author Ceki Gulcu
39 * @author Maarten Bosteels
40 *
41 * @since 1.5.0
42 */
43 public class BasicMDCAdapter implements MDCAdapter {
44
45 private InheritableThreadLocal<Map<String, String>> inheritableThreadLocal = new InheritableThreadLocal<Map<String, String>>();
46
47 static boolean isJDK14() {
48 try {
49 String javaVersion = System.getProperty("java.version");
50 return javaVersion.startsWith("1.4");
51 } catch (SecurityException se) {
52 // punt and assume JDK 1.5 or later
53 return false;
54 }
55 }
56
57 static boolean IS_JDK14 = isJDK14();
58
59 /**
60 * Put a context value (the <code>val</code> parameter) as identified with
61 * the <code>key</code> parameter into the current thread's context map.
62 * Note that contrary to log4j, the <code>val</code> parameter can be null.
63 *
64 * <p>
65 * If the current thread does not have a context map it is created as a side
66 * effect of this call.
67 *
68 * @throws IllegalArgumentException
69 * in case the "key" parameter is null
70 */
71 public void put(String key, String val) {
72 if (key == null) {
73 throw new IllegalArgumentException("key cannot be null");
74 }
75 Map<String, String> map = (Map<String, String>) inheritableThreadLocal.get();
76 if (map == null) {
77 map = Collections.<String, String> synchronizedMap(new HashMap<String, String>());
78 inheritableThreadLocal.set(map);
79 }
80 map.put(key, val);
81 }
82
83 /**
84 * Get the context identified by the <code>key</code> parameter.
85 */
86 public String get(String key) {
87 Map<String, String> Map = (Map<String, String>) inheritableThreadLocal.get();
88 if ((Map != null) && (key != null)) {
89 return (String) Map.get(key);
90 } else {
91 return null;
92 }
93 }
94
95 /**
96 * Remove the the context identified by the <code>key</code> parameter.
97 */
98 public void remove(String key) {
99 Map<String, String> map = (Map<String, String>) inheritableThreadLocal.get();
100 if (map != null) {
101 map.remove(key);
102 }
103 }
104
105 /**
106 * Clear all entries in the MDC.
107 */
108 public void clear() {
109 Map<String, String> map = (Map<String, String>) inheritableThreadLocal.get();
110 if (map != null) {
111 map.clear();
112 // the InheritableThreadLocal.remove method was introduced in JDK 1.5
113 // Thus, invoking clear() on previous JDK 1.4 will fail
114 if (isJDK14()) {
115 inheritableThreadLocal.set(null);
116 } else {
117 inheritableThreadLocal.remove();
118 }
119 }
120 }
121
122 /**
123 * Returns the keys in the MDC as a {@link Set} of {@link String}s The
124 * returned value can be null.
125 *
126 * @return the keys in the MDC
127 */
128 public Set<String> getKeys() {
129 Map<String, String> map = (Map<String, String>) inheritableThreadLocal.get();
130 if (map != null) {
131 return map.keySet();
132 } else {
133 return null;
134 }
135 }
136
137 /**
138 * Return a copy of the current thread's context map.
139 * Returned value may be null.
140 *
141 */
142 public Map<String, String> getCopyOfContextMap() {
143 Map<String, String> oldMap = (Map<String, String>) inheritableThreadLocal.get();
144 if (oldMap != null) {
145 Map<String, String> newMap = Collections.<String, String> synchronizedMap(new HashMap<String, String>());
146 synchronized (oldMap) {
147 newMap.putAll(oldMap);
148 }
149 return newMap;
150 } else {
151 return null;
152 }
153 }
154
155 public void setContextMap(Map<String, String> contextMap) {
156 Map<String, String> map = Collections.<String, String> synchronizedMap(new HashMap<String, String>(contextMap));
157 inheritableThreadLocal.set(map);
158 }
159
160 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.Collections;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Vector;
30
31 import org.slf4j.Marker;
32
33 /**
34 * A simple implementation of the {@link Marker} interface.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 * @author Joern Huxhorn
38 */
39 public class BasicMarker implements Marker {
40
41 private static final long serialVersionUID = 1803952589649545191L;
42
43 private final String name;
44 private List<Marker> referenceList;
45
46 BasicMarker(String name) {
47 if (name == null) {
48 throw new IllegalArgumentException("A marker name cannot be null");
49 }
50 this.name = name;
51 }
52
53 public String getName() {
54 return name;
55 }
56
57 public synchronized void add(Marker reference) {
58 if (reference == null) {
59 throw new IllegalArgumentException("A null value cannot be added to a Marker as reference.");
60 }
61
62 // no point in adding the reference multiple times
63 if (this.contains(reference)) {
64 return;
65
66 } else if (reference.contains(this)) { // avoid recursion
67 // a potential reference should not its future "parent" as a reference
68 return;
69 } else {
70 // let's add the reference
71 if (referenceList == null) {
72 referenceList = new Vector<Marker>();
73 }
74 referenceList.add(reference);
75 }
76
77 }
78
79 public synchronized boolean hasReferences() {
80 return ((referenceList != null) && (referenceList.size() > 0));
81 }
82
83 public boolean hasChildren() {
84 return hasReferences();
85 }
86
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 }
94 }
95
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 = (Marker) referenceList.get(i);
104 if (referenceToRemove.equals(m)) {
105 referenceList.remove(i);
106 return true;
107 }
108 }
109 return false;
110 }
111
112 public boolean contains(Marker other) {
113 if (other == null) {
114 throw new IllegalArgumentException("Other cannot be null");
115 }
116
117 if (this.equals(other)) {
118 return true;
119 }
120
121 if (hasReferences()) {
122 for (int i = 0; i < referenceList.size(); i++) {
123 Marker ref = (Marker) referenceList.get(i);
124 if (ref.contains(other)) {
125 return true;
126 }
127 }
128 }
129 return false;
130 }
131
132 /**
133 * This method is mainly used with Expression Evaluators.
134 */
135 public boolean contains(String name) {
136 if (name == null) {
137 throw new IllegalArgumentException("Other cannot be null");
138 }
139
140 if (this.name.equals(name)) {
141 return true;
142 }
143
144 if (hasReferences()) {
145 for (int i = 0; i < referenceList.size(); i++) {
146 Marker ref = (Marker) referenceList.get(i);
147 if (ref.contains(name)) {
148 return true;
149 }
150 }
151 }
152 return false;
153 }
154
155 private static String OPEN = "[ ";
156 private static String CLOSE = " ]";
157 private static String SEP = ", ";
158
159 public boolean equals(Object obj) {
160 if (this == obj)
161 return true;
162 if (obj == null)
163 return false;
164 if (!(obj instanceof Marker))
165 return false;
166
167 final Marker other = (Marker) obj;
168 return name.equals(other.getName());
169 }
170
171 public int hashCode() {
172 return name.hashCode();
173 }
174
175 public String toString() {
176 if (!this.hasReferences()) {
177 return this.getName();
178 }
179 Iterator<Marker> it = this.iterator();
180 Marker reference;
181 StringBuilder sb = new StringBuilder(this.getName());
182 sb.append(' ').append(OPEN);
183 while (it.hasNext()) {
184 reference = (Marker) it.next();
185 sb.append(reference.getName());
186 if (it.hasNext()) {
187 sb.append(SEP);
188 }
189 }
190 sb.append(CLOSE);
191
192 return sb.toString();
193 }
194 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.slf4j.IMarkerFactory;
30 import org.slf4j.Marker;
31
32 /**
33 * An almost trivial implementation of the {@link IMarkerFactory}
34 * interface which creates {@link BasicMarker} instances.
35 *
36 * <p>Simple logging systems can conform to the SLF4J API by binding
37 * {@link org.slf4j.MarkerFactory} with an instance of this class.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 */
41 public class BasicMarkerFactory implements IMarkerFactory {
42
43 private final ConcurrentMap<String, Marker> markerMap = new ConcurrentHashMap<String, Marker>();
44
45 /**
46 * Regular users should <em>not</em> create
47 * <code>BasicMarkerFactory</code> instances. <code>Marker</code>
48 * instances can be obtained using the static {@link
49 * org.slf4j.MarkerFactory#getMarker} method.
50 */
51 public BasicMarkerFactory() {
52 }
53
54 /**
55 * Manufacture a {@link BasicMarker} instance by name. If the instance has been
56 * created earlier, return the previously created instance.
57 *
58 * @param name the name of the marker to be created
59 * @return a Marker instance
60 */
61 public Marker getMarker(String name) {
62 if (name == null) {
63 throw new IllegalArgumentException("Marker name cannot be null");
64 }
65
66 Marker marker = markerMap.get(name);
67 if (marker == null) {
68 marker = new BasicMarker(name);
69 Marker oldMarker = markerMap.putIfAbsent(name, marker);
70 if (oldMarker != null) {
71 marker = oldMarker;
72 }
73 }
74 return marker;
75 }
76
77 /**
78 * Does the name marked already exist?
79 */
80 public boolean exists(String name) {
81 if (name == null) {
82 return false;
83 }
84 return markerMap.containsKey(name);
85 }
86
87 public boolean detachMarker(String name) {
88 if (name == null) {
89 return false;
90 }
91 return (markerMap.remove(name) != null);
92 }
93
94 public Marker getDetachedMarker(String name) {
95 return new BasicMarker(name);
96 }
97
98 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 /**
27 * Holds the results of formatting done by {@link MessageFormatter}.
28 *
29 * @author Joern Huxhorn
30 */
31 public class FormattingTuple {
32
33 static public FormattingTuple NULL = new FormattingTuple(null);
34
35 private String message;
36 private Throwable throwable;
37 private Object[] argArray;
38
39 public FormattingTuple(String message) {
40 this(message, null, null);
41 }
42
43 public FormattingTuple(String message, Object[] argArray, Throwable throwable) {
44 this.message = message;
45 this.throwable = throwable;
46 if (throwable == null) {
47 this.argArray = argArray;
48 } else {
49 this.argArray = trimmedCopy(argArray);
50 }
51 }
52
53 static Object[] trimmedCopy(Object[] argArray) {
54 if (argArray == null || argArray.length == 0) {
55 throw new IllegalStateException("non-sensical empty or null argument array");
56 }
57 final int trimemdLen = argArray.length - 1;
58 Object[] trimmed = new Object[trimemdLen];
59 System.arraycopy(argArray, 0, trimmed, 0, trimemdLen);
60 return trimmed;
61 }
62
63 public String getMessage() {
64 return message;
65 }
66
67 public Object[] getArgArray() {
68 return argArray;
69 }
70
71 public Throwable getThrowable() {
72 return throwable;
73 }
74
75 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28
29 /**
30 * This class serves as base for adapters or native implementations of logging systems
31 * lacking Marker support. In this implementation, methods taking marker data
32 * simply invoke the corresponding method without the Marker argument, discarding
33 * any marker data passed as argument.
34 *
35 * @author Ceki Gulcu
36 */
37 public abstract class MarkerIgnoringBase extends NamedLoggerBase implements Logger {
38
39 private static final long serialVersionUID = 9044267456635152283L;
40
41 public boolean isTraceEnabled(Marker marker) {
42 return isTraceEnabled();
43 }
44
45 public void trace(Marker marker, String msg) {
46 trace(msg);
47 }
48
49 public void trace(Marker marker, String format, Object arg) {
50 trace(format, arg);
51 }
52
53 public void trace(Marker marker, String format, Object arg1, Object arg2) {
54 trace(format, arg1, arg2);
55 }
56
57 public void trace(Marker marker, String format, Object... arguments) {
58 trace(format, arguments);
59 }
60
61 public void trace(Marker marker, String msg, Throwable t) {
62 trace(msg, t);
63 }
64
65 public boolean isDebugEnabled(Marker marker) {
66 return isDebugEnabled();
67 }
68
69 public void debug(Marker marker, String msg) {
70 debug(msg);
71 }
72
73 public void debug(Marker marker, String format, Object arg) {
74 debug(format, arg);
75 }
76
77 public void debug(Marker marker, String format, Object arg1, Object arg2) {
78 debug(format, arg1, arg2);
79 }
80
81 public void debug(Marker marker, String format, Object... arguments) {
82 debug(format, arguments);
83 }
84
85 public void debug(Marker marker, String msg, Throwable t) {
86 debug(msg, t);
87 }
88
89 public boolean isInfoEnabled(Marker marker) {
90 return isInfoEnabled();
91 }
92
93 public void info(Marker marker, String msg) {
94 info(msg);
95 }
96
97 public void info(Marker marker, String format, Object arg) {
98 info(format, arg);
99 }
100
101 public void info(Marker marker, String format, Object arg1, Object arg2) {
102 info(format, arg1, arg2);
103 }
104
105 public void info(Marker marker, String format, Object... arguments) {
106 info(format, arguments);
107 }
108
109 public void info(Marker marker, String msg, Throwable t) {
110 info(msg, t);
111 }
112
113 public boolean isWarnEnabled(Marker marker) {
114 return isWarnEnabled();
115 }
116
117 public void warn(Marker marker, String msg) {
118 warn(msg);
119 }
120
121 public void warn(Marker marker, String format, Object arg) {
122 warn(format, arg);
123 }
124
125 public void warn(Marker marker, String format, Object arg1, Object arg2) {
126 warn(format, arg1, arg2);
127 }
128
129 public void warn(Marker marker, String format, Object... arguments) {
130 warn(format, arguments);
131 }
132
133 public void warn(Marker marker, String msg, Throwable t) {
134 warn(msg, t);
135 }
136
137 public boolean isErrorEnabled(Marker marker) {
138 return isErrorEnabled();
139 }
140
141 public void error(Marker marker, String msg) {
142 error(msg);
143 }
144
145 public void error(Marker marker, String format, Object arg) {
146 error(format, arg);
147 }
148
149 public void error(Marker marker, String format, Object arg1, Object arg2) {
150 error(format, arg1, arg2);
151 }
152
153 public void error(Marker marker, String format, Object... arguments) {
154 error(format, arguments);
155 }
156
157 public void error(Marker marker, String msg, Throwable t) {
158 error(msg, t);
159 }
160
161 public String toString() {
162 return this.getClass().getName() + "(" + getName() + ")";
163 }
164
165 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.text.MessageFormat;
27 import java.util.HashMap;
28 import java.util.Map;
29
30 // contributors: lizongbo: proposed special treatment of array parameter values
31 // Joern Huxhorn: pointed out double[] omission, suggested deep array copy
32 /**
33 * Formats messages according to very simple substitution rules. Substitutions
34 * can be made 1, 2 or more arguments.
35 *
36 * <p>
37 * For example,
38 *
39 * <pre>
40 * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;)
41 * </pre>
42 *
43 * will return the string "Hi there.".
44 * <p>
45 * The {} pair is called the <em>formatting anchor</em>. It serves to designate
46 * the location where arguments need to be substituted within the message
47 * pattern.
48 * <p>
49 * In case your message contains the '{' or the '}' character, you do not have
50 * to do anything special unless the '}' character immediately follows '{'. For
51 * example,
52 *
53 * <pre>
54 * MessageFormatter.format(&quot;Set {1,2,3} is not equal to {}.&quot;, &quot;1,2&quot;);
55 * </pre>
56 *
57 * will return the string "Set {1,2,3} is not equal to 1,2.".
58 *
59 * <p>
60 * If for whatever reason you need to place the string "{}" in the message
61 * without its <em>formatting anchor</em> meaning, then you need to escape the
62 * '{' character with '\', that is the backslash character. Only the '{'
63 * character should be escaped. There is no need to escape the '}' character.
64 * For example,
65 *
66 * <pre>
67 * MessageFormatter.format(&quot;Set \\{} is not equal to {}.&quot;, &quot;1,2&quot;);
68 * </pre>
69 *
70 * will return the string "Set {} is not equal to 1,2.".
71 *
72 * <p>
73 * The escaping behavior just described can be overridden by escaping the escape
74 * character '\'. Calling
75 *
76 * <pre>
77 * MessageFormatter.format(&quot;File name is C:\\\\{}.&quot;, &quot;file.zip&quot;);
78 * </pre>
79 *
80 * will return the string "File name is C:\file.zip".
81 *
82 * <p>
83 * The formatting conventions are different than those of {@link MessageFormat}
84 * which ships with the Java platform. This is justified by the fact that
85 * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}.
86 * This local performance difference is both measurable and significant in the
87 * larger context of the complete logging processing chain.
88 *
89 * <p>
90 * See also {@link #format(String, Object)},
91 * {@link #format(String, Object, Object)} and
92 * {@link #arrayFormat(String, Object[])} methods for more details.
93 *
94 * @author Ceki G&uuml;lc&uuml;
95 * @author Joern Huxhorn
96 */
97 final public class MessageFormatter {
98 static final char DELIM_START = '{';
99 static final char DELIM_STOP = '}';
100 static final String DELIM_STR = "{}";
101 private static final char ESCAPE_CHAR = '\\';
102
103 /**
104 * Performs single argument substitution for the 'messagePattern' passed as
105 * parameter.
106 * <p>
107 * For example,
108 *
109 * <pre>
110 * MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;);
111 * </pre>
112 *
113 * will return the string "Hi there.".
114 * <p>
115 *
116 * @param messagePattern
117 * The message pattern which will be parsed and formatted
118 * @param argument
119 * The argument to be substituted in place of the formatting anchor
120 * @return The formatted message
121 */
122 final public static FormattingTuple format(String messagePattern, Object arg) {
123 return arrayFormat(messagePattern, new Object[] { arg });
124 }
125
126 /**
127 *
128 * Performs a two argument substitution for the 'messagePattern' passed as
129 * parameter.
130 * <p>
131 * For example,
132 *
133 * <pre>
134 * MessageFormatter.format(&quot;Hi {}. My name is {}.&quot;, &quot;Alice&quot;, &quot;Bob&quot;);
135 * </pre>
136 *
137 * will return the string "Hi Alice. My name is Bob.".
138 *
139 * @param messagePattern
140 * The message pattern which will be parsed and formatted
141 * @param arg1
142 * The argument to be substituted in place of the first formatting
143 * anchor
144 * @param arg2
145 * The argument to be substituted in place of the second formatting
146 * anchor
147 * @return The formatted message
148 */
149 final public static FormattingTuple format(final String messagePattern, Object arg1, Object arg2) {
150 return arrayFormat(messagePattern, new Object[] { arg1, arg2 });
151 }
152
153 static final Throwable getThrowableCandidate(Object[] argArray) {
154 if (argArray == null || argArray.length == 0) {
155 return null;
156 }
157
158 final Object lastEntry = argArray[argArray.length - 1];
159 if (lastEntry instanceof Throwable) {
160 return (Throwable) lastEntry;
161 }
162 return null;
163 }
164
165 /**
166 * Same principle as the {@link #format(String, Object)} and
167 * {@link #format(String, Object, Object)} methods except that any number of
168 * arguments can be passed in an array.
169 *
170 * @param messagePattern
171 * The message pattern which will be parsed and formatted
172 * @param argArray
173 * An array of arguments to be substituted in place of formatting
174 * anchors
175 * @return The formatted message
176 */
177 final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) {
178
179 Throwable throwableCandidate = getThrowableCandidate(argArray);
180
181 if (messagePattern == null) {
182 return new FormattingTuple(null, argArray, throwableCandidate);
183 }
184
185 if (argArray == null) {
186 return new FormattingTuple(messagePattern);
187 }
188
189 int i = 0;
190 int j;
191 // use string builder for better multicore performance
192 StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50);
193
194 int L;
195 for (L = 0; L < argArray.length; L++) {
196
197 j = messagePattern.indexOf(DELIM_STR, i);
198
199 if (j == -1) {
200 // no more variables
201 if (i == 0) { // this is a simple string
202 return new FormattingTuple(messagePattern, argArray, throwableCandidate);
203 } else { // add the tail string which contains no variables and return
204 // the result.
205 sbuf.append(messagePattern.substring(i, messagePattern.length()));
206 return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate);
207 }
208 } else {
209 if (isEscapedDelimeter(messagePattern, j)) {
210 if (!isDoubleEscaped(messagePattern, j)) {
211 L--; // DELIM_START was escaped, thus should not be incremented
212 sbuf.append(messagePattern.substring(i, j - 1));
213 sbuf.append(DELIM_START);
214 i = j + 1;
215 } else {
216 // The escape character preceding the delimiter start is
217 // itself escaped: "abc x:\\{}"
218 // we have to consume one backward slash
219 sbuf.append(messagePattern.substring(i, j - 1));
220 deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
221 i = j + 2;
222 }
223 } else {
224 // normal case
225 sbuf.append(messagePattern.substring(i, j));
226 deeplyAppendParameter(sbuf, argArray[L], new HashMap<Object[], Object>());
227 i = j + 2;
228 }
229 }
230 }
231 // append the characters following the last {} pair.
232 sbuf.append(messagePattern.substring(i, messagePattern.length()));
233 if (L < argArray.length - 1) {
234 return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate);
235 } else {
236 return new FormattingTuple(sbuf.toString(), argArray, null);
237 }
238 }
239
240 final static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) {
241
242 if (delimeterStartIndex == 0) {
243 return false;
244 }
245 char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1);
246 if (potentialEscape == ESCAPE_CHAR) {
247 return true;
248 } else {
249 return false;
250 }
251 }
252
253 final static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) {
254 if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) {
255 return true;
256 } else {
257 return false;
258 }
259 }
260
261 // special treatment of array values was suggested by 'lizongbo'
262 private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map<Object[], Object> seenMap) {
263 if (o == null) {
264 sbuf.append("null");
265 return;
266 }
267 if (!o.getClass().isArray()) {
268 safeObjectAppend(sbuf, o);
269 } else {
270 // check for primitive array types because they
271 // unfortunately cannot be cast to Object[]
272 if (o instanceof boolean[]) {
273 booleanArrayAppend(sbuf, (boolean[]) o);
274 } else if (o instanceof byte[]) {
275 byteArrayAppend(sbuf, (byte[]) o);
276 } else if (o instanceof char[]) {
277 charArrayAppend(sbuf, (char[]) o);
278 } else if (o instanceof short[]) {
279 shortArrayAppend(sbuf, (short[]) o);
280 } else if (o instanceof int[]) {
281 intArrayAppend(sbuf, (int[]) o);
282 } else if (o instanceof long[]) {
283 longArrayAppend(sbuf, (long[]) o);
284 } else if (o instanceof float[]) {
285 floatArrayAppend(sbuf, (float[]) o);
286 } else if (o instanceof double[]) {
287 doubleArrayAppend(sbuf, (double[]) o);
288 } else {
289 objectArrayAppend(sbuf, (Object[]) o, seenMap);
290 }
291 }
292 }
293
294 private static void safeObjectAppend(StringBuilder sbuf, Object o) {
295 try {
296 String oAsString = o.toString();
297 sbuf.append(oAsString);
298 } catch (Throwable t) {
299 System.err.println("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]");
300 t.printStackTrace();
301 sbuf.append("[FAILED toString()]");
302 }
303
304 }
305
306 private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map<Object[], Object> seenMap) {
307 sbuf.append('[');
308 if (!seenMap.containsKey(a)) {
309 seenMap.put(a, null);
310 final int len = a.length;
311 for (int i = 0; i < len; i++) {
312 deeplyAppendParameter(sbuf, a[i], seenMap);
313 if (i != len - 1)
314 sbuf.append(", ");
315 }
316 // allow repeats in siblings
317 seenMap.remove(a);
318 } else {
319 sbuf.append("...");
320 }
321 sbuf.append(']');
322 }
323
324 private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) {
325 sbuf.append('[');
326 final int len = a.length;
327 for (int i = 0; i < len; i++) {
328 sbuf.append(a[i]);
329 if (i != len - 1)
330 sbuf.append(", ");
331 }
332 sbuf.append(']');
333 }
334
335 private static void byteArrayAppend(StringBuilder sbuf, byte[] a) {
336 sbuf.append('[');
337 final int len = a.length;
338 for (int i = 0; i < len; i++) {
339 sbuf.append(a[i]);
340 if (i != len - 1)
341 sbuf.append(", ");
342 }
343 sbuf.append(']');
344 }
345
346 private static void charArrayAppend(StringBuilder sbuf, char[] a) {
347 sbuf.append('[');
348 final int len = a.length;
349 for (int i = 0; i < len; i++) {
350 sbuf.append(a[i]);
351 if (i != len - 1)
352 sbuf.append(", ");
353 }
354 sbuf.append(']');
355 }
356
357 private static void shortArrayAppend(StringBuilder sbuf, short[] a) {
358 sbuf.append('[');
359 final int len = a.length;
360 for (int i = 0; i < len; i++) {
361 sbuf.append(a[i]);
362 if (i != len - 1)
363 sbuf.append(", ");
364 }
365 sbuf.append(']');
366 }
367
368 private static void intArrayAppend(StringBuilder sbuf, int[] a) {
369 sbuf.append('[');
370 final int len = a.length;
371 for (int i = 0; i < len; i++) {
372 sbuf.append(a[i]);
373 if (i != len - 1)
374 sbuf.append(", ");
375 }
376 sbuf.append(']');
377 }
378
379 private static void longArrayAppend(StringBuilder sbuf, long[] a) {
380 sbuf.append('[');
381 final int len = a.length;
382 for (int i = 0; i < len; i++) {
383 sbuf.append(a[i]);
384 if (i != len - 1)
385 sbuf.append(", ");
386 }
387 sbuf.append(']');
388 }
389
390 private static void floatArrayAppend(StringBuilder sbuf, float[] a) {
391 sbuf.append('[');
392 final int len = a.length;
393 for (int i = 0; i < len; i++) {
394 sbuf.append(a[i]);
395 if (i != len - 1)
396 sbuf.append(", ");
397 }
398 sbuf.append(']');
399 }
400
401 private static void doubleArrayAppend(StringBuilder sbuf, double[] a) {
402 sbuf.append('[');
403 final int len = a.length;
404 for (int i = 0; i < len; i++) {
405 sbuf.append(a[i]);
406 if (i != len - 1)
407 sbuf.append(", ");
408 }
409 sbuf.append(']');
410 }
411 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.Logger;
27 import org.slf4j.helpers.MarkerIgnoringBase;
28
29 /**
30 * A direct NOP (no operation) implementation of {@link Logger}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class NOPLogger extends MarkerIgnoringBase {
35
36 private static final long serialVersionUID = -517220405410904473L;
37
38 /**
39 * The unique instance of NOPLogger.
40 */
41 public static final NOPLogger NOP_LOGGER = new NOPLogger();
42
43 /**
44 * There is no point in creating multiple instances of NOPLOgger,
45 * except by derived classes, hence the protected access for the constructor.
46 */
47 protected NOPLogger() {
48 }
49
50 /**
51 * Always returns the string value "NOP".
52 */
53 public String getName() {
54 return "NOP";
55 }
56
57 /**
58 * Always returns false.
59 * @return always false
60 */
61 final public boolean isTraceEnabled() {
62 return false;
63 }
64
65 /** A NOP implementation. */
66 final public void trace(String msg) {
67 // NOP
68 }
69
70 /** A NOP implementation. */
71 final public void trace(String format, Object arg) {
72 // NOP
73 }
74
75 /** A NOP implementation. */
76 public final void trace(String format, Object arg1, Object arg2) {
77 // NOP
78 }
79
80 /** A NOP implementation. */
81 public final void trace(String format, Object... argArray) {
82 // NOP
83 }
84
85 /** A NOP implementation. */
86 final public void trace(String msg, Throwable t) {
87 // NOP
88 }
89
90 /**
91 * Always returns false.
92 * @return always false
93 */
94 final public boolean isDebugEnabled() {
95 return false;
96 }
97
98 /** A NOP implementation. */
99 final public void debug(String msg) {
100 // NOP
101 }
102
103 /** A NOP implementation. */
104 final public void debug(String format, Object arg) {
105 // NOP
106 }
107
108 /** A NOP implementation. */
109 public final void debug(String format, Object arg1, Object arg2) {
110 // NOP
111 }
112
113 /** A NOP implementation. */
114 public final void debug(String format, Object... argArray) {
115 // NOP
116 }
117
118 /** A NOP implementation. */
119 final public void debug(String msg, Throwable t) {
120 // NOP
121 }
122
123 /**
124 * Always returns false.
125 * @return always false
126 */
127 final public boolean isInfoEnabled() {
128 // NOP
129 return false;
130 }
131
132 /** A NOP implementation. */
133 final public void info(String msg) {
134 // NOP
135 }
136
137 /** A NOP implementation. */
138 final public void info(String format, Object arg1) {
139 // NOP
140 }
141
142 /** A NOP implementation. */
143 final public void info(String format, Object arg1, Object arg2) {
144 // NOP
145 }
146
147 /** A NOP implementation. */
148 public final void info(String format, Object... argArray) {
149 // NOP
150 }
151
152 /** A NOP implementation. */
153 final public void info(String msg, Throwable t) {
154 // NOP
155 }
156
157 /**
158 * Always returns false.
159 * @return always false
160 */
161 final public boolean isWarnEnabled() {
162 return false;
163 }
164
165 /** A NOP implementation. */
166 final public void warn(String msg) {
167 // NOP
168 }
169
170 /** A NOP implementation. */
171 final public void warn(String format, Object arg1) {
172 // NOP
173 }
174
175 /** A NOP implementation. */
176 final public void warn(String format, Object arg1, Object arg2) {
177 // NOP
178 }
179
180 /** A NOP implementation. */
181 public final void warn(String format, Object... argArray) {
182 // NOP
183 }
184
185 /** A NOP implementation. */
186 final public void warn(String msg, Throwable t) {
187 // NOP
188 }
189
190 /** A NOP implementation. */
191 final public boolean isErrorEnabled() {
192 return false;
193 }
194
195 /** A NOP implementation. */
196 final public void error(String msg) {
197 // NOP
198 }
199
200 /** A NOP implementation. */
201 final public void error(String format, Object arg1) {
202 // NOP
203 }
204
205 /** A NOP implementation. */
206 final public void error(String format, Object arg1, Object arg2) {
207 // NOP
208 }
209
210 /** A NOP implementation. */
211 public final void error(String format, Object... argArray) {
212 // NOP
213 }
214
215 /** A NOP implementation. */
216 final public void error(String msg, Throwable t) {
217 // NOP
218 }
219 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.Logger;
28 import org.slf4j.helpers.NOPLogger;
29
30 /**
31 * NOPLoggerFactory is an trivial implementation of {@link
32 * ILoggerFactory} which always returns the unique instance of
33 * NOPLogger.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public class NOPLoggerFactory implements ILoggerFactory {
38
39 public NOPLoggerFactory() {
40 // nothing to do
41 }
42
43 public Logger getLogger(String name) {
44 return NOPLogger.NOP_LOGGER;
45 }
46
47 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.Map;
27
28 import org.slf4j.spi.MDCAdapter;
29
30 /**
31 * This adapter is an empty implementation of the {@link MDCAdapter} interface.
32 * It is used for all logging systems which do not support mapped
33 * diagnostic contexts such as JDK14, simple and NOP.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 *
37 * @since 1.4.1
38 */
39 public class NOPMDCAdapter implements MDCAdapter {
40
41 public void clear() {
42 }
43
44 public String get(String key) {
45 return null;
46 }
47
48 public void put(String key, String val) {
49 }
50
51 public void remove(String key) {
52 }
53
54 public Map<String, String> getCopyOfContextMap() {
55 return null;
56 }
57
58 public void setContextMap(Map<String, String> contextMap) {
59 // NOP
60 }
61
62 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.io.ObjectStreamException;
27 import java.io.Serializable;
28
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33 * Serves as base class for named logger implementation. More significantly, this
34 * class establishes deserialization behavior. See @see #readResolve.
35 *
36 * @author Ceki Gulcu
37 * @since 1.5.3
38 */
39 abstract class NamedLoggerBase implements Logger, Serializable {
40
41 private static final long serialVersionUID = 7535258609338176893L;
42
43 protected String name;
44
45 public String getName() {
46 return name;
47 }
48
49 /**
50 * Replace this instance with a homonymous (same name) logger returned
51 * by LoggerFactory. Note that this method is only called during
52 * deserialization.
53 *
54 * <p>
55 * This approach will work well if the desired ILoggerFactory is the one
56 * references by LoggerFactory. However, if the user manages its logger hierarchy
57 * through a different (non-static) mechanism, e.g. dependency injection, then
58 * this approach would be mostly counterproductive.
59 *
60 * @return logger with same name as returned by LoggerFactory
61 * @throws ObjectStreamException
62 */
63 protected Object readResolve() throws ObjectStreamException {
64 // using getName() instead of this.name works even for
65 // NOPLogger
66 return LoggerFactory.getLogger(getName());
67 }
68
69 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28
29 /**
30 * A logger implementation which logs via a delegate logger. By default, the delegate is a
31 * {@link NOPLogger}. However, a different delegate can be set at anytime.
32 * <p/>
33 * See also the <a href="http://www.slf4j.org/codes.html#substituteLogger">relevant
34 * error code</a> documentation.
35 *
36 * @author Chetan Mehrotra
37 */
38 public class SubstituteLogger implements Logger {
39
40 private final String name;
41
42 private volatile Logger _delegate;
43
44 public SubstituteLogger(String name) {
45 this.name = name;
46 }
47
48 public String getName() {
49 return name;
50 }
51
52 public boolean isTraceEnabled() {
53 return delegate().isTraceEnabled();
54 }
55
56 public void trace(String msg) {
57 delegate().trace(msg);
58 }
59
60 public void trace(String format, Object arg) {
61 delegate().trace(format, arg);
62 }
63
64 public void trace(String format, Object arg1, Object arg2) {
65 delegate().trace(format, arg1, arg2);
66 }
67
68 public void trace(String format, Object... arguments) {
69 delegate().trace(format, arguments);
70 }
71
72 public void trace(String msg, Throwable t) {
73 delegate().trace(msg, t);
74 }
75
76 public boolean isTraceEnabled(Marker marker) {
77 return delegate().isTraceEnabled(marker);
78 }
79
80 public void trace(Marker marker, String msg) {
81 delegate().trace(marker, msg);
82 }
83
84 public void trace(Marker marker, String format, Object arg) {
85 delegate().trace(marker, format, arg);
86 }
87
88 public void trace(Marker marker, String format, Object arg1, Object arg2) {
89 delegate().trace(marker, format, arg1, arg2);
90 }
91
92 public void trace(Marker marker, String format, Object... arguments) {
93 delegate().trace(marker, format, arguments);
94 }
95
96 public void trace(Marker marker, String msg, Throwable t) {
97 delegate().trace(marker, msg, t);
98 }
99
100 public boolean isDebugEnabled() {
101 return delegate().isDebugEnabled();
102 }
103
104 public void debug(String msg) {
105 delegate().debug(msg);
106 }
107
108 public void debug(String format, Object arg) {
109 delegate().debug(format, arg);
110 }
111
112 public void debug(String format, Object arg1, Object arg2) {
113 delegate().debug(format, arg1, arg2);
114 }
115
116 public void debug(String format, Object... arguments) {
117 delegate().debug(format, arguments);
118 }
119
120 public void debug(String msg, Throwable t) {
121 delegate().debug(msg, t);
122 }
123
124 public boolean isDebugEnabled(Marker marker) {
125 return delegate().isDebugEnabled(marker);
126 }
127
128 public void debug(Marker marker, String msg) {
129 delegate().debug(marker, msg);
130 }
131
132 public void debug(Marker marker, String format, Object arg) {
133 delegate().debug(marker, format, arg);
134 }
135
136 public void debug(Marker marker, String format, Object arg1, Object arg2) {
137 delegate().debug(marker, format, arg1, arg2);
138 }
139
140 public void debug(Marker marker, String format, Object... arguments) {
141 delegate().debug(marker, format, arguments);
142 }
143
144 public void debug(Marker marker, String msg, Throwable t) {
145 delegate().debug(marker, msg, t);
146 }
147
148 public boolean isInfoEnabled() {
149 return delegate().isInfoEnabled();
150 }
151
152 public void info(String msg) {
153 delegate().info(msg);
154 }
155
156 public void info(String format, Object arg) {
157 delegate().info(format, arg);
158 }
159
160 public void info(String format, Object arg1, Object arg2) {
161 delegate().info(format, arg1, arg2);
162 }
163
164 public void info(String format, Object... arguments) {
165 delegate().info(format, arguments);
166 }
167
168 public void info(String msg, Throwable t) {
169 delegate().info(msg, t);
170 }
171
172 public boolean isInfoEnabled(Marker marker) {
173 return delegate().isInfoEnabled(marker);
174 }
175
176 public void info(Marker marker, String msg) {
177 delegate().info(marker, msg);
178 }
179
180 public void info(Marker marker, String format, Object arg) {
181 delegate().info(marker, format, arg);
182 }
183
184 public void info(Marker marker, String format, Object arg1, Object arg2) {
185 delegate().info(marker, format, arg1, arg2);
186 }
187
188 public void info(Marker marker, String format, Object... arguments) {
189 delegate().info(marker, format, arguments);
190 }
191
192 public void info(Marker marker, String msg, Throwable t) {
193 delegate().info(marker, msg, t);
194 }
195
196 public boolean isWarnEnabled() {
197 return delegate().isWarnEnabled();
198 }
199
200 public void warn(String msg) {
201 delegate().warn(msg);
202 }
203
204 public void warn(String format, Object arg) {
205 delegate().warn(format, arg);
206 }
207
208 public void warn(String format, Object arg1, Object arg2) {
209 delegate().warn(format, arg1, arg2);
210 }
211
212 public void warn(String format, Object... arguments) {
213 delegate().warn(format, arguments);
214 }
215
216 public void warn(String msg, Throwable t) {
217 delegate().warn(msg, t);
218 }
219
220 public boolean isWarnEnabled(Marker marker) {
221 return delegate().isWarnEnabled(marker);
222 }
223
224 public void warn(Marker marker, String msg) {
225 delegate().warn(marker, msg);
226 }
227
228 public void warn(Marker marker, String format, Object arg) {
229 delegate().warn(marker, format, arg);
230 }
231
232 public void warn(Marker marker, String format, Object arg1, Object arg2) {
233 delegate().warn(marker, format, arg1, arg2);
234 }
235
236 public void warn(Marker marker, String format, Object... arguments) {
237 delegate().warn(marker, format, arguments);
238 }
239
240 public void warn(Marker marker, String msg, Throwable t) {
241 delegate().warn(marker, msg, t);
242 }
243
244 public boolean isErrorEnabled() {
245 return delegate().isErrorEnabled();
246 }
247
248 public void error(String msg) {
249 delegate().error(msg);
250 }
251
252 public void error(String format, Object arg) {
253 delegate().error(format, arg);
254 }
255
256 public void error(String format, Object arg1, Object arg2) {
257 delegate().error(format, arg1, arg2);
258 }
259
260 public void error(String format, Object... arguments) {
261 delegate().error(format, arguments);
262 }
263
264 public void error(String msg, Throwable t) {
265 delegate().error(msg, t);
266 }
267
268 public boolean isErrorEnabled(Marker marker) {
269 return delegate().isErrorEnabled(marker);
270 }
271
272 public void error(Marker marker, String msg) {
273 delegate().error(marker, msg);
274 }
275
276 public void error(Marker marker, String format, Object arg) {
277 delegate().error(marker, format, arg);
278 }
279
280 public void error(Marker marker, String format, Object arg1, Object arg2) {
281 delegate().error(marker, format, arg1, arg2);
282 }
283
284 public void error(Marker marker, String format, Object... arguments) {
285 delegate().error(marker, format, arguments);
286 }
287
288 public void error(Marker marker, String msg, Throwable t) {
289 delegate().error(marker, msg, t);
290 }
291
292 @Override
293 public boolean equals(Object o) {
294 if (this == o)
295 return true;
296 if (o == null || getClass() != o.getClass())
297 return false;
298
299 SubstituteLogger that = (SubstituteLogger) o;
300
301 if (!name.equals(that.name))
302 return false;
303
304 return true;
305 }
306
307 @Override
308 public int hashCode() {
309 return name.hashCode();
310 }
311
312 /**
313 * Return the delegate logger instance if set. Otherwise, return a {@link NOPLogger}
314 * instance.
315 */
316 Logger delegate() {
317 return _delegate != null ? _delegate : NOPLogger.NOP_LOGGER;
318 }
319
320 /**
321 * Typically called after the {@link org.slf4j.LoggerFactory} initialization phase is completed.
322 * @param delegate
323 */
324 public void setDelegate(Logger delegate) {
325 this._delegate = delegate;
326 }
327 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.Logger;
28
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.ConcurrentMap;
33
34 /**
35 * SubstituteLoggerFactory manages instances of {@link SubstituteLogger}.
36 *
37 * @author Ceki G&uuml;lc&uuml;
38 * @author Chetan Mehrotra
39 */
40 public class SubstituteLoggerFactory implements ILoggerFactory {
41
42 final ConcurrentMap<String, SubstituteLogger> loggers = new ConcurrentHashMap<String, SubstituteLogger>();
43
44 public Logger getLogger(String name) {
45 SubstituteLogger logger = loggers.get(name);
46 if (logger == null) {
47 logger = new SubstituteLogger(name);
48 SubstituteLogger oldLogger = loggers.putIfAbsent(name, logger);
49 if (oldLogger != null)
50 logger = oldLogger;
51 }
52 return logger;
53 }
54
55 public List<String> getLoggerNames() {
56 return new ArrayList<String>(loggers.keySet());
57 }
58
59 public List<SubstituteLogger> getLoggers() {
60 return new ArrayList<SubstituteLogger>(loggers.values());
61 }
62
63 public void clear() {
64 loggers.clear();
65 }
66 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 /**
27 * An internal utility class.
28 *
29 * @author Alexander Dorokhine
30 * @author Ceki G&uuml;lc&uuml;
31 */
32 public final class Util {
33
34 private Util() {
35 }
36
37 /**
38 * In order to call {@link SecurityManager#getClassContext()}, which is a
39 * protected method, we add this wrapper which allows the method to be visible
40 * inside this package.
41 */
42 private static final class ClassContextSecurityManager extends SecurityManager {
43 protected Class<?>[] getClassContext() {
44 return super.getClassContext();
45 }
46 }
47
48 private static final ClassContextSecurityManager SECURITY_MANAGER = new ClassContextSecurityManager();
49
50 /**
51 * Returns the name of the class which called the invoking method.
52 *
53 * @return the name of the class which called the invoking method.
54 */
55 public static Class<?> getCallingClass() {
56 Class<?>[] trace = SECURITY_MANAGER.getClassContext();
57 String thisClassName = Util.class.getName();
58
59 // Advance until Util is found
60 int i;
61 for (i = 0; i < trace.length; i++) {
62 if (thisClassName.equals(trace[i].getName()))
63 break;
64 }
65
66 // trace[i] = Util; trace[i+1] = caller; trace[i+2] = caller's caller
67 if (i >= trace.length || i + 2 >= trace.length) {
68 throw new IllegalStateException("Failed to find org.slf4j.helpers.Util or its caller in the stack; " + "this should not happen");
69 }
70
71 return trace[i + 2];
72 }
73
74 static final public void report(String msg, Throwable t) {
75 System.err.println(msg);
76 System.err.println("Reported exception:");
77 t.printStackTrace();
78 }
79
80 static final public void report(String msg) {
81 System.err.println("SLF4J: " + msg);
82 }
83 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>Helper classes.</p>
12
13 <hr/>
14 </body>
15 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27
28 /**
29 * The binding of {@link LoggerFactory} class with an actual instance of
30 * {@link ILoggerFactory} is performed using information returned by this class.
31 *
32 * This class is meant to provide a dummy StaticLoggerBinder to the slf4j-api module.
33 * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop,
34 * slf4j-log4j12 etc.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticLoggerBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticLoggerBinder singleton
49 */
50 public static final StaticLoggerBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Declare the version of the SLF4J API this implementation is compiled against.
56 * The value of this field is usually modified with each release.
57 */
58 // to avoid constant folding by the compiler, this field must *not* be final
59 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
60
61 private StaticLoggerBinder() {
62 throw new UnsupportedOperationException("This code should have never made it into slf4j-api.jar");
63 }
64
65 public ILoggerFactory getLoggerFactory() {
66 throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar");
67 }
68
69 public String getLoggerFactoryClassStr() {
70 throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar");
71 }
72 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.spi.MDCAdapter;
27
28 /**
29 * This class is only a stub. Real implementations are found in
30 * each SLF4J binding project, e.g. slf4j-nop, slf4j-log4j12 etc.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 throw new UnsupportedOperationException("This code should never make it into the jar");
43 }
44
45 /**
46 * Currently this method always returns an instance of
47 * {@link StaticMDCBinder}.
48 */
49 public MDCAdapter getMDCA() {
50 throw new UnsupportedOperationException("This code should never make it into the jar");
51 }
52
53 public String getMDCAdapterClassStr() {
54 throw new UnsupportedOperationException("This code should never make it into the jar");
55 }
56 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * This class is meant to provide a *dummy* StaticMarkerBinder to the slf4j-api module.
37 * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop,
38 * slf4j-simple, slf4j-log4j12 etc.
39 *
40 * @author Ceki G&uuml;lc&uuml;
41 */
42 public class StaticMarkerBinder implements MarkerFactoryBinder {
43
44 /**
45 * The unique instance of this class.
46 */
47 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
48
49 private StaticMarkerBinder() {
50 throw new UnsupportedOperationException("This code should never make it into the jar");
51 }
52
53 /**
54 * Currently this method always returns an instance of
55 * {@link BasicMarkerFactory}.
56 */
57 public IMarkerFactory getMarkerFactory() {
58 throw new UnsupportedOperationException("This code should never make it into the jar");
59 }
60
61 /**
62 * Currently, this method returns the class name of
63 * {@link BasicMarkerFactory}.
64 */
65 public String getMarkerFactoryClassStr() {
66 throw new UnsupportedOperationException("This code should never make it into the jar");
67 }
68
69 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>Implementations of core logging interfaces defined in the {@link
12 org.slf4j} package.</p>
13
14 <hr/>
15 </body>
16 </html>
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2
3 <html>
4 <head>
5 <title></title>
6 </head>
7
8
9 <body>
10
11 <p>Core logging interfaces.</p>
12
13 <hr/>
14 </body>
15 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28
29 /**
30 * An <b>optional</b> interface helping integration with logging systems capable of
31 * extracting location information. This interface is mainly used by SLF4J bridges
32 * such as jcl-over-slf4j, jul-to-slf4j and log4j-over-slf4j or {@link Logger} wrappers
33 * which need to provide hints so that the underlying logging system can extract
34 * the correct location information (method name, line number).
35 *
36 * @author Ceki Gulcu
37 * @since 1.3
38 */
39 public interface LocationAwareLogger extends Logger {
40
41 final public int TRACE_INT = 00;
42 final public int DEBUG_INT = 10;
43 final public int INFO_INT = 20;
44 final public int WARN_INT = 30;
45 final public int ERROR_INT = 40;
46
47 /**
48 * Printing method with support for location information.
49 *
50 * @param marker The marker to be used for this event, may be null.
51 * @param fqcn The fully qualified class name of the <b>logger instance</b>,
52 * typically the logger class, logger bridge or a logger wrapper.
53 * @param level One of the level integers defined in this interface
54 * @param message The message for the log event
55 * @param t Throwable associated with the log event, may be null.
56 */
57 public void log(Marker marker, String fqcn, int level, String message, Object[] argArray, Throwable t);
58
59 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import org.slf4j.ILoggerFactory;
27
28 /**
29 * An internal interface which helps the static {@link org.slf4j.LoggerFactory}
30 * class bind with the appropriate {@link ILoggerFactory} instance.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public interface LoggerFactoryBinder {
35
36 /**
37 * Return the instance of {@link ILoggerFactory} that
38 * {@link org.slf4j.LoggerFactory} class should bind to.
39 *
40 * @return the instance of {@link ILoggerFactory} that
41 * {@link org.slf4j.LoggerFactory} class should bind to.
42 */
43 public ILoggerFactory getLoggerFactory();
44
45 /**
46 * The String form of the {@link ILoggerFactory} object that this
47 * <code>LoggerFactoryBinder</code> instance is <em>intended</em> to return.
48 *
49 * <p>This method allows the developer to intterogate this binder's intention
50 * which may be different from the {@link ILoggerFactory} instance it is able to
51 * yield in practice. The discrepency should only occur in case of errors.
52 *
53 * @return the class name of the intended {@link ILoggerFactory} instance
54 */
55 public String getLoggerFactoryClassStr();
56 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import java.util.Map;
27
28 /**
29 * This interface abstracts the service offered by various MDC
30 * implementations.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 * @since 1.4.1
34 */
35 public interface MDCAdapter {
36
37 /**
38 * Put a context value (the <code>val</code> parameter) as identified with
39 * the <code>key</code> parameter into the current thread's context map.
40 * The <code>key</code> parameter cannot be null. The code>val</code> parameter
41 * can be null only if the underlying implementation supports it.
42 *
43 * <p>If the current thread does not have a context map it is created as a side
44 * effect of this call.
45 */
46 public void put(String key, String val);
47
48 /**
49 * Get the context identified by the <code>key</code> parameter.
50 * The <code>key</code> parameter cannot be null.
51 *
52 * @return the string value identified by the <code>key</code> parameter.
53 */
54 public String get(String key);
55
56 /**
57 * Remove the the context identified by the <code>key</code> parameter.
58 * The <code>key</code> parameter cannot be null.
59 *
60 * <p>
61 * This method does nothing if there is no previous value
62 * associated with <code>key</code>.
63 */
64 public void remove(String key);
65
66 /**
67 * Clear all entries in the MDC.
68 */
69 public void clear();
70
71 /**
72 * Return a copy of the current thread's context map, with keys and
73 * values of type String. Returned value may be null.
74 *
75 * @return A copy of the current thread's context map. May be null.
76 * @since 1.5.1
77 */
78 public Map<String, String> getCopyOfContextMap();
79
80 /**
81 * Set the current thread's context map by first clearing any existing
82 * map and then copying the map passed as parameter. The context map
83 * parameter must only contain keys and values of type String.
84 *
85 * @param contextMap must contain only keys and values of type String
86 *
87 * @since 1.5.1
88 */
89 public void setContextMap(Map<String, String> contextMap);
90 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.spi;
25
26 import org.slf4j.IMarkerFactory;
27
28 /**
29 * An internal interface which helps the static {@link org.slf4j.MarkerFactory}
30 * class bind with the appropriate {@link IMarkerFactory} instance.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public interface MarkerFactoryBinder {
35
36 /**
37 * Return the instance of {@link IMarkerFactory} that
38 * {@link org.slf4j.MarkerFactory} class should bind to.
39 *
40 * @return the instance of {@link IMarkerFactory} that
41 * {@link org.slf4j.MarkerFactory} class should bind to.
42 */
43 public IMarkerFactory getMarkerFactory();
44
45 /**
46 * The String form of the {@link IMarkerFactory} object that this
47 * <code>MarkerFactoryBinder</code> instance is <em>intended</em> to return.
48 *
49 * <p>This method allows the developer to intterogate this binder's intention
50 * which may be different from the {@link IMarkerFactory} instance it is able to
51 * return. Such a discrepency should only occur in case of errors.
52 *
53 * @return the class name of the intended {@link IMarkerFactory} instance
54 */
55 public String getMarkerFactoryClassStr();
56 }
0
1 <body>
2
3
4 Classes and interfaces which are internal to SLF4J. Under most
5 circumstances SLF4J users should be oblivious even to the existence of
6 this package.
7 </body>
0 Implementation-Title: slf4j-api
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.api
3 Bundle-Name: slf4j-api
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j.impl;version=${slf4j.api.minimum.compatible.version}
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.util.Iterator;
27
28 import junit.framework.TestCase;
29
30 import org.slf4j.helpers.BasicMarkerFactory;
31
32 /**
33 * Unit test BasicMarker
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 * @author Joern Huxhorn
37 */
38 public class BasicMarkerTest extends TestCase {
39 static final String BLUE_STR = "BLUE";
40 static final String RED_STR = "RED";
41 static final String GREEN_STR = "GREEN";
42 static final String COMP_STR = "COMP";
43 static final String MULTI_COMP_STR = "MULTI_COMP";
44 static final String PARENT_MARKER_STR = "PARENT_MARKER";
45 static final String CHILD_MARKER_STR = "CHILD_MARKER";
46 static final String NOT_CONTAINED_MARKER_STR = "NOT_CONTAINED";
47
48 final IMarkerFactory factory;
49 final Marker blue;
50 final Marker red;
51 final Marker green;
52 final Marker comp;
53 final Marker multiComp;
54
55 short diff = Differentiator.getDiffentiator();
56
57 public BasicMarkerTest() {
58 factory = new BasicMarkerFactory();
59
60 blue = factory.getMarker(BLUE_STR);
61 red = factory.getMarker(RED_STR);
62 green = factory.getMarker(GREEN_STR);
63 comp = factory.getMarker(COMP_STR);
64 comp.add(blue);
65
66 multiComp = factory.getMarker(MULTI_COMP_STR);
67 multiComp.add(green);
68 multiComp.add(comp);
69 }
70
71 public void testPrimitive() {
72 assertEquals(BLUE_STR, blue.getName());
73 assertTrue(blue.contains(blue));
74
75 Marker blue2 = factory.getMarker(BLUE_STR);
76 assertEquals(BLUE_STR, blue2.getName());
77 assertEquals(blue, blue2);
78 assertTrue(blue.contains(blue2));
79 assertTrue(blue2.contains(blue));
80 }
81
82 public void testPrimitiveByName() {
83 assertTrue(blue.contains(BLUE_STR));
84 }
85
86 public void testComposite() {
87 assertTrue(comp.contains(comp));
88 assertTrue(comp.contains(blue));
89 }
90
91 public void testCompositeByName() {
92 assertTrue(comp.contains(COMP_STR));
93 assertTrue(comp.contains(BLUE_STR));
94 }
95
96 public void testMultiComposite() {
97 assertTrue(multiComp.contains(comp));
98 assertTrue(multiComp.contains(blue));
99 assertTrue(multiComp.contains(green));
100 assertFalse(multiComp.contains(red));
101 }
102
103 public void testMultiCompositeByName() {
104 assertTrue(multiComp.contains(COMP_STR));
105 assertTrue(multiComp.contains(BLUE_STR));
106 assertTrue(multiComp.contains(GREEN_STR));
107 assertFalse(multiComp.contains(RED_STR));
108 }
109
110 public void testMultiAdd() {
111 Marker parent = factory.getMarker(PARENT_MARKER_STR);
112 Marker child = factory.getMarker(CHILD_MARKER_STR);
113 for (int i = 0; i < 10; i++) {
114 parent.add(child);
115 }
116
117 // check that the child was added once and only once
118 Iterator<Marker> iterator = parent.iterator();
119 assertTrue(iterator.hasNext());
120 assertEquals(CHILD_MARKER_STR, iterator.next().toString());
121 assertFalse(iterator.hasNext());
122 }
123
124 public void testAddRemove() {
125 final String NEW_PREFIX = "NEW_";
126 Marker parent = factory.getMarker(NEW_PREFIX + PARENT_MARKER_STR);
127 Marker child = factory.getMarker(NEW_PREFIX + CHILD_MARKER_STR);
128 assertFalse(parent.contains(child));
129 assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR));
130 assertFalse(parent.remove(child));
131
132 parent.add(child);
133
134 assertTrue(parent.contains(child));
135 assertTrue(parent.contains(NEW_PREFIX + CHILD_MARKER_STR));
136
137 assertTrue(parent.remove(child));
138
139 assertFalse(parent.contains(child));
140 assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR));
141 assertFalse(parent.remove(child));
142 }
143
144 public void testSelfRecursion() {
145 final String diffPrefix = "NEW_" + diff;
146 final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR;
147 final String NOT_CONTAINED_NAME = diffPrefix + NOT_CONTAINED_MARKER_STR;
148 Marker parent = factory.getMarker(PARENT_NAME);
149 Marker notContained = factory.getMarker(NOT_CONTAINED_NAME);
150 parent.add(parent);
151 assertTrue(parent.contains(parent));
152 assertTrue(parent.contains(PARENT_NAME));
153 assertFalse(parent.contains(notContained));
154 assertFalse(parent.contains(NOT_CONTAINED_MARKER_STR));
155 }
156
157 public void testIndirectRecursion() {
158 final String diffPrefix = "NEW_" + diff;
159 final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR;
160 final String CHILD_NAME = diffPrefix + CHILD_MARKER_STR;
161 final String NOT_CONTAINED_NAME = diffPrefix + NOT_CONTAINED_MARKER_STR;
162
163 Marker parent = factory.getMarker(PARENT_NAME);
164 Marker child = factory.getMarker(CHILD_NAME);
165 Marker notContained = factory.getMarker(NOT_CONTAINED_NAME);
166
167 parent.add(child);
168 child.add(parent);
169 assertTrue(parent.contains(parent));
170 assertTrue(parent.contains(child));
171 assertTrue(parent.contains(PARENT_NAME));
172 assertTrue(parent.contains(CHILD_NAME));
173 assertFalse(parent.contains(notContained));
174 assertFalse(parent.contains(NOT_CONTAINED_MARKER_STR));
175 }
176
177 public void testHomonyms() {
178 final String diffPrefix = "homonym" + diff;
179 final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR;
180 final String CHILD_NAME = diffPrefix + CHILD_MARKER_STR;
181 Marker parent = factory.getMarker(PARENT_NAME);
182 Marker child = factory.getMarker(CHILD_NAME);
183 parent.add(child);
184
185 IMarkerFactory otherFactory = new BasicMarkerFactory();
186 Marker otherParent = otherFactory.getMarker(PARENT_NAME);
187 Marker otherChild = otherFactory.getMarker(CHILD_NAME);
188
189 assertTrue(parent.contains(otherParent));
190 assertTrue(parent.contains(otherChild));
191
192 assertTrue(parent.remove(otherChild));
193 }
194
195 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j;
26
27 import java.util.Random;
28
29 public class Differentiator {
30
31 static Random random = new Random(System.currentTimeMillis());
32
33 static public short getDiffentiator() {
34 return (short) random.nextInt(Short.MAX_VALUE);
35 }
36 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.util.Random;
27
28 import org.slf4j.helpers.BasicMarker;
29 import org.slf4j.helpers.NOPLogger;
30
31 import junit.framework.TestCase;
32
33 public class NoBindingTest extends TestCase {
34
35 int diff = new Random().nextInt(10000);
36
37 public void testLogger() {
38 Logger logger = LoggerFactory.getLogger(NoBindingTest.class);
39 logger.debug("hello" + diff);
40 assertTrue(logger instanceof NOPLogger);
41 }
42
43 public void testMDC() {
44 MDC.put("k" + diff, "v");
45 assertNull(MDC.get("k"));
46 }
47
48 public void testMarker() {
49 Marker m = MarkerFactory.getMarker("a" + diff);
50 assertTrue(m instanceof BasicMarker);
51 }
52 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import junit.framework.AssertionFailedError;
27
28 /**
29 * BogoPerf is used to check that the time required to perform a certain
30 * operation does not deteriorate over time. BogoPerf adjusts to the CPU speed
31 * and capabilities of the host.
32 *
33 * @author Ceki G&uuml;lc&uuml;
34 *
35 */
36 public class BogoPerf {
37
38 private static long NANOS_IN_ONE_SECOND = 1000 * 1000 * 1000;
39 private static int INITIAL_N = 1000;
40 private static int LAST_N = 100;
41 private static int SLACK_FACTOR = 3;
42
43 static {
44 // let the JIT warm up
45 computeBogoIPS(INITIAL_N);
46 double bogo_ips = computeBogoIPS(INITIAL_N);
47 System.out.println("Host runs at " + bogo_ips + " BIPS");
48 }
49
50 /**
51 * Compute bogoInstructions per second
52 * <p>
53 * on a 3.2 Ghz Pentium D CPU (around 2007), we obtain about 9'000 bogoIPS.
54 *
55 * @param N
56 * number of bogoInstructions to average over in order to
57 * compute the result
58 * @return bogo Instructions Per Second
59 */
60 private static double computeBogoIPS(int N) {
61 long begin = System.nanoTime();
62
63 for (int i = 0; i < N; i++) {
64 bogoInstruction();
65 }
66 long end = System.nanoTime();
67
68 // duration
69 double D = end - begin;
70 // average duration per instruction
71 double avgDPIS = D / N;
72 // System.out.println(D + " nanos for " + N + " instructions");
73 // System.out.println(avgD + " nanos per instruction");
74
75 double bogoIPS = NANOS_IN_ONE_SECOND / avgDPIS;
76 // System.out.println(bogoIPS + " bogoIPS");
77
78 return bogoIPS;
79 }
80
81 private static void bogoInstruction() {
82 // use our own random number generator, independent of the host JDK
83 MyRandom myRandom = new MyRandom(100);
84 int len = 150;
85 int[] intArray = new int[len];
86 for (int i = 0; i < len; i++) {
87 intArray[i] = myRandom.nextInt();
88 }
89 // use our own sort algorithm, independent of the host JDK
90 BubbleSort.sort(intArray);
91 }
92
93 /**
94 * Computed the BogoIPS for this host CPU.
95 *
96 * @return
97 */
98 public static double currentBIPS() {
99 return computeBogoIPS(LAST_N);
100 }
101
102 static double min(double a, double b) {
103 return (a <= b) ? a : b;
104 }
105
106 /**
107 * Assertion used for values that <b>decrease</b> with faster CPUs, typically
108 * the time (duration) needed to perform a task.
109 *
110 * @param currentDuration
111 * @param referenceDuration
112 * @param referenceBIPS
113 * @throws AssertionFailedError
114 */
115 public static void assertDuration(double currentDuration, long referenceDuration, double referenceBIPS) throws AssertionFailedError {
116 double ajustedDuration = adjustExpectedDuration(referenceDuration, referenceBIPS);
117 if (currentDuration > ajustedDuration * SLACK_FACTOR) {
118 throw new AssertionFailedError("current duration " + currentDuration + " exceeded expected " + ajustedDuration + " (adjusted reference), "
119 + referenceDuration + " (raw reference)");
120 }
121 }
122
123 /**
124 * Assertion used for values that <b>increase<b> with faster CPUs, typically
125 * the number of operations accomplished per unit of time.
126 *
127 * @param currentPerformance
128 * @param referencePerformance
129 * @param referenceBIPS
130 * @throws AssertionFailedError
131 */
132 public static void assertPerformance(double currentPerformance, long referencePerformance, double referenceBIPS) throws AssertionFailedError {
133 double ajustedPerf = adjustExpectedPerformance(referencePerformance, referenceBIPS);
134 if (currentPerformance * SLACK_FACTOR < ajustedPerf) {
135 throw new AssertionFailedError(currentPerformance + " below expected " + ajustedPerf + " (adjusted), " + referencePerformance + " (raw)");
136 }
137 }
138
139 private static double adjustExpectedPerformance(long referenceDuration, double referenceBIPS) {
140 double currentBIPS = currentBIPS();
141 return referenceDuration * (currentBIPS / referenceBIPS);
142 }
143
144 private static double adjustExpectedDuration(long referenceDuration, double referenceBIPS) {
145 double currentBIPS = currentBIPS();
146 System.out.println("currentBIPS=" + currentBIPS + " BIPS");
147 return referenceDuration * (referenceBIPS / currentBIPS);
148 }
149 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 /**
27 * This class is used internally by BogoPerf, hence the package private
28 * (default) access.
29 *
30 * @author Ceki
31 */
32 class BubbleSort {
33
34 static void sort(int[] a) {
35 int len = a.length;
36 for (int i = 0; i < len - 1; i++) {
37 for (int j = 0; j < len - 1 - i; j++) {
38 if (a[j] > a[j + 1]) {
39 swap(a, j, j + 1);
40 }
41 }
42 }
43 }
44
45 static void swap(int[] a, int i, int j) {
46 int t = a[i];
47 a[i] = a[j];
48 a[j] = t;
49 }
50 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.Arrays;
27 import java.util.Random;
28
29 import junit.framework.TestCase;
30
31 /**
32 * Test that our BubbleSort algorithm is correctly implemented.
33 *
34 * @author Ceki
35 *
36 */
37 public class BubbleSortTest extends TestCase {
38
39 public void testSmoke() {
40 int[] a = new int[] { 5, 3, 2, 7 };
41 BubbleSort.sort(a);
42 int i = 0;
43 assertEquals(2, a[i++]);
44 assertEquals(3, a[i++]);
45 assertEquals(5, a[i++]);
46 assertEquals(7, a[i++]);
47 }
48
49 public void testEmpty() {
50 int[] a = new int[] {};
51 BubbleSort.sort(a);
52 }
53
54 public void testSorted() {
55 int[] a = new int[] { 3, 30, 300, 3000 };
56 BubbleSort.sort(a);
57 int i = 0;
58 assertEquals(3, a[i++]);
59 assertEquals(30, a[i++]);
60 assertEquals(300, a[i++]);
61 assertEquals(3000, a[i++]);
62 }
63
64 public void testInverted() {
65 int[] a = new int[] { 3000, 300, 30, 3 };
66 BubbleSort.sort(a);
67 int i = 0;
68 assertEquals(3, a[i++]);
69 assertEquals(30, a[i++]);
70 assertEquals(300, a[i++]);
71 assertEquals(3000, a[i++]);
72 }
73
74 public void testWithSameEntry() {
75 int[] a = new int[] { 10, 20, 10, 20 };
76 BubbleSort.sort(a);
77 int i = 0;
78 assertEquals(10, a[i++]);
79 assertEquals(10, a[i++]);
80 assertEquals(20, a[i++]);
81 assertEquals(20, a[i++]);
82 }
83
84 public void testRandom() {
85 int len = 100;
86 Random random = new Random(156);
87 int[] a = new int[len];
88 int[] witness = new int[len];
89 for (int i = 0; i < len; i++) {
90 int r = random.nextInt();
91 a[i] = r;
92 witness[i] = r;
93 }
94 BubbleSort.sort(a);
95 Arrays.sort(witness);
96 assertTrue(Arrays.equals(witness, a));
97 }
98
99 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.text.MessageFormat;
27
28 import junit.framework.TestCase;
29 import org.junit.Ignore;
30
31 @Ignore
32 public class MessageFormatterPerfTest extends TestCase {
33
34 Integer i1 = new Integer(1);
35 Integer i2 = new Integer(2);
36 static long RUN_LENGTH = 100 * 1000;
37 //
38 static long REFERENCE_BIPS = 48416;
39
40 public MessageFormatterPerfTest(String name) {
41 super(name);
42 }
43
44 protected void setUp() throws Exception {
45 }
46
47 protected void tearDown() throws Exception {
48 }
49
50 public void XtestJDKFormatterPerf() {
51 jdkMessageFormatter(RUN_LENGTH);
52 double duration = jdkMessageFormatter(RUN_LENGTH);
53 System.out.println("jdk duration = " + duration + " nanos");
54 }
55
56 public void testSLF4JPerf_OneArg() {
57 slf4jMessageFormatter_OneArg(RUN_LENGTH);
58 double duration = slf4jMessageFormatter_OneArg(RUN_LENGTH);
59 System.out.println("duration=" + duration);
60 long referencePerf = 36;
61 BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS);
62 }
63
64 public void testSLF4JPerf_TwoArg() {
65 slf4jMessageFormatter_TwoArg(RUN_LENGTH);
66 double duration = slf4jMessageFormatter_TwoArg(RUN_LENGTH);
67 long referencePerf = 60;
68 BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS);
69 }
70
71 public double slf4jMessageFormatter_OneArg(long len) {
72 long start = System.nanoTime();
73 for (int i = 0; i < len; i++) {
74 final FormattingTuple tp = MessageFormatter.format("This is some rather short message {} ", i1);
75 tp.getMessage();
76 tp.getArgArray();
77 tp.getThrowable();
78
79 MessageFormatter.format("This is some rather short message {} ", i1);
80 }
81 long end = System.nanoTime();
82 return (end - start) / (1000 * 1000.0);
83 }
84
85 public double slf4jMessageFormatter_TwoArg(long len) {
86 long start = System.nanoTime();
87 for (int i = 0; i < len; i++) {
88 final FormattingTuple tp = MessageFormatter.format("This is some {} short message {} ", i1, i2);
89 tp.getMessage();
90 tp.getArgArray();
91 tp.getThrowable();
92 }
93 long end = System.nanoTime();
94 return (end - start) / (1000 * 1000.0);
95 }
96
97 public double jdkMessageFormatter(long len) {
98 @SuppressWarnings("unused")
99 String s = "";
100 s += ""; // keep compiler happy
101 long start = System.currentTimeMillis();
102 Object[] oa = new Object[] { i1 };
103 for (int i = 0; i < len; i++) {
104 s = MessageFormat.format("This is some rather short message {0}", oa);
105 }
106 long end = System.currentTimeMillis();
107 return (1.0 * end - start);
108 }
109
110 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.util.Arrays;
27
28 import org.junit.Test;
29
30 import static org.junit.Assert.*;
31
32 /**
33 * @author Ceki Gulcu
34 */
35 public class MessageFormatterTest {
36
37 Integer i1 = new Integer(1);
38 Integer i2 = new Integer(2);
39 Integer i3 = new Integer(3);
40 Integer[] ia0 = new Integer[] { i1, i2, i3 };
41 Integer[] ia1 = new Integer[] { new Integer(10), new Integer(20), new Integer(30) };
42
43 String result;
44
45 @Test
46 public void testNull() {
47 result = MessageFormatter.format(null, i1).getMessage();
48 assertEquals(null, result);
49 }
50
51 @Test
52 public void nullParametersShouldBeHandledWithoutBarfing() {
53 result = MessageFormatter.format("Value is {}.", null).getMessage();
54 assertEquals("Value is null.", result);
55
56 result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, null).getMessage();
57 assertEquals("Val1 is null, val2 is null.", result);
58
59 result = MessageFormatter.format("Val1 is {}, val2 is {}.", i1, null).getMessage();
60 assertEquals("Val1 is 1, val2 is null.", result);
61
62 result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, i2).getMessage();
63 assertEquals("Val1 is null, val2 is 2.", result);
64
65 result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, null }).getMessage();
66 assertEquals("Val1 is null, val2 is null, val3 is null", result);
67
68 result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, i2, i3 }).getMessage();
69 assertEquals("Val1 is null, val2 is 2, val3 is 3", result);
70
71 result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, i3 }).getMessage();
72 assertEquals("Val1 is null, val2 is null, val3 is 3", result);
73 }
74
75 @Test
76 public void verifyOneParameterIsHandledCorrectly() {
77 result = MessageFormatter.format("Value is {}.", i3).getMessage();
78 assertEquals("Value is 3.", result);
79
80 result = MessageFormatter.format("Value is {", i3).getMessage();
81 assertEquals("Value is {", result);
82
83 result = MessageFormatter.format("{} is larger than 2.", i3).getMessage();
84 assertEquals("3 is larger than 2.", result);
85
86 result = MessageFormatter.format("No subst", i3).getMessage();
87 assertEquals("No subst", result);
88
89 result = MessageFormatter.format("Incorrect {subst", i3).getMessage();
90 assertEquals("Incorrect {subst", result);
91
92 result = MessageFormatter.format("Value is {bla} {}", i3).getMessage();
93 assertEquals("Value is {bla} 3", result);
94
95 result = MessageFormatter.format("Escaped \\{} subst", i3).getMessage();
96 assertEquals("Escaped {} subst", result);
97
98 result = MessageFormatter.format("{Escaped", i3).getMessage();
99 assertEquals("{Escaped", result);
100
101 result = MessageFormatter.format("\\{}Escaped", i3).getMessage();
102 assertEquals("{}Escaped", result);
103
104 result = MessageFormatter.format("File name is {{}}.", "App folder.zip").getMessage();
105 assertEquals("File name is {App folder.zip}.", result);
106
107 // escaping the escape character
108 result = MessageFormatter.format("File name is C:\\\\{}.", "App folder.zip").getMessage();
109 assertEquals("File name is C:\\App folder.zip.", result);
110 }
111
112 @Test
113 public void testTwoParameters() {
114 result = MessageFormatter.format("Value {} is smaller than {}.", i1, i2).getMessage();
115 assertEquals("Value 1 is smaller than 2.", result);
116
117 result = MessageFormatter.format("Value {} is smaller than {}", i1, i2).getMessage();
118 assertEquals("Value 1 is smaller than 2", result);
119
120 result = MessageFormatter.format("{}{}", i1, i2).getMessage();
121 assertEquals("12", result);
122
123 result = MessageFormatter.format("Val1={}, Val2={", i1, i2).getMessage();
124 assertEquals("Val1=1, Val2={", result);
125
126 result = MessageFormatter.format("Value {} is smaller than \\{}", i1, i2).getMessage();
127 assertEquals("Value 1 is smaller than {}", result);
128
129 result = MessageFormatter.format("Value {} is smaller than \\{} tail", i1, i2).getMessage();
130 assertEquals("Value 1 is smaller than {} tail", result);
131
132 result = MessageFormatter.format("Value {} is smaller than \\{", i1, i2).getMessage();
133 assertEquals("Value 1 is smaller than \\{", result);
134
135 result = MessageFormatter.format("Value {} is smaller than {tail", i1, i2).getMessage();
136 assertEquals("Value 1 is smaller than {tail", result);
137
138 result = MessageFormatter.format("Value \\{} is smaller than {}", i1, i2).getMessage();
139 assertEquals("Value {} is smaller than 1", result);
140 }
141
142 @Test
143 public void testExceptionIn_toString() {
144 Object o = new Object() {
145 public String toString() {
146 throw new IllegalStateException("a");
147 }
148 };
149 result = MessageFormatter.format("Troublesome object {}", o).getMessage();
150 assertEquals("Troublesome object [FAILED toString()]", result);
151
152 }
153
154 @Test
155 public void testNullArray() {
156 String msg0 = "msg0";
157 String msg1 = "msg1 {}";
158 String msg2 = "msg2 {} {}";
159 String msg3 = "msg3 {} {} {}";
160
161 Object[] args = null;
162
163 result = MessageFormatter.arrayFormat(msg0, args).getMessage();
164 assertEquals(msg0, result);
165
166 result = MessageFormatter.arrayFormat(msg1, args).getMessage();
167 assertEquals(msg1, result);
168
169 result = MessageFormatter.arrayFormat(msg2, args).getMessage();
170 assertEquals(msg2, result);
171
172 result = MessageFormatter.arrayFormat(msg3, args).getMessage();
173 assertEquals(msg3, result);
174 }
175
176 // tests the case when the parameters are supplied in a single array
177 @Test
178 public void testArrayFormat() {
179 result = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia0).getMessage();
180 assertEquals("Value 1 is smaller than 2 and 3.", result);
181
182 result = MessageFormatter.arrayFormat("{}{}{}", ia0).getMessage();
183 assertEquals("123", result);
184
185 result = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia0).getMessage();
186 assertEquals("Value 1 is smaller than 2.", result);
187
188 result = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia0).getMessage();
189 assertEquals("Value 1 is smaller than 2", result);
190
191 result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage();
192 assertEquals("Val=1, {, Val=2", result);
193
194 result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage();
195 assertEquals("Val=1, {, Val=2", result);
196
197 result = MessageFormatter.arrayFormat("Val1={}, Val2={", ia0).getMessage();
198 assertEquals("Val1=1, Val2={", result);
199 }
200
201 @Test
202 public void testArrayValues() {
203 Integer p0 = i1;
204 Integer[] p1 = new Integer[] { i2, i3 };
205
206 result = MessageFormatter.format("{}{}", p0, p1).getMessage();
207 assertEquals("1[2, 3]", result);
208
209 // Integer[]
210 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", p1 }).getMessage();
211 assertEquals("a[2, 3]", result);
212
213 // byte[]
214 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new byte[] { 1, 2 } }).getMessage();
215 assertEquals("a[1, 2]", result);
216
217 // int[]
218 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new int[] { 1, 2 } }).getMessage();
219 assertEquals("a[1, 2]", result);
220
221 // float[]
222 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new float[] { 1, 2 } }).getMessage();
223 assertEquals("a[1.0, 2.0]", result);
224
225 // double[]
226 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new double[] { 1, 2 } }).getMessage();
227 assertEquals("a[1.0, 2.0]", result);
228
229 }
230
231 @Test
232 public void testMultiDimensionalArrayValues() {
233 Integer[][] multiIntegerA = new Integer[][] { ia0, ia1 };
234 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntegerA }).getMessage();
235 assertEquals("a[[1, 2, 3], [10, 20, 30]]", result);
236
237 int[][] multiIntA = new int[][] { { 1, 2 }, { 10, 20 } };
238 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntA }).getMessage();
239 assertEquals("a[[1, 2], [10, 20]]", result);
240
241 float[][] multiFloatA = new float[][] { { 1, 2 }, { 10, 20 } };
242 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiFloatA }).getMessage();
243 assertEquals("a[[1.0, 2.0], [10.0, 20.0]]", result);
244
245 Object[][] multiOA = new Object[][] { ia0, ia1 };
246 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiOA }).getMessage();
247 assertEquals("a[[1, 2, 3], [10, 20, 30]]", result);
248
249 Object[][][] _3DOA = new Object[][][] { multiOA, multiOA };
250 result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", _3DOA }).getMessage();
251 assertEquals("a[[[1, 2, 3], [10, 20, 30]], [[1, 2, 3], [10, 20, 30]]]", result);
252 }
253
254 @Test
255 public void testCyclicArrays() {
256 {
257 Object[] cyclicA = new Object[1];
258 cyclicA[0] = cyclicA;
259 assertEquals("[[...]]", MessageFormatter.arrayFormat("{}", cyclicA).getMessage());
260 }
261 {
262 Object[] a = new Object[2];
263 a[0] = i1;
264 Object[] c = new Object[] { i3, a };
265 Object[] b = new Object[] { i2, c };
266 a[1] = b;
267 assertEquals("1[2, [3, [1, [...]]]]", MessageFormatter.arrayFormat("{}{}", a).getMessage());
268 }
269 }
270
271 @Test
272 public void testArrayThrowable() {
273 FormattingTuple ft;
274 Throwable t = new Throwable();
275 Object[] ia = new Object[] { i1, i2, i3, t };
276 Object[] iaWitness = new Object[] { i1, i2, i3 };
277
278 ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia);
279 assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage());
280 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
281 assertEquals(t, ft.getThrowable());
282
283 ft = MessageFormatter.arrayFormat("{}{}{}", ia);
284 assertEquals("123", ft.getMessage());
285 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
286 assertEquals(t, ft.getThrowable());
287
288 ft = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia);
289 assertEquals("Value 1 is smaller than 2.", ft.getMessage());
290 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
291 assertEquals(t, ft.getThrowable());
292
293 ft = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia);
294 assertEquals("Value 1 is smaller than 2", ft.getMessage());
295 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
296 assertEquals(t, ft.getThrowable());
297
298 ft = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia);
299 assertEquals("Val=1, {, Val=2", ft.getMessage());
300 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
301 assertEquals(t, ft.getThrowable());
302
303 ft = MessageFormatter.arrayFormat("Val={}, \\{, Val={}", ia);
304 assertEquals("Val=1, \\{, Val=2", ft.getMessage());
305 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
306 assertEquals(t, ft.getThrowable());
307
308 ft = MessageFormatter.arrayFormat("Val1={}, Val2={", ia);
309 assertEquals("Val1=1, Val2={", ft.getMessage());
310 assertTrue(Arrays.equals(iaWitness, ft.getArgArray()));
311 assertEquals(t, ft.getThrowable());
312
313 ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {} -- {} .", ia);
314 assertEquals("Value 1 is smaller than 2 and 3 -- " + t.toString() + " .", ft.getMessage());
315 assertTrue(Arrays.equals(ia, ft.getArgArray()));
316 assertNull(ft.getThrowable());
317
318 ft = MessageFormatter.arrayFormat("{}{}{}{}", ia);
319 assertEquals("123" + t.toString(), ft.getMessage());
320 assertTrue(Arrays.equals(ia, ft.getArgArray()));
321 assertNull(ft.getThrowable());
322 }
323 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 class MyRandom {
27
28 private final static long m = 200000000041L; // a prime number
29 private final static long a = 2000000011L; // a prime number
30
31 long y;
32 long unused;
33 int bits = 32;
34
35 public MyRandom() {
36 this(System.nanoTime());
37 }
38
39 public MyRandom(long seed) {
40 this.y = seed;
41 }
42
43 int nextInt() {
44 // we don't really care about the randomness of this
45 // generator
46 y = (a * y + 1) % m;
47 unused = y >>> (48 - bits); // just exercise the >>> operator
48 return (int) (y);
49 }
50 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import java.lang.reflect.InvocationHandler;
27 import java.lang.reflect.InvocationTargetException;
28 import java.lang.reflect.Method;
29 import java.lang.reflect.Proxy;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Set;
35
36 import junit.framework.TestCase;
37 import org.slf4j.Logger;
38
39 /**
40 * @author Chetan Mehrotra
41 */
42 public class SubstitutableLoggerTest extends TestCase {
43 private static final Set<String> EXCLUDED_METHODS = new HashSet<String>(Arrays.asList("getName"));
44
45 public void testDelegate() throws Exception {
46 SubstituteLogger log = new SubstituteLogger("foo");
47 assertTrue(log.delegate() instanceof NOPLogger);
48
49 Set<String> expectedMethodSignatures = determineMethodSignatures(Logger.class);
50 LoggerInvocationHandler ih = new LoggerInvocationHandler();
51 Logger proxyLogger = (Logger) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Logger.class }, ih);
52 log.setDelegate(proxyLogger);
53
54 invokeMethods(log);
55
56 // Assert that all methods are delegated
57 expectedMethodSignatures.removeAll(ih.getInvokedMethodSignatures());
58 if (!expectedMethodSignatures.isEmpty()) {
59 fail("Following methods are not delegated " + expectedMethodSignatures.toString());
60 }
61 }
62
63 private void invokeMethods(Logger proxyLogger) throws InvocationTargetException, IllegalAccessException {
64 for (Method m : Logger.class.getDeclaredMethods()) {
65 if (!EXCLUDED_METHODS.contains(m.getName())) {
66 m.invoke(proxyLogger, new Object[m.getParameterTypes().length]);
67 }
68 }
69 }
70
71 private class LoggerInvocationHandler implements InvocationHandler {
72 private final Set<String> invokedMethodSignatures = new HashSet<String>();
73
74 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
75 invokedMethodSignatures.add(getMethodSignature(method));
76 if (method.getName().startsWith("is")) {
77 return true;
78 }
79 return null;
80 }
81
82 public Set<String> getInvokedMethodSignatures() {
83 return invokedMethodSignatures;
84 }
85 }
86
87 private static Set<String> determineMethodSignatures(Class<Logger> loggerClass) {
88 Set<String> methodSignatures = new HashSet<String>();
89 for (Method m : loggerClass.getDeclaredMethods()) {
90 if (!EXCLUDED_METHODS.contains(m.getName())) {
91 methodSignatures.add(getMethodSignature(m));
92 }
93 }
94 return methodSignatures;
95 }
96
97 private static String getMethodSignature(Method m) {
98 List<String> result = new ArrayList<String>();
99 result.add(m.getName());
100 for (Class<?> clazz : m.getParameterTypes()) {
101 result.add(clazz.getSimpleName());
102 }
103 return result.toString();
104 }
105 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.helpers;
25
26 import junit.framework.TestCase;
27 import org.slf4j.Logger;
28
29 import java.util.Arrays;
30 import java.util.HashSet;
31 import java.util.Set;
32
33 public class SubstituteLoggerFactoryTest extends TestCase {
34 private SubstituteLoggerFactory factory = new SubstituteLoggerFactory();
35
36 public void testFactory() {
37 Logger log = factory.getLogger("foo");
38 assertNotNull(log);
39
40 Logger log2 = factory.getLogger("foo");
41 assertTrue("Loggers with same name must be same", log == log2);
42 }
43
44 public void testLoggerNameList() {
45 factory.getLogger("foo1");
46 factory.getLogger("foo2");
47
48 Set<String> expectedNames = new HashSet<String>(Arrays.asList("foo1", "foo2"));
49 Set<String> actualNames = new HashSet<String>(factory.getLoggerNames());
50
51 assertEquals(expectedNames, actualNames);
52 }
53
54 public void testLoggers() {
55 factory.getLogger("foo1");
56 factory.getLogger("foo2");
57
58 Set<String> expectedNames = new HashSet<String>(Arrays.asList("foo1", "foo2"));
59
60 Set<String> actualNames = new HashSet<String>();
61 for (SubstituteLogger slog : factory.getLoggers()) {
62 actualNames.add(slog.getName());
63 }
64
65 assertEquals(expectedNames, actualNames);
66 }
67
68 }
0 <project xmlns="http://maven.apache.org/POM/4.0.0"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
4 <modelVersion>4.0.0</modelVersion>
5
6 <parent>
7 <groupId>org.slf4j</groupId>
8 <artifactId>slf4j-parent</artifactId>
9 <version>1.7.12</version>
10 </parent>
11
12 <artifactId>slf4j-ext</artifactId>
13
14 <packaging>jar</packaging>
15 <name>SLF4J Extensions Module</name>
16 <description>Extensions to the SLF4J API</description>
17
18 <url>http://www.slf4j.org</url>
19
20 <dependencies>
21 <dependency>
22 <groupId>org.slf4j</groupId>
23 <artifactId>slf4j-api</artifactId>
24 </dependency>
25 <dependency>
26 <groupId>org.slf4j</groupId>
27 <artifactId>slf4j-log4j12</artifactId>
28 <version>${project.version}</version>
29 <scope>test</scope>
30 </dependency>
31 <dependency>
32 <groupId>ch.qos.cal10n</groupId>
33 <artifactId>cal10n-api</artifactId>
34 </dependency>
35 <dependency>
36 <groupId>javassist</groupId>
37 <artifactId>javassist</artifactId>
38 <version>3.4.GA</version>
39 <optional>true</optional>
40 </dependency>
41 <dependency>
42 <groupId>commons-lang</groupId>
43 <artifactId>commons-lang</artifactId>
44 <version>2.4</version>
45 <optional>true</optional>
46 </dependency>
47 </dependencies>
48
49 <build>
50 <plugins>
51 <plugin>
52 <groupId>org.apache.maven.plugins</groupId>
53 <artifactId>maven-compiler-plugin</artifactId>
54 <configuration>
55 <source>${required.jdk.version}</source>
56 <target>${required.jdk.version}</target>
57 </configuration>
58 </plugin>
59
60 <plugin>
61 <groupId>org.apache.maven.plugins</groupId>
62 <artifactId>maven-surefire-plugin</artifactId>
63 <configuration>
64 <!-- http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html -->
65 <printSummary>false</printSummary>
66 <forkMode>once</forkMode>
67 <reportFormat>plain</reportFormat>
68 <trimStackTrace>false</trimStackTrace>
69 <excludes>
70 <exclude>**/AllTest.java</exclude>
71 <exclude>**/PackageTest.java</exclude>
72 </excludes>
73 </configuration>
74 </plugin>
75
76
77 <plugin>
78 <groupId>org.apache.maven.plugins</groupId>
79 <artifactId>maven-jar-plugin</artifactId>
80 <configuration>
81 <archive>
82 <manifestEntries>
83 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
84 <Bundle-Description>${project.description}</Bundle-Description>
85 <Implementation-Version>${project.version}</Implementation-Version>
86 <Premain-Class>org.slf4j.agent.AgentPremain</Premain-Class>
87 <!-- what is the proper way to specify the maven full name? /ravn -->
88 <Boot-Class-Path>../../../../javassist/javassist/3.4.GA/javassist-3.4.GA.jar javassist-3.4.GA.jar javassist.jar</Boot-Class-Path>
89 </manifestEntries>
90 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
91 </archive>
92 </configuration>
93 </plugin>
94 </plugins>
95
96 </build>
97
98 <reporting>
99 <plugins>
100
101 </plugins>
102 </reporting>
103
104 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import org.slf4j.MDC;
27
28 public class NDC {
29 public final static String PREFIX = "NDC";
30
31 private static int size() {
32 int i = 0;
33 while (true) {
34 String val = MDC.get(PREFIX + i);
35 if (val != null) {
36 i++;
37 } else {
38 break;
39 }
40 }
41 return i;
42 }
43
44 public static void push(String val) {
45 int next = size();
46 MDC.put(PREFIX + next, val);
47 }
48
49 public static String pop() {
50 int next = size();
51 if (next == 0) {
52 return "";
53 }
54 int last = next - 1;
55 String key = PREFIX + last;
56 String val = MDC.get(key);
57 MDC.remove(key);
58 return val;
59 }
60
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.agent;
25
26 /**
27 * <p>
28 * All recognized options in the string passed to the java agent. For
29 * "java -javaagent:foo.jar=OPTIONS HelloWorld" this would be "OPTIONS".
30 * </p>
31 * <p>
32 * It is considered to be a list of options separated by (currently) ";", on the
33 * form "option=value". The interpretation of "value" is specific to each
34 * option.
35 * </p>
36 */
37 public class AgentOptions {
38
39 /**
40 * List of class prefixes to ignore when instrumenting. Note: Classes loaded
41 * before the agent cannot be instrumented.
42 */
43 public static final String IGNORE = "ignore";
44 /**
45 * Indicate the SLF4J level that should be used by the logging statements
46 * added by the agent. Default is "info".
47 */
48 public static final String LEVEL = "level";
49 /**
50 * Indicate that the agent should print out "new java.util.Date()" at the time
51 * the option was processed and at shutdown time (using the shutdown hook).
52 *
53 */
54 public static final String TIME = "time";
55 /**
56 * Indicate that the agent should log actions to System.err, like adding
57 * logging to methods, etc.
58 *
59 */
60 public static final String VERBOSE = "verbose";
61
62 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.agent;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.IOException;
28 import java.lang.instrument.Instrumentation;
29 import java.util.Date;
30 import java.util.Properties;
31
32 import org.slf4j.instrumentation.LogTransformer;
33
34 /**
35 * Entry point for slf4j-ext when used as a Java agent.
36 *
37 */
38 public class AgentPremain {
39
40 /**
41 * JavaAgent premain entry point as specified in the MANIFEST.MF file. See
42 * {@link http
43 * ://java.sun.com/javase/6/docs/api/java/lang/instrument/package-
44 * summary.html} for details.
45 *
46 * @param agentArgument
47 * string provided after "=" up to first space
48 * @param instrumentation
49 * instrumentation environment provided by the JVM
50 */
51 public static void premain(String agentArgument, Instrumentation instrumentation) {
52
53 // We cannot do sanity checks for slf4j here as the jars loaded
54 // by the application are not visible here.
55
56 LogTransformer.Builder builder = new LogTransformer.Builder();
57 builder = builder.addEntryExit(true);
58
59 if (agentArgument != null) {
60 Properties args = parseArguments(agentArgument, ",");
61
62 if (args.containsKey(AgentOptions.VERBOSE)) {
63 builder = builder.verbose(true);
64 }
65
66 if (args.containsKey(AgentOptions.TIME)) {
67 printStartStopTimes();
68 }
69
70 if (args.containsKey(AgentOptions.IGNORE)) {
71 String ignore = args.getProperty(AgentOptions.IGNORE);
72 builder = builder.ignore(ignore.split(":"));
73 }
74
75 if (args.containsKey(AgentOptions.LEVEL)) {
76 builder = builder.level(args.getProperty(AgentOptions.LEVEL));
77 }
78 }
79
80 instrumentation.addTransformer(builder.build());
81 }
82
83 /**
84 * Consider the argument string to be a property file (by converting the
85 * splitter character to line feeds), and then reading it like any other
86 * property file.
87 *
88 *
89 * @param agentArgument
90 * string given by instrumentation framework
91 * @param separator
92 * String to convert to line feeds
93 * @return argument converted to properties
94 */
95 private static Properties parseArguments(String agentArgument, String separator) {
96 Properties p = new Properties();
97 try {
98 String argumentAsLines = agentArgument.replaceAll(separator, "\n");
99 p.load(new ByteArrayInputStream(argumentAsLines.getBytes()));
100 } catch (IOException e) {
101 String s = "Could not load arguments as properties";
102 throw new RuntimeException(s, e);
103 }
104 return p;
105 }
106
107 /**
108 * Print the start message to System.err with the time NOW, and register a
109 * shutdown hook which will print the stop message to System.err with the
110 * time then and the number of milliseconds passed since.
111 *
112 */
113 private static void printStartStopTimes() {
114 final long start = System.currentTimeMillis();
115
116 System.err.println("Start at " + new Date());
117
118 Thread hook = new Thread() {
119 @Override
120 public void run() {
121 long timePassed = System.currentTimeMillis() - start;
122 System.err.println("Stop at " + new Date() + ", execution time = " + timePassed + " ms");
123 }
124 };
125 Runtime.getRuntime().addShutdownHook(hook);
126 }
127 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>"-javaagent" routines for SLF4J.</p>
10 <p>The "-javaagent" flag provided in Java 5+ allows for writing
11 agents in Java, which previously was possible in native code only. The
12 full details are available at <a
13 href="http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html">http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html</a>.
14
15
16 Please notice that code made available to the java agent is also
17 available to the actual program executed.</p>
18 <p>The slf4j-ext-X.Y.Z.jar file provides such a java agent, which is
19 implemented in AgentPremain.java. It is used by adding a -javaagent flag to the Java command line:
20
21 E.g.
22 <pre><code>java HelloWorld</code></pre>
23 is changed to
24 <pre><code>java -javaagent:/path/to/slf4j-ext-X.Y.Z.jar=<em>OPTIONS</em> HelloWorld</code></pre>
25
26 What is actually done, depends on the <em>OPTIONS</em> passed to the agent. These are listed in AgentOptions.java.
27 </p>
28
29
30
31 </body>
32 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.ext.LoggerWrapper;
30 import org.slf4j.spi.LocationAwareLogger;
31
32 import ch.qos.cal10n.IMessageConveyor;
33 import ch.qos.cal10n.MessageParameterObj;
34
35 /**
36 * A logger specialized in localized logging. Localization is based in the <a
37 * href="http://cal10n.qos.ch">CAL10N project</p>.
38 *
39 * @author Ceki G&uuml;lc&uuml;
40 */
41 public class LocLogger extends LoggerWrapper implements Logger {
42
43 private static final String FQCN = LocLogger.class.getName();
44
45 /**
46 * Every localized message logged by a LocLogger will bear this marker. It
47 * allows marker-aware implementations to perform additional processing on
48 * localized messages.
49 */
50 static Marker LOCALIZED = MarkerFactory.getMarker("LOCALIZED");
51
52 final IMessageConveyor imc;
53
54 public LocLogger(Logger logger, IMessageConveyor imc) {
55 super(logger, LoggerWrapper.class.getName());
56 if (imc == null) {
57 throw new IllegalArgumentException("IMessageConveyor cannot be null");
58 }
59 this.imc = imc;
60 }
61
62 /**
63 * Log a localized message at the TRACE level.
64 *
65 * @param key
66 * the key used for localization
67 * @param args
68 * optional arguments
69 */
70 public void trace(Enum<?> key, Object... args) {
71 if (!logger.isTraceEnabled()) {
72 return;
73 }
74 String translatedMsg = imc.getMessage(key, args);
75 MessageParameterObj mpo = new MessageParameterObj(key, args);
76
77 if (instanceofLAL) {
78 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.TRACE_INT, translatedMsg, args, null);
79 } else {
80 logger.trace(LOCALIZED, translatedMsg, mpo);
81 }
82 }
83
84 /**
85 * Log a localized message at the DEBUG level.
86 *
87 * @param key
88 * the key used for localization
89 * @param args
90 * optional arguments
91 */
92 public void debug(Enum<?> key, Object... args) {
93 if (!logger.isDebugEnabled()) {
94 return;
95 }
96 String translatedMsg = imc.getMessage(key, args);
97 MessageParameterObj mpo = new MessageParameterObj(key, args);
98
99 if (instanceofLAL) {
100 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.DEBUG_INT, translatedMsg, args, null);
101 } else {
102 logger.debug(LOCALIZED, translatedMsg, mpo);
103 }
104 }
105
106 /**
107 * Log a localized message at the INFO level.
108 *
109 * @param key
110 * the key used for localization
111 * @param args
112 * optional arguments
113 */
114 public void info(Enum<?> key, Object... args) {
115 if (!logger.isInfoEnabled()) {
116 return;
117 }
118 String translatedMsg = imc.getMessage(key, args);
119 MessageParameterObj mpo = new MessageParameterObj(key, args);
120
121 if (instanceofLAL) {
122 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.INFO_INT, translatedMsg, args, null);
123 } else {
124 logger.info(LOCALIZED, translatedMsg, mpo);
125 }
126 }
127
128 /**
129 * Log a localized message at the WARN level.
130 *
131 * @param key
132 * the key used for localization
133 * @param args
134 * optional arguments
135 */
136 public void warn(Enum<?> key, Object... args) {
137 if (!logger.isWarnEnabled()) {
138 return;
139 }
140 String translatedMsg = imc.getMessage(key, args);
141 MessageParameterObj mpo = new MessageParameterObj(key, args);
142
143 if (instanceofLAL) {
144 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.WARN_INT, translatedMsg, args, null);
145 } else {
146 logger.warn(LOCALIZED, translatedMsg, mpo);
147 }
148 }
149
150 /**
151 * Log a localized message at the ERROR level.
152 *
153 * @param key
154 * the key used for localization
155 * @param args
156 * optional arguments
157 */
158 public void error(Enum<?> key, Object... args) {
159 if (!logger.isErrorEnabled()) {
160 return;
161 }
162 String translatedMsg = imc.getMessage(key, args);
163 MessageParameterObj mpo = new MessageParameterObj(key, args);
164
165 if (instanceofLAL) {
166 ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.ERROR_INT, translatedMsg, args, null);
167 } else {
168 logger.error(LOCALIZED, translatedMsg, mpo);
169 }
170 }
171
172 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n;
25
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import ch.qos.cal10n.IMessageConveyor;
30
31 /**
32 *
33 * This class is essentially a wrapper around an {@link LoggerFactory} producing
34 * {@link LocLogger} instances.
35 *
36 * <p>
37 * Contrary to {@link LoggerFactory#getLogger(String)} method of
38 * {@link LoggerFactory}, each call to {@link getLocLogger} produces a new
39 * instance of {@link LocLogger}. This should not matter because a LocLogger
40 * instance does have any state beyond that of the {@link Logger} in stance it
41 * wraps and its message conveyor.
42 *
43 * @author Ceki G&uuml;c&uuml;
44 *
45 */
46 public class LocLoggerFactory {
47
48 final IMessageConveyor imc;
49
50 public LocLoggerFactory(IMessageConveyor imc) {
51 this.imc = imc;
52 }
53
54 /**
55 * Get an LocLogger instance by name.
56 *
57 * @param name
58 * @return LocLogger instance by name.
59 */
60 public LocLogger getLocLogger(String name) {
61 return new LocLogger(LoggerFactory.getLogger(name), imc);
62 }
63
64 /**
65 * Get a new LocLogger instance by class. The returned LocLogger will be named
66 * after the class.
67 *
68 * @param clazz
69 * @return LocLogger instance by class
70 */
71 public LocLogger getLocLogger(Class<?> clazz) {
72 return getLocLogger(clazz.getName());
73 }
74 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>SLF4J API extensions</p>
10 </body>
11 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import java.io.Serializable;
27 import java.io.ByteArrayInputStream;
28 import java.io.ByteArrayOutputStream;
29 import java.util.Date;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.Map;
33 import java.beans.XMLDecoder;
34 import java.beans.XMLEncoder;
35 import java.beans.ExceptionListener;
36
37 /**
38 * Base class for Event Data. Event Data contains data to be logged about an
39 * event. Users may extend this class for each EventType they want to log.
40 *
41 * @author Ralph Goers
42 */
43 public class EventData implements Serializable {
44
45 private static final long serialVersionUID = 153270778642103985L;
46
47 private Map<String, Object> eventData = new HashMap<String, Object>();
48 public static final String EVENT_MESSAGE = "EventMessage";
49 public static final String EVENT_TYPE = "EventType";
50 public static final String EVENT_DATETIME = "EventDateTime";
51 public static final String EVENT_ID = "EventId";
52
53 /**
54 * Default Constructor
55 */
56 public EventData() {
57 }
58
59 /**
60 * Constructor to create event data from a Map.
61 *
62 * @param map
63 * The event data.
64 */
65 public EventData(Map<String, Object> map) {
66 eventData.putAll(map);
67 }
68
69 /**
70 * Construct from a serialized form of the Map containing the RequestInfo
71 * elements
72 *
73 * @param xml
74 * The serialized form of the RequestInfo Map.
75 */
76 @SuppressWarnings("unchecked")
77 public EventData(String xml) {
78 ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
79 try {
80 XMLDecoder decoder = new XMLDecoder(bais);
81 this.eventData = (Map<String, Object>) decoder.readObject();
82 } catch (Exception e) {
83 throw new EventException("Error decoding " + xml, e);
84 }
85 }
86
87 /**
88 * Serialize all the EventData items into an XML representation.
89 *
90 * @return an XML String containing all the EventDAta items.
91 */
92 public String toXML() {
93 return toXML(eventData);
94 }
95
96 /**
97 * Serialize all the EventData items into an XML representation.
98 *
99 * @param map the Map to transform
100 * @return an XML String containing all the EventDAta items.
101 */
102 public static String toXML(Map<String, Object> map) {
103 ByteArrayOutputStream baos = new ByteArrayOutputStream();
104 try {
105 XMLEncoder encoder = new XMLEncoder(baos);
106 encoder.setExceptionListener(new ExceptionListener() {
107 public void exceptionThrown(Exception exception) {
108 exception.printStackTrace();
109 }
110 });
111 encoder.writeObject(map);
112 encoder.close();
113 return baos.toString();
114 } catch (Exception e) {
115 e.printStackTrace();
116 return null;
117 }
118 }
119
120 /**
121 * Retrieve the event identifier.
122 *
123 * @return The event identifier
124 */
125 public String getEventId() {
126 return (String) this.eventData.get(EVENT_ID);
127 }
128
129 /**
130 * Set the event identifier.
131 *
132 * @param eventId
133 * The event identifier.
134 */
135 public void setEventId(String eventId) {
136 if (eventId == null) {
137 throw new IllegalArgumentException("eventId cannot be null");
138 }
139 this.eventData.put(EVENT_ID, eventId);
140 }
141
142 /**
143 * Retrieve the message text associated with this event, if any.
144 *
145 * @return The message text associated with this event or null if there is
146 * none.
147 */
148 public String getMessage() {
149 return (String) this.eventData.get(EVENT_MESSAGE);
150 }
151
152 /**
153 * Set the message text associated with this event.
154 *
155 * @param message
156 * The message text.
157 */
158 public void setMessage(String message) {
159 this.eventData.put(EVENT_MESSAGE, message);
160 }
161
162 /**
163 * Retrieve the date and time the event occurred.
164 *
165 * @return The Date associated with the event.
166 */
167 public Date getEventDateTime() {
168 return (Date) this.eventData.get(EVENT_DATETIME);
169 }
170
171 /**
172 * Set the date and time the event occurred in case it is not the same as when
173 * the event was logged.
174 *
175 * @param eventDateTime
176 * The event Date.
177 */
178 public void setEventDateTime(Date eventDateTime) {
179 this.eventData.put(EVENT_DATETIME, eventDateTime);
180 }
181
182 /**
183 * Set the type of event that occurred.
184 *
185 * @param eventType
186 * The type of the event.
187 */
188 public void setEventType(String eventType) {
189 this.eventData.put(EVENT_TYPE, eventType);
190 }
191
192 /**
193 * Retrieve the type of the event.
194 *
195 * @return The event type.
196 */
197 public String getEventType() {
198 return (String) this.eventData.get(EVENT_TYPE);
199 }
200
201 /**
202 * Add arbitrary attributes about the event.
203 *
204 * @param name
205 * The attribute's key.
206 * @param obj
207 * The data associated with the key.
208 */
209 public void put(String name, Serializable obj) {
210 this.eventData.put(name, obj);
211 }
212
213 /**
214 * Retrieve an event attribute.
215 *
216 * @param name
217 * The attribute's key.
218 * @return The value associated with the key or null if the key is not
219 * present.
220 */
221 public Serializable get(String name) {
222 return (Serializable) this.eventData.get(name);
223 }
224
225 /**
226 * Populate the event data from a Map.
227 *
228 * @param data
229 * The Map to copy.
230 */
231 public void putAll(Map<String, Object> data) {
232 this.eventData.putAll(data);
233 }
234
235 /**
236 * Returns the number of attributes in the EventData.
237 *
238 * @return the number of attributes in the EventData.
239 */
240 public int getSize() {
241 return this.eventData.size();
242 }
243
244 /**
245 * Returns an Iterator over all the entries in the EventDAta.
246 *
247 * @return an Iterator that can be used to access all the event attributes.
248 */
249 public Iterator<Map.Entry<String, Object>> getEntrySetIterator() {
250 return this.eventData.entrySet().iterator();
251 }
252
253 /**
254 * Retrieve all the attributes in the EventData as a Map. Changes to this map
255 * will be reflected in the EventData.
256 *
257 * @return The Map of attributes in this EventData instance.
258 */
259 public Map<String, Object> getEventMap() {
260 return this.eventData;
261 }
262
263 /**
264 * Convert the EventData to a String.
265 *
266 * @return The EventData as a String.
267 */
268 @Override
269 public String toString() {
270 return toXML();
271 }
272
273 /**
274 * Compare two EventData objects for equality.
275 *
276 * @param o
277 * The Object to compare.
278 * @return true if the objects are the same instance or contain all the same
279 * keys and their values.
280 */
281 @SuppressWarnings("unchecked")
282 @Override
283 public boolean equals(Object o) {
284 if (this == o) {
285 return true;
286 }
287 if (!(o instanceof EventData || o instanceof Map)) {
288 return false;
289 }
290 Map<String, Object> map = (o instanceof EventData) ? ((EventData) o).getEventMap() : (Map<String, Object>) o;
291
292 return this.eventData.equals(map);
293 }
294
295 /**
296 * Compute the hashCode for this EventData instance.
297 *
298 * @return The hashcode for this EventData instance.
299 */
300 @Override
301 public int hashCode() {
302 return this.eventData.hashCode();
303 }
304 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 /**
27 * Exception used to identify issues related to an event that is being logged.
28 */
29 public class EventException extends RuntimeException {
30
31 private static final long serialVersionUID = -22873966112391992L;
32
33 /**
34 * Default constructor.
35 */
36 public EventException() {
37 super();
38 }
39
40 /**
41 * Constructor that allows an exception message.
42 * @param exceptionMessage The exception message.
43 */
44 public EventException(String exceptionMessage) {
45 super(exceptionMessage);
46 }
47
48 /**
49 * Constructor that chains another Exception or Error.
50 * @param originalException The original exception.
51 */
52 public EventException(Throwable originalException) {
53 super(originalException);
54 }
55
56 /**
57 * Constructor that chains another Exception or Error and also allows a message
58 * to be specified.
59 * @param exceptionMessage The exception message.
60 * @param originalException The original excepton.
61 */
62 public EventException(String exceptionMessage, Throwable originalException) {
63 super(exceptionMessage, originalException);
64 }
65 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.LoggerFactory;
27 import org.slf4j.Marker;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.spi.LocationAwareLogger;
30
31 /**
32 * Simple Logger used to log events. All events are directed to a logger named "EventLogger"
33 * with a level of INFO and with an Event marker.
34 *
35 * @author Ralph Goers
36 */
37 public class EventLogger {
38
39 private static final String FQCN = EventLogger.class.getName();
40
41 static Marker EVENT_MARKER = MarkerFactory.getMarker("EVENT");
42
43 private static LoggerWrapper eventLogger = new LoggerWrapper(LoggerFactory.getLogger("EventLogger"), FQCN);
44
45 /**
46 * There can only be a single EventLogger.
47 */
48 private EventLogger() {
49 }
50
51 /**
52 * Logs the event.
53 *
54 * @param data The EventData.
55 */
56 public static void logEvent(EventData data) {
57 if (eventLogger.instanceofLAL) {
58 ((LocationAwareLogger) eventLogger.logger).log(EVENT_MARKER, FQCN, LocationAwareLogger.INFO_INT, data.toXML(), new Object[] { data }, null);
59 } else {
60 eventLogger.logger.info(EVENT_MARKER, data.toXML(), data);
61 }
62 }
63 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28 import org.slf4j.helpers.FormattingTuple;
29 import org.slf4j.helpers.MessageFormatter;
30 import org.slf4j.spi.LocationAwareLogger;
31
32 /**
33 * A helper class wrapping an {@link org.slf4j.Logger} instance preserving
34 * location information if the wrapped instance supports it.
35 *
36 * @author Ralph Goers
37 * @author Ceki G&uuml;lc&uuml;
38 */
39 public class LoggerWrapper implements Logger {
40
41 // To ensure consistency between two instances sharing the same name
42 // (homonyms)
43 // a LoggerWrapper should not contain any state beyond
44 // the Logger instance it wraps.
45 // Note that 'instanceofLAL' directly depends on Logger.
46 // fqcn depend on the caller, but its value would not be different
47 // between successive invocations of a factory class
48
49 protected final Logger logger;
50 final String fqcn;
51 // is this logger instance a LocationAwareLogger
52 protected final boolean instanceofLAL;
53
54 public LoggerWrapper(Logger logger, String fqcn) {
55 this.logger = logger;
56 this.fqcn = fqcn;
57 if (logger instanceof LocationAwareLogger) {
58 instanceofLAL = true;
59 } else {
60 instanceofLAL = false;
61 }
62 }
63
64 /**
65 * Delegate to the appropriate method of the underlying logger.
66 */
67 public boolean isTraceEnabled() {
68 return logger.isTraceEnabled();
69 }
70
71 /**
72 * Delegate to the appropriate method of the underlying logger.
73 */
74 public boolean isTraceEnabled(Marker marker) {
75 return logger.isTraceEnabled(marker);
76 }
77
78 /**
79 * Delegate to the appropriate method of the underlying logger.
80 */
81 public void trace(String msg) {
82 if (!logger.isTraceEnabled())
83 return;
84
85 if (instanceofLAL) {
86 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null);
87 } else {
88 logger.trace(msg);
89 }
90 }
91
92 /**
93 * Delegate to the appropriate method of the underlying logger.
94 */
95 public void trace(String format, Object arg) {
96 if (!logger.isTraceEnabled())
97 return;
98
99 if (instanceofLAL) {
100 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
101 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg }, null);
102 } else {
103 logger.trace(format, arg);
104 }
105 }
106
107 /**
108 * Delegate to the appropriate method of the underlying logger.
109 */
110 public void trace(String format, Object arg1, Object arg2) {
111 if (!logger.isTraceEnabled())
112 return;
113
114 if (instanceofLAL) {
115 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
116 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
117 } else {
118 logger.trace(format, arg1, arg2);
119 }
120 }
121
122 /**
123 * Delegate to the appropriate method of the underlying logger.
124 */
125 public void trace(String format, Object... args) {
126 if (!logger.isTraceEnabled())
127 return;
128
129 if (instanceofLAL) {
130 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
131 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null);
132 } else {
133 logger.trace(format, args);
134 }
135 }
136
137 /**
138 * Delegate to the appropriate method of the underlying logger.
139 */
140 public void trace(String msg, Throwable t) {
141 if (!logger.isTraceEnabled())
142 return;
143
144 if (instanceofLAL) {
145 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, t);
146 } else {
147 logger.trace(msg, t);
148 }
149 }
150
151 /**
152 * Delegate to the appropriate method of the underlying logger.
153 */
154 public void trace(Marker marker, String msg) {
155 if (!logger.isTraceEnabled(marker))
156 return;
157 if (instanceofLAL) {
158 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null);
159 } else {
160 logger.trace(marker, msg);
161 }
162 }
163
164 /**
165 * Delegate to the appropriate method of the underlying logger.
166 */
167 public void trace(Marker marker, String format, Object arg) {
168 if (!logger.isTraceEnabled(marker))
169 return;
170 if (instanceofLAL) {
171 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
172 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg }, null);
173 } else {
174 logger.trace(marker, format, arg);
175 }
176 }
177
178 /**
179 * Delegate to the appropriate method of the underlying logger.
180 */
181 public void trace(Marker marker, String format, Object arg1, Object arg2) {
182 if (!logger.isTraceEnabled(marker))
183 return;
184 if (instanceofLAL) {
185 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
186 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
187 } else {
188 logger.trace(marker, format, arg1, arg2);
189 }
190 }
191
192 /**
193 * Delegate to the appropriate method of the underlying logger.
194 */
195 public void trace(Marker marker, String format, Object... args) {
196 if (!logger.isTraceEnabled(marker))
197 return;
198 if (instanceofLAL) {
199 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
200 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null);
201 } else {
202 logger.trace(marker, format, args);
203 }
204 }
205
206 /**
207 * Delegate to the appropriate method of the underlying logger.
208 */
209 public void trace(Marker marker, String msg, Throwable t) {
210 if (!logger.isTraceEnabled(marker))
211 return;
212 if (instanceofLAL) {
213 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, msg, null, t);
214 } else {
215 logger.trace(marker, msg, t);
216 }
217 }
218
219 /**
220 * Delegate to the appropriate method of the underlying logger.
221 */
222 public boolean isDebugEnabled() {
223 return logger.isDebugEnabled();
224 }
225
226 /**
227 * Delegate to the appropriate method of the underlying logger.
228 */
229 public boolean isDebugEnabled(Marker marker) {
230 return logger.isDebugEnabled(marker);
231 }
232
233 /**
234 * Delegate to the appropriate method of the underlying logger.
235 */
236 public void debug(String msg) {
237 if (!logger.isDebugEnabled())
238 return;
239
240 if (instanceofLAL) {
241 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null);
242 } else {
243 logger.debug(msg);
244 }
245 }
246
247 /**
248 * Delegate to the appropriate method of the underlying logger.
249 */
250 public void debug(String format, Object arg) {
251 if (!logger.isDebugEnabled())
252 return;
253
254 if (instanceofLAL) {
255 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
256 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg }, null);
257 } else {
258 logger.debug(format, arg);
259 }
260 }
261
262 /**
263 * Delegate to the appropriate method of the underlying logger.
264 */
265 public void debug(String format, Object arg1, Object arg2) {
266 if (!logger.isDebugEnabled())
267 return;
268
269 if (instanceofLAL) {
270 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
271 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
272 } else {
273 logger.debug(format, arg1, arg2);
274 }
275 }
276
277 /**
278 * Delegate to the appropriate method of the underlying logger.
279 */
280 public void debug(String format, Object... argArray) {
281 if (!logger.isDebugEnabled())
282 return;
283
284 if (instanceofLAL) {
285 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
286 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), ft.getArgArray(), ft.getThrowable());
287 } else {
288 logger.debug(format, argArray);
289 }
290 }
291
292 /**
293 * Delegate to the appropriate method of the underlying logger.
294 */
295 public void debug(String msg, Throwable t) {
296 if (!logger.isDebugEnabled())
297 return;
298
299 if (instanceofLAL) {
300 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, t);
301 } else {
302 logger.debug(msg, t);
303 }
304 }
305
306 /**
307 * Delegate to the appropriate method of the underlying logger.
308 */
309 public void debug(Marker marker, String msg) {
310 if (!logger.isDebugEnabled(marker))
311 return;
312 if (instanceofLAL) {
313 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null);
314 } else {
315 logger.debug(marker, msg);
316 }
317 }
318
319 /**
320 * Delegate to the appropriate method of the underlying logger.
321 */
322 public void debug(Marker marker, String format, Object arg) {
323 if (!logger.isDebugEnabled(marker))
324 return;
325 if (instanceofLAL) {
326 FormattingTuple ft = MessageFormatter.format(format, arg);
327 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), ft.getArgArray(), ft.getThrowable());
328 } else {
329 logger.debug(marker, format, arg);
330 }
331 }
332
333 /**
334 * Delegate to the appropriate method of the underlying logger.
335 */
336 public void debug(Marker marker, String format, Object arg1, Object arg2) {
337 if (!logger.isDebugEnabled(marker))
338 return;
339 if (instanceofLAL) {
340 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
341 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
342 } else {
343 logger.debug(marker, format, arg1, arg2);
344 }
345 }
346
347 /**
348 * Delegate to the appropriate method of the underlying logger.
349 */
350 public void debug(Marker marker, String format, Object... argArray) {
351 if (!logger.isDebugEnabled(marker))
352 return;
353 if (instanceofLAL) {
354
355 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
356 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), argArray, ft.getThrowable());
357 } else {
358 logger.debug(marker, format, argArray);
359 }
360 }
361
362 /**
363 * Delegate to the appropriate method of the underlying logger.
364 */
365 public void debug(Marker marker, String msg, Throwable t) {
366 if (!logger.isDebugEnabled(marker))
367 return;
368 if (instanceofLAL) {
369 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, t);
370 } else {
371 logger.debug(marker, msg, t);
372 }
373 }
374
375 /**
376 * Delegate to the appropriate method of the underlying logger.
377 */
378 public boolean isInfoEnabled() {
379 return logger.isInfoEnabled();
380 }
381
382 /**
383 * Delegate to the appropriate method of the underlying logger.
384 */
385 public boolean isInfoEnabled(Marker marker) {
386 return logger.isInfoEnabled(marker);
387 }
388
389 /**
390 * Delegate to the appropriate method of the underlying logger.
391 */
392 public void info(String msg) {
393 if (!logger.isInfoEnabled())
394 return;
395
396 if (instanceofLAL) {
397 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, null);
398 } else {
399 logger.info(msg);
400 }
401 }
402
403 /**
404 * Delegate to the appropriate method of the underlying logger.
405 */
406 public void info(String format, Object arg) {
407 if (!logger.isInfoEnabled())
408 return;
409
410 if (instanceofLAL) {
411 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
412 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null);
413 } else {
414 logger.info(format, arg);
415 }
416 }
417
418 /**
419 * Delegate to the appropriate method of the underlying logger.
420 */
421 public void info(String format, Object arg1, Object arg2) {
422 if (!logger.isInfoEnabled())
423 return;
424
425 if (instanceofLAL) {
426 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
427 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
428 } else {
429 logger.info(format, arg1, arg2);
430 }
431 }
432
433 /**
434 * Delegate to the appropriate method of the underlying logger.
435 */
436 public void info(String format, Object... args) {
437 if (!logger.isInfoEnabled())
438 return;
439
440 if (instanceofLAL) {
441 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
442 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, args, null);
443 } else {
444 logger.info(format, args);
445 }
446 }
447
448 /**
449 * Delegate to the appropriate method of the underlying logger.
450 */
451 public void info(String msg, Throwable t) {
452 if (!logger.isInfoEnabled())
453 return;
454
455 if (instanceofLAL) {
456 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, t);
457 } else {
458 logger.info(msg, t);
459 }
460 }
461
462 /**
463 * Delegate to the appropriate method of the underlying logger.
464 */
465 public void info(Marker marker, String msg) {
466 if (!logger.isInfoEnabled(marker))
467 return;
468 if (instanceofLAL) {
469 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, msg, null, null);
470 } else {
471 logger.info(marker, msg);
472 }
473 }
474
475 /**
476 * Delegate to the appropriate method of the underlying logger.
477 */
478 public void info(Marker marker, String format, Object arg) {
479 if (!logger.isInfoEnabled(marker))
480 return;
481 if (instanceofLAL) {
482 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
483 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null);
484 } else {
485 logger.info(marker, format, arg);
486 }
487 }
488
489 /**
490 * Delegate to the appropriate method of the underlying logger.
491 */
492 public void info(Marker marker, String format, Object arg1, Object arg2) {
493 if (!logger.isInfoEnabled(marker))
494 return;
495 if (instanceofLAL) {
496 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
497 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
498 } else {
499 logger.info(marker, format, arg1, arg2);
500 }
501 }
502
503 /**
504 * Delegate to the appropriate method of the underlying logger.
505 */
506 public void info(Marker marker, String format, Object... args) {
507 if (!logger.isInfoEnabled(marker))
508 return;
509 if (instanceofLAL) {
510 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
511 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, args, null);
512 } else {
513 logger.info(marker, format, args);
514 }
515 }
516
517 /**
518 * Delegate to the appropriate method of the underlying logger.
519 */
520 public void info(Marker marker, String msg, Throwable t) {
521 if (!logger.isInfoEnabled(marker))
522 return;
523 if (instanceofLAL) {
524 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, msg, null, t);
525 } else {
526 logger.info(marker, msg, t);
527 }
528 }
529
530 public boolean isWarnEnabled() {
531 return logger.isWarnEnabled();
532 }
533
534 /**
535 * Delegate to the appropriate method of the underlying logger.
536 */
537 public boolean isWarnEnabled(Marker marker) {
538 return logger.isWarnEnabled(marker);
539 }
540
541 /**
542 * Delegate to the appropriate method of the underlying logger.
543 */
544 public void warn(String msg) {
545 if (!logger.isWarnEnabled())
546 return;
547
548 if (instanceofLAL) {
549 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, null);
550 } else {
551 logger.warn(msg);
552 }
553 }
554
555 /**
556 * Delegate to the appropriate method of the underlying logger.
557 */
558 public void warn(String format, Object arg) {
559 if (!logger.isWarnEnabled())
560 return;
561
562 if (instanceofLAL) {
563 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
564 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg }, null);
565 } else {
566 logger.warn(format, arg);
567 }
568 }
569
570 /**
571 * Delegate to the appropriate method of the underlying logger.
572 */
573 public void warn(String format, Object arg1, Object arg2) {
574 if (!logger.isWarnEnabled())
575 return;
576
577 if (instanceofLAL) {
578 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
579 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
580 } else {
581 logger.warn(format, arg1, arg2);
582 }
583 }
584
585 /**
586 * Delegate to the appropriate method of the underlying logger.
587 */
588 public void warn(String format, Object... args) {
589 if (!logger.isWarnEnabled())
590 return;
591
592 if (instanceofLAL) {
593 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
594 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, args, null);
595 } else {
596 logger.warn(format, args);
597 }
598 }
599
600 /**
601 * Delegate to the appropriate method of the underlying logger.
602 */
603 public void warn(String msg, Throwable t) {
604 if (!logger.isWarnEnabled())
605 return;
606
607 if (instanceofLAL) {
608 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, t);
609 } else {
610 logger.warn(msg, t);
611 }
612 }
613
614 /**
615 * Delegate to the appropriate method of the underlying logger.
616 */
617 public void warn(Marker marker, String msg) {
618 if (!logger.isWarnEnabled(marker))
619 return;
620 if (instanceofLAL) {
621 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, msg, null, null);
622 } else {
623 logger.warn(marker, msg);
624 }
625 }
626
627 /**
628 * Delegate to the appropriate method of the underlying logger.
629 */
630 public void warn(Marker marker, String format, Object arg) {
631 if (!logger.isWarnEnabled(marker))
632 return;
633 if (instanceofLAL) {
634 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
635 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg }, null);
636 } else {
637 logger.warn(marker, format, arg);
638 }
639 }
640
641 /**
642 * Delegate to the appropriate method of the underlying logger.
643 */
644 public void warn(Marker marker, String format, Object arg1, Object arg2) {
645 if (!logger.isWarnEnabled(marker))
646 return;
647 if (instanceofLAL) {
648 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
649 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
650 } else {
651 logger.warn(marker, format, arg1, arg2);
652 }
653 }
654
655 /**
656 * Delegate to the appropriate method of the underlying logger.
657 */
658 public void warn(Marker marker, String format, Object... args) {
659 if (!logger.isWarnEnabled(marker))
660 return;
661 if (instanceofLAL) {
662 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
663 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, args, null);
664 } else {
665 logger.warn(marker, format, args);
666 }
667 }
668
669 /**
670 * Delegate to the appropriate method of the underlying logger.
671 */
672 public void warn(Marker marker, String msg, Throwable t) {
673 if (!logger.isWarnEnabled(marker))
674 return;
675 if (instanceofLAL) {
676 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, msg, null, t);
677 } else {
678 logger.warn(marker, msg, t);
679 }
680 }
681
682 /**
683 * Delegate to the appropriate method of the underlying logger.
684 */
685 public boolean isErrorEnabled() {
686 return logger.isErrorEnabled();
687 }
688
689 /**
690 * Delegate to the appropriate method of the underlying logger.
691 */
692 public boolean isErrorEnabled(Marker marker) {
693 return logger.isErrorEnabled(marker);
694 }
695
696 /**
697 * Delegate to the appropriate method of the underlying logger.
698 */
699 public void error(String msg) {
700 if (!logger.isErrorEnabled())
701 return;
702
703 if (instanceofLAL) {
704 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null);
705 } else {
706 logger.error(msg);
707 }
708 }
709
710 /**
711 * Delegate to the appropriate method of the underlying logger.
712 */
713 public void error(String format, Object arg) {
714 if (!logger.isErrorEnabled())
715 return;
716
717 if (instanceofLAL) {
718 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
719 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg }, null);
720 } else {
721 logger.error(format, arg);
722 }
723 }
724
725 /**
726 * Delegate to the appropriate method of the underlying logger.
727 */
728 public void error(String format, Object arg1, Object arg2) {
729 if (!logger.isErrorEnabled())
730 return;
731
732 if (instanceofLAL) {
733 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
734 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
735 } else {
736 logger.error(format, arg1, arg2);
737 }
738 }
739
740 /**
741 * Delegate to the appropriate method of the underlying logger.
742 */
743 public void error(String format, Object... args) {
744 if (!logger.isErrorEnabled())
745 return;
746
747 if (instanceofLAL) {
748 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
749 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, args, null);
750 } else {
751 logger.error(format, args);
752 }
753 }
754
755 /**
756 * Delegate to the appropriate method of the underlying logger.
757 */
758 public void error(String msg, Throwable t) {
759 if (!logger.isErrorEnabled())
760 return;
761
762 if (instanceofLAL) {
763 ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t);
764 } else {
765 logger.error(msg, t);
766 }
767 }
768
769 /**
770 * Delegate to the appropriate method of the underlying logger.
771 */
772 public void error(Marker marker, String msg) {
773 if (!logger.isErrorEnabled(marker))
774 return;
775 if (instanceofLAL) {
776 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null);
777 } else {
778 logger.error(marker, msg);
779 }
780 }
781
782 /**
783 * Delegate to the appropriate method of the underlying logger.
784 */
785 public void error(Marker marker, String format, Object arg) {
786 if (!logger.isErrorEnabled(marker))
787 return;
788 if (instanceofLAL) {
789 String formattedMessage = MessageFormatter.format(format, arg).getMessage();
790 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg }, null);
791 } else {
792 logger.error(marker, format, arg);
793 }
794 }
795
796 /**
797 * Delegate to the appropriate method of the underlying logger.
798 */
799 public void error(Marker marker, String format, Object arg1, Object arg2) {
800 if (!logger.isErrorEnabled(marker))
801 return;
802 if (instanceofLAL) {
803 String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
804 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
805 } else {
806 logger.error(marker, format, arg1, arg2);
807 }
808 }
809
810 /**
811 * Delegate to the appropriate method of the underlying logger.
812 */
813 public void error(Marker marker, String format, Object... args) {
814 if (!logger.isErrorEnabled(marker))
815 return;
816 if (instanceofLAL) {
817 String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
818 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, args, null);
819 } else {
820 logger.error(marker, format, args);
821 }
822 }
823
824 /**
825 * Delegate to the appropriate method of the underlying logger.
826 */
827 public void error(Marker marker, String msg, Throwable t) {
828 if (!logger.isErrorEnabled(marker))
829 return;
830 if (instanceofLAL) {
831 ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t);
832 } else {
833 logger.error(marker, msg, t);
834 }
835 }
836
837 /**
838 * Delegate to the appropriate method of the underlying logger.
839 */
840 public String getName() {
841 return logger.getName();
842 }
843 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.apache.commons.lang.text.StrLookup;
27 import org.slf4j.MDC;
28
29 /**
30 * This class can be used with the Commons Lang StrSubstitutor to replace
31 * tokens that occur in Strings with their values in the MDC.
32 *
33 * @author Ralph Goers
34 */
35 public class MDCStrLookup extends StrLookup {
36 /**
37 * Looks up up a value in the MDC.
38 *
39 * @param key the key to be looked up, may be null
40 * @return the matching value, null if no match
41 */
42 public String lookup(String key) {
43 if (key == null) {
44 return null;
45 }
46 return MDC.get(key);
47 }
48 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.Logger;
27 import org.slf4j.Marker;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.helpers.FormattingTuple;
30 import org.slf4j.helpers.MessageFormatter;
31 import org.slf4j.spi.LocationAwareLogger;
32
33 /**
34 * A utility that provides standard mechanisms for logging certain kinds of
35 * activities.
36 *
37 * @author Ralph Goers
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public class XLogger extends LoggerWrapper implements Logger {
41
42 private static final String FQCN = XLogger.class.getName();
43 static Marker FLOW_MARKER = MarkerFactory.getMarker("FLOW");
44 static Marker ENTRY_MARKER = MarkerFactory.getMarker("ENTRY");
45 static Marker EXIT_MARKER = MarkerFactory.getMarker("EXIT");
46
47 static Marker EXCEPTION_MARKER = MarkerFactory.getMarker("EXCEPTION");
48 static Marker THROWING_MARKER = MarkerFactory.getMarker("THROWING");
49 static Marker CATCHING_MARKER = MarkerFactory.getMarker("CATCHING");
50
51 static String EXIT_MESSAGE_0 = "exit";
52 static String EXIT_MESSAGE_1 = "exit with ({})";
53
54 static String ENTRY_MESSAGE_0 = "entry";
55 static String ENTRY_MESSAGE_1 = "entry with ({})";
56 static String ENTRY_MESSAGE_2 = "entry with ({}, {})";
57 static String ENTRY_MESSAGE_3 = "entry with ({}, {}, {})";
58 static String ENTRY_MESSAGE_4 = "entry with ({}, {}, {}, {})";
59 static int ENTRY_MESSAGE_ARRAY_LEN = 5;
60 static String[] ENTRY_MESSAGE_ARRAY = new String[ENTRY_MESSAGE_ARRAY_LEN];
61 static {
62 ENTRY_MARKER.add(FLOW_MARKER);
63 EXIT_MARKER.add(FLOW_MARKER);
64 THROWING_MARKER.add(EXCEPTION_MARKER);
65 CATCHING_MARKER.add(EXCEPTION_MARKER);
66
67 ENTRY_MESSAGE_ARRAY[0] = ENTRY_MESSAGE_0;
68 ENTRY_MESSAGE_ARRAY[1] = ENTRY_MESSAGE_1;
69 ENTRY_MESSAGE_ARRAY[2] = ENTRY_MESSAGE_2;
70 ENTRY_MESSAGE_ARRAY[3] = ENTRY_MESSAGE_3;
71 ENTRY_MESSAGE_ARRAY[4] = ENTRY_MESSAGE_4;
72 }
73
74 public enum Level {
75 TRACE("TRACE", LocationAwareLogger.TRACE_INT), DEBUG("DEBUG", LocationAwareLogger.DEBUG_INT), INFO("INFO", LocationAwareLogger.INFO_INT), WARN("WARN",
76 LocationAwareLogger.WARN_INT), ERROR("ERROR", LocationAwareLogger.ERROR_INT);
77
78 private final String name;
79 private final int level;
80
81 public String toString() {
82 return this.name;
83 }
84
85 public int intValue() {
86 return this.level;
87 }
88
89 private Level(String name, int level) {
90 this.name = name;
91 this.level = level;
92 }
93 }
94
95 /**
96 * Given an underlying logger, construct an XLogger
97 *
98 * @param logger
99 * underlying logger
100 */
101 public XLogger(Logger logger) {
102 // If class B extends A, assuming B does not override method x(), the caller
103 // of new B().x() is A and not B, see also
104 // http://bugzilla.slf4j.org/show_bug.cgi?id=114
105 super(logger, LoggerWrapper.class.getName());
106 }
107
108 /**
109 * Log method entry.
110 *
111 * @param argArray
112 * supplied parameters
113 */
114 public void entry(Object... argArray) {
115 if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
116 String messagePattern = null;
117 if (argArray.length < ENTRY_MESSAGE_ARRAY_LEN) {
118 messagePattern = ENTRY_MESSAGE_ARRAY[argArray.length];
119 } else {
120 messagePattern = buildMessagePattern(argArray.length);
121 }
122 FormattingTuple tp = MessageFormatter.arrayFormat(messagePattern, argArray);
123 ((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), argArray, tp.getThrowable());
124 }
125 }
126
127 /**
128 * Log method exit
129 */
130 public void exit() {
131 if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
132 ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, EXIT_MESSAGE_0, null, null);
133 }
134 }
135
136 /**
137 * Log method exit
138 *
139 * @param result
140 * The result of the method being exited
141 */
142 public <T> T exit(T result) {
143 if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) {
144 FormattingTuple tp = MessageFormatter.format(EXIT_MESSAGE_1, result);
145 ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), new Object[] { result }, tp.getThrowable());
146 }
147 return result;
148 }
149
150 /**
151 * Log an exception being thrown. The generated log event uses Level ERROR.
152 *
153 * @param throwable
154 * the exception being caught.
155 */
156 public <T extends Throwable> T throwing(T throwable) {
157 if (instanceofLAL) {
158 ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "throwing", null, throwable);
159 }
160 return throwable;
161 }
162
163 /**
164 * Log an exception being thrown allowing the log level to be specified.
165 *
166 * @param level
167 * the logging level to use.
168 * @param throwable
169 * the exception being caught.
170 */
171 public <T extends Throwable> T throwing(Level level, T throwable) {
172 if (instanceofLAL) {
173 ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, level.level, "throwing", null, throwable);
174 }
175 return throwable;
176 }
177
178 /**
179 * Log an exception being caught. The generated log event uses Level ERROR.
180 *
181 * @param throwable
182 * the exception being caught.
183 */
184 public void catching(Throwable throwable) {
185 if (instanceofLAL) {
186 ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "catching", null, throwable);
187 }
188 }
189
190 /**
191 * Log an exception being caught allowing the log level to be specified.
192 *
193 * @param level
194 * the logging level to use.
195 * @param throwable
196 * the exception being caught.
197 */
198 public void catching(Level level, Throwable throwable) {
199 if (instanceofLAL) {
200 ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, level.level, "catching", null, throwable);
201 }
202 }
203
204 private static String buildMessagePattern(int len) {
205 StringBuilder sb = new StringBuilder();
206 sb.append(" entry with (");
207 for (int i = 0; i < len; i++) {
208 sb.append("{}");
209 if (i != len - 1)
210 sb.append(", ");
211 }
212 sb.append(')');
213 return sb.toString();
214 }
215 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.ext;
25
26 import org.slf4j.LoggerFactory;
27
28 /**
29 *
30 * This class is essentially a wrapper around an
31 * {@link LoggerFactory} producing {@link XLogger} instances.
32 *
33 * <p>Contrary to {@link LoggerFactory#getLogger(String)} method of
34 * {@link LoggerFactory}, each call to {@link #getXLogger(String)}
35 * produces a new instance of <code>XLogger</code>. This should not matter
36 * because an <code>XLogger</code> instance does not have any state beyond that of
37 * the {@link org.slf4j.Logger Logger} instance it wraps.
38 *
39 * @author Ralph Goers
40 * @author Ceki G&uuml;lc&uuml;
41 */
42 public class XLoggerFactory {
43
44 /**
45 * Get an XLogger instance by name.
46 *
47 * @param name
48 * @return XLogger instance
49 */
50 public static XLogger getXLogger(String name) {
51 return new XLogger(LoggerFactory.getLogger(name));
52 }
53
54 /**
55 * Get a new XLogger instance by class. The returned XLogger
56 * will be named after the class.
57 *
58 * @param clazz
59 * @return XLogger instance by name
60 */
61 public static XLogger getXLogger(Class<?> clazz) {
62 return getXLogger(clazz.getName());
63 }
64 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>Localized logging using the <a href="http://cal10n.qos.ch">CAL10N</a> API.</p>
10 </body>
11 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.instrumentation;
25
26 import javassist.CtBehavior;
27 import javassist.CtClass;
28 import javassist.CtMethod;
29 import javassist.Modifier;
30 import javassist.NotFoundException;
31 import javassist.bytecode.AttributeInfo;
32 import javassist.bytecode.CodeAttribute;
33 import javassist.bytecode.LocalVariableAttribute;
34
35 /**
36 * Helper methods for Javassist functionality.
37 *
38 */
39 public class JavassistHelper {
40
41 /**
42 * Create a javaassist source snippet which either is empty (for anything
43 * which does not return a value) or a explanatory text around the $_
44 * javaassist return value variable.
45 *
46 * @param method
47 * descriptor of method
48 * @return source snippet
49 * @throws NotFoundException
50 */
51 public static String returnValue(CtBehavior method) throws NotFoundException {
52
53 String returnValue = "";
54 if (methodReturnsValue(method)) {
55 returnValue = " returns: \" + $_ + \".";
56 }
57 return returnValue;
58 }
59
60 /**
61 * determine if the given method returns a value, and return true if so.
62 * false otherwise.
63 *
64 * @param method
65 * @return
66 * @throws NotFoundException
67 */
68 private static boolean methodReturnsValue(CtBehavior method) throws NotFoundException {
69
70 if (method instanceof CtMethod == false) {
71 return false;
72 }
73
74 CtClass returnType = ((CtMethod) method).getReturnType();
75 String returnTypeName = returnType.getName();
76
77 boolean isVoidMethod = "void".equals(returnTypeName);
78
79 boolean methodReturnsValue = isVoidMethod == false;
80 return methodReturnsValue;
81 }
82
83 /**
84 * Return javaassist source snippet which lists all the parameters and their
85 * values. If available the source names are extracted from the debug
86 * information and used, otherwise just a number is shown.
87 *
88 * @param method
89 * @return
90 * @throws NotFoundException
91 */
92 public static String getSignature(CtBehavior method) throws NotFoundException {
93
94 CtClass parameterTypes[] = method.getParameterTypes();
95
96 CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute();
97
98 LocalVariableAttribute locals = null;
99
100 if (codeAttribute != null) {
101 AttributeInfo attribute;
102 attribute = codeAttribute.getAttribute("LocalVariableTable");
103 locals = (LocalVariableAttribute) attribute;
104 }
105
106 String methodName = method.getName();
107
108 StringBuilder sb = new StringBuilder(methodName).append("(\" ");
109 for (int i = 0; i < parameterTypes.length; i++) {
110 if (i > 0) {
111 // add a comma and a space between printed values
112 sb.append(" + \", \" ");
113 }
114
115 CtClass parameterType = parameterTypes[i];
116 boolean isArray = parameterType.isArray();
117 CtClass arrayType = parameterType.getComponentType();
118 if (isArray) {
119 while (arrayType.isArray()) {
120 arrayType = arrayType.getComponentType();
121 }
122 }
123
124 sb.append(" + \"");
125 try {
126 sb.append(parameterNameFor(method, locals, i));
127 } catch (Exception e) {
128 sb.append(i + 1);
129 }
130 sb.append("\" + \"=");
131
132 if (parameterType.isPrimitive()) {
133 // let the compiler handle primitive -> string
134 sb.append("\"+ $").append(i + 1);
135 } else {
136 String s = "org.slf4j.instrumentation.ToStringHelper.render";
137 sb.append("\"+ ").append(s).append("($").append(i + 1).append(')');
138 }
139 }
140 sb.append("+\")");
141
142 String signature = sb.toString();
143 return signature;
144 }
145
146 /**
147 * Determine the name of parameter with index i in the given method. Use the
148 * locals attributes about local variables from the classfile. Note: This is
149 * still work in progress.
150 *
151 * @param method
152 * @param locals
153 * @param i
154 * @return the name of the parameter if available or a number if not.
155 */
156 static String parameterNameFor(CtBehavior method, LocalVariableAttribute locals, int i) {
157
158 if (locals == null) {
159 return Integer.toString(i + 1);
160 }
161
162 int modifiers = method.getModifiers();
163
164 int j = i;
165
166 if (Modifier.isSynchronized(modifiers)) {
167 // skip object to synchronize upon.
168 j++;
169 // System.err.println("Synchronized");
170 }
171 if (Modifier.isStatic(modifiers) == false) {
172 // skip "this"
173 j++;
174 // System.err.println("Instance");
175 }
176 String variableName = locals.variableName(j);
177 // if (variableName.equals("this")) {
178 // System.err.println("'this' returned as a parameter name for "
179 // + method.getName() + " index " + j
180 // +
181 // ", names are probably shifted. Please submit source for class in slf4j bugreport");
182 // }
183 return variableName;
184 }
185 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 /**
25 *
26 */
27 package org.slf4j.instrumentation;
28
29 import static org.slf4j.helpers.MessageFormatter.format;
30
31 import java.io.ByteArrayInputStream;
32 import java.lang.instrument.ClassFileTransformer;
33 import java.security.ProtectionDomain;
34
35 import javassist.CannotCompileException;
36 import javassist.ClassPool;
37 import javassist.CtBehavior;
38 import javassist.CtClass;
39 import javassist.CtField;
40 import javassist.NotFoundException;
41
42 import org.slf4j.helpers.MessageFormatter;
43
44 /**
45 * <p>
46 * LogTransformer does the work of analyzing each class, and if appropriate add
47 * log statements to each method to allow logging entry/exit.
48 * </p>
49 * <p>
50 * This class is based on the article <a href="http://today.java.net/pub/a/today/2008/04/24/add-logging-at-class-load-time-with-instrumentation.html"
51 * >Add Logging at Class Load Time with Java Instrumentation</a>.
52 * </p>
53 */
54 public class LogTransformer implements ClassFileTransformer {
55
56 /**
57 * Builder provides a flexible way of configuring some of many options on the
58 * parent class instead of providing many constructors.
59 *
60 * {@link http
61 * ://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html}
62 *
63 */
64 public static class Builder {
65
66 /**
67 * Build and return the LogTransformer corresponding to the options set in
68 * this Builder.
69 *
70 * @return
71 */
72 public LogTransformer build() {
73 if (verbose) {
74 System.err.println("Creating LogTransformer");
75 }
76 return new LogTransformer(this);
77 }
78
79 boolean addEntryExit;
80
81 /**
82 * Should each method log entry (with parameters) and exit (with parameters
83 * and returnvalue)?
84 *
85 * @param b
86 * value of flag
87 * @return
88 */
89 public Builder addEntryExit(boolean b) {
90 addEntryExit = b;
91 return this;
92 }
93
94 boolean addVariableAssignment;
95
96 // private Builder addVariableAssignment(boolean b) {
97 // System.err.println("cannot currently log variable assignments.");
98 // addVariableAssignment = b;
99 // return this;
100 // }
101
102 boolean verbose;
103
104 /**
105 * Should LogTransformer be verbose in what it does? This currently list the
106 * names of the classes being processed.
107 *
108 * @param b
109 * @return
110 */
111 public Builder verbose(boolean b) {
112 verbose = b;
113 return this;
114 }
115
116 String[] ignore = { "org/slf4j/", "ch/qos/logback/", "org/apache/log4j/" };
117
118 public Builder ignore(String[] strings) {
119 this.ignore = strings;
120 return this;
121 }
122
123 private String level = "info";
124
125 public Builder level(String level) {
126 level = level.toLowerCase();
127 if (level.equals("info") || level.equals("debug") || level.equals("trace")) {
128 this.level = level;
129 } else {
130 if (verbose) {
131 System.err.println("level not info/debug/trace : " + level);
132 }
133 }
134 return this;
135 }
136 }
137
138 private String level;
139 private String levelEnabled;
140
141 private LogTransformer(Builder builder) {
142 String s = "WARNING: javassist not available on classpath for javaagent, log statements will not be added";
143 try {
144 if (Class.forName("javassist.ClassPool") == null) {
145 System.err.println(s);
146 }
147 } catch (ClassNotFoundException e) {
148 System.err.println(s);
149 }
150
151 this.addEntryExit = builder.addEntryExit;
152 // this.addVariableAssignment = builder.addVariableAssignment;
153 this.verbose = builder.verbose;
154 this.ignore = builder.ignore;
155 this.level = builder.level;
156 this.levelEnabled = "is" + builder.level.substring(0, 1).toUpperCase() + builder.level.substring(1) + "Enabled";
157 }
158
159 private boolean addEntryExit;
160 // private boolean addVariableAssignment;
161 private boolean verbose;
162 private String[] ignore;
163
164 public byte[] transform(ClassLoader loader, String className, Class<?> clazz, ProtectionDomain domain, byte[] bytes) {
165
166 try {
167 return transform0(className, clazz, domain, bytes);
168 } catch (Exception e) {
169 System.err.println("Could not instrument " + className);
170 e.printStackTrace();
171 return bytes;
172 }
173 }
174
175 /**
176 * transform0 sees if the className starts with any of the namespaces to
177 * ignore, if so it is returned unchanged. Otherwise it is processed by
178 * doClass(...)
179 *
180 * @param className
181 * @param clazz
182 * @param domain
183 * @param bytes
184 * @return
185 */
186
187 private byte[] transform0(String className, Class<?> clazz, ProtectionDomain domain, byte[] bytes) {
188
189 try {
190 for (int i = 0; i < ignore.length; i++) {
191 if (className.startsWith(ignore[i])) {
192 return bytes;
193 }
194 }
195 String slf4jName = "org.slf4j.LoggerFactory";
196 try {
197 if (domain != null && domain.getClassLoader() != null) {
198 domain.getClassLoader().loadClass(slf4jName);
199 } else {
200 if (verbose) {
201 System.err.println("Skipping " + className + " as it doesn't have a domain or a class loader.");
202 }
203 return bytes;
204 }
205 } catch (ClassNotFoundException e) {
206 if (verbose) {
207 System.err.println("Skipping " + className + " as slf4j is not available to it");
208 }
209 return bytes;
210 }
211 if (verbose) {
212 System.err.println("Processing " + className);
213 }
214 return doClass(className, clazz, bytes);
215 } catch (Throwable e) {
216 System.out.println("e = " + e);
217 return bytes;
218 }
219 }
220
221 private String loggerName;
222
223 /**
224 * doClass() process a single class by first creates a class description from
225 * the byte codes. If it is a class (i.e. not an interface) the methods
226 * defined have bodies, and a static final logger object is added with the
227 * name of this class as an argument, and each method then gets processed with
228 * doMethod(...) to have logger calls added.
229 *
230 * @param name
231 * class name (slashes separate, not dots)
232 * @param clazz
233 * @param b
234 * @return
235 */
236 private byte[] doClass(String name, Class<?> clazz, byte[] b) {
237 ClassPool pool = ClassPool.getDefault();
238 CtClass cl = null;
239 try {
240 cl = pool.makeClass(new ByteArrayInputStream(b));
241 if (cl.isInterface() == false) {
242
243 loggerName = "_____log";
244
245 // We have to declare the log variable.
246
247 String pattern1 = "private static org.slf4j.Logger {};";
248 String loggerDefinition = format(pattern1, loggerName).getMessage();
249 CtField field = CtField.make(loggerDefinition, cl);
250
251 // and assign it the appropriate value.
252
253 String pattern2 = "org.slf4j.LoggerFactory.getLogger({}.class);";
254 String replace = name.replace('/', '.');
255 String getLogger = format(pattern2, replace).getMessage();
256
257 cl.addField(field, getLogger);
258
259 // then check every behaviour (which includes methods). We are
260 // only
261 // interested in non-empty ones, as they have code.
262 // NOTE: This will be changed, as empty methods should be
263 // instrumented too.
264
265 CtBehavior[] methods = cl.getDeclaredBehaviors();
266 for (int i = 0; i < methods.length; i++) {
267 if (methods[i].isEmpty() == false) {
268 doMethod(methods[i]);
269 }
270 }
271 b = cl.toBytecode();
272 }
273 } catch (Exception e) {
274 System.err.println("Could not instrument " + name + ", " + e);
275 e.printStackTrace(System.err);
276 } finally {
277 if (cl != null) {
278 cl.detach();
279 }
280 }
281 return b;
282 }
283
284 /**
285 * process a single method - this means add entry/exit logging if requested.
286 * It is only called for methods with a body.
287 *
288 * @param method
289 * method to work on
290 * @throws NotFoundException
291 * @throws CannotCompileException
292 */
293 private void doMethod(CtBehavior method) throws NotFoundException, CannotCompileException {
294
295 String signature = JavassistHelper.getSignature(method);
296 String returnValue = JavassistHelper.returnValue(method);
297
298 if (addEntryExit) {
299 String messagePattern = "if ({}.{}()) {}.{}(\">> {}\");";
300 Object[] arg1 = new Object[] { loggerName, levelEnabled, loggerName, level, signature };
301 String before = MessageFormatter.arrayFormat(messagePattern, arg1).getMessage();
302 // System.out.println(before);
303 method.insertBefore(before);
304
305 String messagePattern2 = "if ({}.{}()) {}.{}(\"<< {}{}\");";
306 Object[] arg2 = new Object[] { loggerName, levelEnabled, loggerName, level, signature, returnValue };
307 String after = MessageFormatter.arrayFormat(messagePattern2, arg2).getMessage();
308 // System.out.println(after);
309 method.insertAfter(after);
310 }
311 }
312 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.instrumentation;
25
26 import java.util.Map;
27 import java.util.WeakHashMap;
28
29 public class ToStringHelper {
30
31 /**
32 * Prefix to use at the start of the representation. Always used.
33 */
34 private static final String ARRAY_PREFIX = "[";
35
36 /**
37 * Suffix to use at the end of the representation. Always used.
38 */
39 private static final char ARRAY_SUFFIX = ']';
40
41 /**
42 * String separating each element when rendering an array. To be compatible
43 * with lists comma-space is used.
44 */
45
46 private static final char[] ELEMENT_SEPARATOR = ", ".toCharArray();
47
48 /**
49 * unrenderableClasses is essentially a Set of Class objects which has for
50 * some reason failed to render properly when invoked through a toString
51 * method call. To avoid memory leaks a data structure using weak references
52 * is needed, but unfortunately the runtime library does not contain a
53 * WeakHashSet class, so the behavior is emulated with a WeakHashmap with
54 * the class as the key, and a Long containing the value of
55 * System.currentTimeMilis when an instance of the class failed to render.
56 */
57
58 final static Map<Class<?>, Object> unrenderableClasses = new WeakHashMap<Class<?>, Object>();
59
60 /**
61 * Returns o.toString() unless it throws an exception (which causes it to be
62 * stored in unrenderableClasses) or already was present in
63 * unrenderableClasses. If so, the same string is returned as would have
64 * been returned by Object.toString(). Arrays get special treatment as they
65 * don't have usable toString methods.
66 *
67 * @param o
68 * incoming object to render.
69 * @return
70 */
71
72 public static String render(Object o) {
73 if (o == null) {
74 return String.valueOf(o);
75 }
76 Class<?> objectClass = o.getClass();
77
78 if (unrenderableClasses.containsKey(objectClass) == false) {
79 try {
80 if (objectClass.isArray()) {
81 return renderArray(o, objectClass).toString();
82 } else {
83 return o.toString();
84 }
85 } catch (Exception e) {
86 Long now = new Long(System.currentTimeMillis());
87
88 System.err.println("Disabling exception throwing class " + objectClass.getName() + ", " + e.getMessage());
89
90 unrenderableClasses.put(objectClass, now);
91 }
92 }
93 String name = o.getClass().getName();
94 return name + "@" + Integer.toHexString(o.hashCode());
95 }
96
97 /**
98 * renderArray returns an array similar to a List. If the array type is an
99 * object they are rendered with "render(object)" for each. If the array
100 * type is a primitive each element is added directly to the string buffer
101 * collecting the result.
102 *
103 * @param o
104 * @param objectClass
105 * @return
106 */
107 private static StringBuilder renderArray(Object o, Class<?> objectClass) {
108 Class<?> componentType = objectClass.getComponentType();
109 StringBuilder sb = new StringBuilder(ARRAY_PREFIX);
110
111 if (componentType.isPrimitive() == false) {
112 Object[] oa = (Object[]) o;
113 for (int i = 0; i < oa.length; i++) {
114 if (i > 0) {
115 sb.append(ELEMENT_SEPARATOR);
116 }
117 sb.append(render(oa[i]));
118 }
119 } else {
120 if (Boolean.TYPE.equals(componentType)) {
121 boolean[] ba = (boolean[]) o;
122 for (int i = 0; i < ba.length; i++) {
123 if (i > 0) {
124 sb.append(ELEMENT_SEPARATOR);
125 }
126 sb.append(ba[i]);
127 }
128 } else if (Integer.TYPE.equals(componentType)) {
129 int[] ia = (int[]) o;
130 for (int i = 0; i < ia.length; i++) {
131 if (i > 0) {
132 sb.append(ELEMENT_SEPARATOR);
133 }
134 sb.append(ia[i]);
135 }
136
137 } else if (Long.TYPE.equals(componentType)) {
138 long[] ia = (long[]) o;
139 for (int i = 0; i < ia.length; i++) {
140 if (i > 0) {
141 sb.append(ELEMENT_SEPARATOR);
142 }
143 sb.append(ia[i]);
144 }
145 } else if (Double.TYPE.equals(componentType)) {
146 double[] ia = (double[]) o;
147 for (int i = 0; i < ia.length; i++) {
148 if (i > 0) {
149 sb.append(ELEMENT_SEPARATOR);
150 }
151 sb.append(ia[i]);
152 }
153 } else if (Float.TYPE.equals(componentType)) {
154 float[] ia = (float[]) o;
155 for (int i = 0; i < ia.length; i++) {
156 if (i > 0) {
157 sb.append(ELEMENT_SEPARATOR);
158 }
159 sb.append(ia[i]);
160 }
161 } else if (Character.TYPE.equals(componentType)) {
162 char[] ia = (char[]) o;
163 for (int i = 0; i < ia.length; i++) {
164 if (i > 0) {
165 sb.append(ELEMENT_SEPARATOR);
166 }
167 sb.append(ia[i]);
168 }
169 } else if (Short.TYPE.equals(componentType)) {
170 short[] ia = (short[]) o;
171 for (int i = 0; i < ia.length; i++) {
172 if (i > 0) {
173 sb.append(ELEMENT_SEPARATOR);
174 }
175 sb.append(ia[i]);
176 }
177 } else if (Byte.TYPE.equals(componentType)) {
178 byte[] ia = (byte[]) o;
179 for (int i = 0; i < ia.length; i++) {
180 if (i > 0) {
181 sb.append(ELEMENT_SEPARATOR);
182 }
183 sb.append(ia[i]);
184 }
185 }
186 }
187 sb.append(ARRAY_SUFFIX);
188 return sb;
189 }
190 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9 <p>Java instrumentation routines for SLF4J.</p>
10
11 <p>Byte code instrumentation is an way to change behaviour of java
12 classes at <i>load time</i>. This is done in-between the original byte
13 codes are retrieved and the class object is constructed by the class
14 loader. Currently this depends on the javassist library from JBoss
15 (which in turn uses it extensively in their application server).</p>
16 </body>
17 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 * An enum of supported time units.
28 *
29 * @author Ceki
30 *
31 */
32 public enum DurationUnit {
33 NANOSECOND, MICROSECOND, MILLISSECOND, SECOND;
34 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.slf4j.Logger;
30 import org.slf4j.Marker;
31 import org.slf4j.MarkerFactory;
32
33 // + Profiler [BAS]
34 // |-- elapsed time [doX] 0 milliseconds.
35 // |-- elapsed time [doYYYYY] 56 milliseconds.
36 // |--+ Profiler Y
37 // |-- elapsed time [doZ] 21 milliseconds.
38 // |-- elapsed time [doZ] 21 milliseconds.
39 // |-- Total elapsed time [Y] 78 milliseconds.
40 // |-- elapsed time [doZ] 21 milliseconds.
41 // |-- Total elapsed time [BAS] 78 milliseconds.
42
43 /**
44 * A poor man's profiler to measure the time elapsed performing some lengthy
45 * task.
46 *
47 * @author Ceki G&uuml;lc&uuml;
48 */
49 public class Profiler implements TimeInstrument {
50
51 final static String PROFILER_MARKER_NAME = "PROFILER";
52
53 final static int MIN_SW_NAME_LENGTH = 24;
54 final static int MIN_SW_ELAPSED_TIME_NUMBER_LENGTH = 9;
55
56 final String name;
57 final StopWatch globalStopWatch;
58
59 List<TimeInstrument> childTimeInstrumentList = new ArrayList<TimeInstrument>();
60
61 // optional field
62 ProfilerRegistry profilerRegistry;
63 // optional field
64 Logger logger;
65
66 public Profiler(String name) {
67 this.name = name;
68 this.globalStopWatch = new StopWatch(name);
69 }
70
71 public String getName() {
72 return name;
73 }
74
75 public ProfilerRegistry getProfilerRegistry() {
76 return profilerRegistry;
77 }
78
79 public void registerWith(ProfilerRegistry profilerRegistry) {
80 if (profilerRegistry == null) {
81 return;
82 }
83 this.profilerRegistry = profilerRegistry;
84 profilerRegistry.put(this);
85 }
86
87 public Logger getLogger() {
88 return logger;
89 }
90
91 public void setLogger(Logger logger) {
92 this.logger = logger;
93 }
94
95 /**
96 * Starts a child stop watch and stops any previously started time
97 * instruments.
98 */
99 public void start(String name) {
100 stopLastTimeInstrument();
101 StopWatch childSW = new StopWatch(name);
102 childTimeInstrumentList.add(childSW);
103 }
104
105 public Profiler startNested(String name) {
106 stopLastTimeInstrument();
107 Profiler nestedProfiler = new Profiler(name);
108 nestedProfiler.registerWith(profilerRegistry);
109 nestedProfiler.setLogger(logger);
110 childTimeInstrumentList.add(nestedProfiler);
111 return nestedProfiler;
112 }
113
114 TimeInstrument getLastTimeInstrument() {
115 if (childTimeInstrumentList.size() > 0) {
116 return childTimeInstrumentList.get(childTimeInstrumentList.size() - 1);
117 } else {
118 return null;
119 }
120 }
121
122 void stopLastTimeInstrument() {
123 TimeInstrument last = getLastTimeInstrument();
124 if (last != null) {
125 last.stop();
126 }
127 }
128
129 // void stopNestedProfilers() {
130 // for (Object child : childTimeInstrumentList) {
131 // if (child instanceof Profiler)
132 // ((Profiler) child).stop();
133 // }
134 // }
135
136 public long elapsedTime() {
137 return globalStopWatch.elapsedTime();
138 }
139
140 public TimeInstrument stop() {
141 stopLastTimeInstrument();
142 globalStopWatch.stop();
143 return this;
144 }
145
146 public TimeInstrumentStatus getStatus() {
147 return globalStopWatch.status;
148 }
149
150 /**
151 * This method is used in tests.
152 */
153 void sanityCheck() throws IllegalStateException {
154 if (getStatus() != TimeInstrumentStatus.STOPPED) {
155 throw new IllegalStateException("time instrument [" + getName() + " is not stopped");
156 }
157
158 long totalElapsed = globalStopWatch.elapsedTime();
159 long childTotal = 0;
160
161 for (TimeInstrument ti : childTimeInstrumentList) {
162 childTotal += ti.elapsedTime();
163 if (ti.getStatus() != TimeInstrumentStatus.STOPPED) {
164 throw new IllegalStateException("time instrument [" + ti.getName() + " is not stopped");
165 }
166 if (ti instanceof Profiler) {
167 Profiler nestedProfiler = (Profiler) ti;
168 nestedProfiler.sanityCheck();
169 }
170 }
171 if (totalElapsed < childTotal) {
172 throw new IllegalStateException("children have a higher accumulated elapsed time");
173 }
174 }
175
176 static String TOP_PROFILER_FIRST_PREFIX = "+";
177 static String NESTED_PROFILER_FIRST_PREFIX = "|---+";
178 static String TOTAL_ELAPSED = " Total ";
179 static String SUBTOTAL_ELAPSED = " Subtotal ";
180 static String ELAPSED_TIME = " elapsed time ";
181
182 public void print() {
183 System.out.println(toString());
184 }
185
186 @Override
187 public String toString() {
188 DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch);
189 return buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, "");
190 }
191
192 public void log() {
193 Marker profilerMarker = MarkerFactory.getMarker(PROFILER_MARKER_NAME);
194 if (logger == null) {
195 throw new NullPointerException("If you invoke the log() method, then you must associate a logger with this profiler.");
196 }
197 if (logger.isDebugEnabled(profilerMarker)) {
198 DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch);
199 String r = buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, "");
200 logger.debug(profilerMarker, SpacePadder.LINE_SEP + r);
201 }
202 }
203
204 /**
205 * Return a copy of the child instrument list for this Profiler instance.
206 *
207 * @return a copy of this instance's child time instrument list
208 * @since 1.5.9
209 */
210 public List<TimeInstrument> getCopyOfChildTimeInstruments() {
211 List<TimeInstrument> copy = new ArrayList<TimeInstrument>(childTimeInstrumentList);
212 return copy;
213 }
214
215 /**
216 * Return a copy of the global stopwath of this Profiler instance.
217 *
218 * @return a copy of this instance's global stop watch
219 * @since 1.5.9
220 */
221 public StopWatch getCopyOfGlobalStopWatch() {
222 StopWatch copy = new StopWatch(globalStopWatch);
223 return copy;
224 }
225
226 private String buildProfilerString(DurationUnit du, String firstPrefix, String label, String indentation) {
227 StringBuilder buf = new StringBuilder();
228
229 buf.append(firstPrefix);
230 buf.append(" Profiler [");
231 buf.append(name);
232 buf.append("]");
233 buf.append(SpacePadder.LINE_SEP);
234 for (TimeInstrument child : childTimeInstrumentList) {
235 if (child instanceof StopWatch) {
236 buildStopWatchString(buf, du, ELAPSED_TIME, indentation, (StopWatch) child);
237 } else if (child instanceof Profiler) {
238 Profiler profiler = (Profiler) child;
239 String subString = profiler.buildProfilerString(du, NESTED_PROFILER_FIRST_PREFIX, SUBTOTAL_ELAPSED, indentation + " ");
240 buf.append(subString);
241 buildStopWatchString(buf, du, ELAPSED_TIME, indentation, profiler.globalStopWatch);
242 }
243 }
244 buildStopWatchString(buf, du, label, indentation, globalStopWatch);
245 return buf.toString();
246 }
247
248 private static void buildStopWatchString(StringBuilder buf, DurationUnit du, String prefix, String indentation, StopWatch sw) {
249
250 buf.append(indentation);
251 buf.append("|--");
252 buf.append(prefix);
253 SpacePadder.leftPad(buf, "[" + sw.getName() + "]", MIN_SW_NAME_LENGTH);
254 buf.append(" ");
255 String timeStr = Util.durationInDurationUnitsAsStr(sw.elapsedTime(), du);
256 SpacePadder.leftPad(buf, timeStr, MIN_SW_ELAPSED_TIME_NUMBER_LENGTH);
257 buf.append(" ");
258 Util.appendDurationUnitAsStr(buf, du);
259 buf.append(SpacePadder.LINE_SEP);
260 }
261 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.HashMap;
27 import java.util.Map;
28
29 /**
30 * A minimalist registry of profilers.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class ProfilerRegistry {
35
36 private static final InheritableThreadLocal<ProfilerRegistry> inheritableThreadLocal = new InheritableThreadLocal<ProfilerRegistry>();
37
38 Map<String, Profiler> profilerMap = new HashMap<String, Profiler>();
39
40 public void put(Profiler profiler) {
41 put(profiler.getName(), profiler);
42 }
43
44 public void put(String name, Profiler profiler) {
45 profilerMap.put(name, profiler);
46 }
47
48 public static ProfilerRegistry getThreadContextInstance() {
49 ProfilerRegistry pr = inheritableThreadLocal.get();
50 if (pr == null) {
51 pr = new ProfilerRegistry();
52 inheritableThreadLocal.set(pr);
53 }
54 return pr;
55 }
56
57 public Profiler get(String name) {
58 return profilerMap.get(name);
59 }
60
61 public void clear() {
62 profilerMap.clear();
63 }
64 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 public class SpacePadder {
27 public static final String LINE_SEP = System.getProperty("line.separator");
28
29 final static String[] SPACES = { " ", " ", " ", " ", // 1,2,4,8
30 // spaces
31 " ", // 16 spaces
32 " " }; // 32 spaces
33
34 @Deprecated
35 final static public void leftPad(StringBuffer buf, String s, int desiredLength) {
36 int actualLen = 0;
37 if (s != null) {
38 actualLen = s.length();
39 }
40 if (actualLen < desiredLength) {
41 spacePad(buf, desiredLength - actualLen);
42 }
43 if (s != null) {
44 buf.append(s);
45 }
46 }
47
48 final static public void leftPad(StringBuilder buf, String s, int desiredLength) {
49 int actualLen = 0;
50 if (s != null) {
51 actualLen = s.length();
52 }
53 if (actualLen < desiredLength) {
54 spacePad(buf, desiredLength - actualLen);
55 }
56 if (s != null) {
57 buf.append(s);
58 }
59 }
60
61 @Deprecated
62 final static public void rightPad(StringBuffer buf, String s, int desiredLength) {
63 int actualLen = 0;
64 if (s != null) {
65 actualLen = s.length();
66 }
67 if (s != null) {
68 buf.append(s);
69 }
70 if (actualLen < desiredLength) {
71 spacePad(buf, desiredLength - actualLen);
72 }
73 }
74
75 final static public void rightPad(StringBuilder buf, String s, int desiredLength) {
76 int actualLen = 0;
77 if (s != null) {
78 actualLen = s.length();
79 }
80 if (s != null) {
81 buf.append(s);
82 }
83 if (actualLen < desiredLength) {
84 spacePad(buf, desiredLength - actualLen);
85 }
86 }
87
88 /**
89 * Fast space padding method.
90 *
91 * @param sbuf the buffer to pad
92 * @param length the target size of the buffer after padding
93 */
94 @Deprecated
95 final static public void spacePad(StringBuffer sbuf, int length) {
96 while (length >= 32) {
97 sbuf.append(SPACES[5]);
98 length -= 32;
99 }
100
101 for (int i = 4; i >= 0; i--) {
102 if ((length & (1 << i)) != 0) {
103 sbuf.append(SPACES[i]);
104 }
105 }
106 }
107
108 /**
109 * Fast space padding method.
110 *
111 * @param sbuf the buffer to pad
112 * @param length the target size of the buffer after padding
113 */
114 final static public void spacePad(StringBuilder sbuf, int length) {
115 while (length >= 32) {
116 sbuf.append(SPACES[5]);
117 length -= 32;
118 }
119
120 for (int i = 4; i >= 0; i--) {
121 if ((length & (1 << i)) != 0) {
122 sbuf.append(SPACES[i]);
123 }
124 }
125 }
126 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 * A very basic @{link TimeInstrument} which can be started and stopped
28 * once and only once.
29 *
30 * @author Ceki G&uuml;lc&uuml;
31 *
32 */
33 public class StopWatch implements TimeInstrument {
34
35 private String name;
36 private long startTime;
37 private long stopTime;
38 TimeInstrumentStatus status;
39
40 public StopWatch(String name) {
41 start(name);
42 }
43
44 StopWatch(StopWatch original) {
45 this.name = original.name;
46 this.startTime = original.startTime;
47 this.stopTime = original.stopTime;
48 this.status = original.status;
49 }
50
51 public void start(String name) {
52 this.name = name;
53 startTime = System.nanoTime();
54 status = TimeInstrumentStatus.STARTED;
55 }
56
57 public String getName() {
58 return name;
59 }
60
61 public TimeInstrument stop() {
62 if (status == TimeInstrumentStatus.STOPPED) {
63 return this;
64 }
65 return stop(System.nanoTime());
66 }
67
68 public StopWatch stop(long stopTime) {
69 this.status = TimeInstrumentStatus.STOPPED;
70 this.stopTime = stopTime;
71 return this;
72 }
73
74 @Override
75 public String toString() {
76 StringBuilder buf = new StringBuilder();
77 buf.append("StopWatch [");
78 buf.append(name);
79 buf.append("] ");
80
81 switch (status) {
82 case STARTED:
83 buf.append("STARTED");
84 break;
85 case STOPPED:
86 buf.append("elapsed time: ");
87 buf.append(Util.durationInDurationUnitsAsStr(elapsedTime(), DurationUnit.MICROSECOND));
88 break;
89 default:
90 throw new IllegalStateException("Status " + status + " is not expected");
91 }
92 return buf.toString();
93 }
94
95 public final long elapsedTime() {
96 if (status == TimeInstrumentStatus.STARTED) {
97 return 0;
98 } else {
99 return stopTime - startTime;
100 }
101 }
102
103 public TimeInstrumentStatus getStatus() {
104 return status;
105 }
106
107 public void print() {
108 System.out.println(toString());
109 }
110
111 public void log() {
112 throw new UnsupportedOperationException("A stopwatch instance does not know how to log");
113 }
114
115 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 * This interface sets the methods that must be implemented by
28 * {@link Profiler} and {@link StopWatch} classes. It settles the
29 * general feel of the profiler package.
30 *
31 * @author Ceki G&uuml;lc&uuml;
32 *
33 */
34 public interface TimeInstrument {
35
36 /**
37 * All time instruments are named entities.
38 * @return the name of this instrument
39 */
40 String getName();
41
42 TimeInstrumentStatus getStatus();
43
44 /**
45 * Start tis time instrument.
46 *
47 * @param name
48 */
49 void start(String name);
50
51 /**
52 * Stop this time instrument.
53 *
54 * @return this
55 */
56 TimeInstrument stop();
57
58 /**
59 * Time elapsed between start and stop, in nanoseconds.
60 *
61 * @return time elapsed in nanoseconds
62 */
63 long elapsedTime();
64
65 /**
66 * Print information about this time instrument on the console.
67 */
68 void print();
69
70 /**
71 * If the time instrument has an associated logger, then log information about
72 * this time instrument. Note that {@link StopWatch} instances cannot log while {@link Profiler}
73 * instances can.
74 */
75 void log();
76 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 /**
26 * A StopWatch can be in two states: STARTED or STOPPED.
27 */
28
29 package org.slf4j.profiler;
30
31 /**
32 * A time instrument can be in STARTED or STOPPED status.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 *
36 */
37 enum TimeInstrumentStatus {
38 STARTED, STOPPED;
39 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.text.DecimalFormat;
27
28 /**
29 *
30 * A collection of utility methods.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 *
34 */
35 class Util {
36
37 static final long NANOS_IN_ONE_MICROSECOND = 1000;
38 static final long NANOS_IN_ONE_MILLISECOND = NANOS_IN_ONE_MICROSECOND * 1000;
39 static final long NANOS_IN_ONE_SECOND = NANOS_IN_ONE_MILLISECOND * 1000;
40 private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.000");
41
42 static DurationUnit selectDurationUnitForDisplay(StopWatch sw) {
43 return selectDurationUnitForDisplay(sw.elapsedTime());
44 }
45
46 static DurationUnit selectDurationUnitForDisplay(long durationInNanos) {
47 if (durationInNanos < 10 * NANOS_IN_ONE_MICROSECOND) {
48 return DurationUnit.NANOSECOND;
49 } else if (durationInNanos < 10 * NANOS_IN_ONE_MILLISECOND) {
50 return DurationUnit.MICROSECOND;
51 } else if (durationInNanos < 10 * NANOS_IN_ONE_SECOND) {
52 return DurationUnit.MILLISSECOND;
53 } else {
54 return DurationUnit.SECOND;
55 }
56 }
57
58 static public double convertToMicros(long nanos) {
59 return (double) nanos / NANOS_IN_ONE_MICROSECOND;
60 }
61
62 static public double convertToMillis(long nanos) {
63 return (double) nanos / NANOS_IN_ONE_MILLISECOND;
64 }
65
66 static public double convertToSeconds(long nanos) {
67 return ((double) nanos / NANOS_IN_ONE_SECOND);
68 }
69
70 static String durationInDurationUnitsAsStr(StringBuilder buf, StopWatch sw) {
71 DurationUnit du = selectDurationUnitForDisplay(sw);
72 return durationInDurationUnitsAsStr(sw.elapsedTime(), du);
73 }
74
75 static String durationInDurationUnitsAsStr(long nanos, DurationUnit durationUnit) {
76 StringBuilder buf = new StringBuilder();
77 switch (durationUnit) {
78 case NANOSECOND:
79 buf.append(nanos);
80 break;
81 case MICROSECOND:
82 double micros = convertToMicros(nanos);
83 buf.append(DECIMAL_FORMAT.format(micros));
84 break;
85 case MILLISSECOND:
86 double millis = convertToMillis(nanos);
87 buf.append(DECIMAL_FORMAT.format(millis));
88 break;
89 case SECOND:
90 double seconds = convertToSeconds(nanos);
91 buf.append(DECIMAL_FORMAT.format(seconds));
92 break;
93 }
94 return buf.toString();
95 }
96
97 static void appendDurationUnitAsStr(StringBuilder buf, DurationUnit durationUnit) {
98 switch (durationUnit) {
99 case NANOSECOND:
100 buf.append("nanoseconds.");
101 break;
102 case MICROSECOND:
103 buf.append("microseconds.");
104 break;
105 case MILLISSECOND:
106 buf.append("milliseconds.");
107 break;
108 case SECOND:
109 buf.append(" seconds.");
110 break;
111 }
112 }
113 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1
2 <html>
3 <head>
4 <title></title>
5 </head>
6
7
8 <body>
9
10 <p>Poor man's profiler API</p>
11 </body>
12 </html>
0 Implementation-Title: slf4j-ext
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.ext
3 Bundle-Name: slf4j-ext
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.profiler;version=${parsedVersion.osgiVersion}, org.slf4j.cal10n;version=${parsedVersion.osgiVersion}, org.slf4j.ext;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, ch.qos.cal10n;version=${cal10n.version}
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import junit.framework.TestCase;
27
28 public class NDCTest extends TestCase {
29
30 protected void setUp() throws Exception {
31 super.setUp();
32 MDC.clear();
33 }
34
35 protected void tearDown() throws Exception {
36 super.tearDown();
37 }
38
39 public void testEmpty() {
40 assertEquals("", NDC.pop());
41 }
42
43 public void testSmoke() {
44 NDC.push("a");
45 String result = NDC.pop();
46 assertEquals("a", result);
47 }
48
49 public void testSmoke2() {
50 NDC.push("a");
51 NDC.push("b");
52 String result1 = NDC.pop();
53 String result0 = NDC.pop();
54 assertEquals("b", result1);
55 assertEquals("a", result0);
56 }
57 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import java.util.Locale;
27
28 import junit.framework.TestCase;
29
30 import org.apache.log4j.spi.LoggingEvent;
31 import org.slf4j.cal10n.LocLogger;
32 import org.slf4j.cal10n.LocLoggerFactory;
33 import org.slf4j.dummyExt.ListAppender;
34
35 import ch.qos.cal10n.IMessageConveyor;
36 import ch.qos.cal10n.MessageConveyor;
37
38 public class LocLoggerTest extends TestCase {
39
40 ListAppender listAppender;
41 org.apache.log4j.Logger log4jRoot;
42
43 IMessageConveyor imc = new MessageConveyor(Locale.UK);
44 LocLoggerFactory llFactory_uk = new LocLoggerFactory(imc);
45
46 final static String EXPECTED_FILE_NAME = "LocLoggerTest.java";
47
48 public LocLoggerTest(String name) {
49 super(name);
50 }
51
52 public void setUp() throws Exception {
53 super.setUp();
54
55 // start from a clean slate for each test
56
57 listAppender = new ListAppender();
58 listAppender.extractLocationInfo = true;
59 log4jRoot = org.apache.log4j.Logger.getRootLogger();
60 log4jRoot.addAppender(listAppender);
61 log4jRoot.setLevel(org.apache.log4j.Level.TRACE);
62 }
63
64 void verify(LoggingEvent le, String expectedMsg) {
65 assertEquals(expectedMsg, le.getMessage());
66 assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName());
67 }
68
69 public void tearDown() throws Exception {
70 super.tearDown();
71 }
72
73 public void testSmoke() {
74 LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass());
75 locLogger.info(Months.JAN);
76 verify((LoggingEvent) listAppender.list.get(0), "January");
77
78 }
79 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import ch.qos.cal10n.BaseName;
27 import ch.qos.cal10n.Locale;
28 import ch.qos.cal10n.LocaleData;
29
30 @BaseName("months")
31 @LocaleData(@Locale("en"))
32 public enum Months {
33 JAN, FEB, MAR, APR, MAY, JUN;
34 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import java.util.Locale;
27
28 import org.slf4j.cal10n.LocLogger;
29 import org.slf4j.cal10n.LocLoggerFactory;
30
31 import ch.qos.cal10n.IMessageConveyor;
32 import ch.qos.cal10n.MessageConveyor;
33
34 public class MyApplication {
35
36 // create a message conveyor for a given locale
37 IMessageConveyor messageConveyor = new MessageConveyor(Locale.JAPAN);
38
39 // create the LogLoggerFactory
40 LocLoggerFactory llFactory_uk = new LocLoggerFactory(messageConveyor);
41
42 // create a locLogger
43 LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass());
44
45 public void applicationStart() {
46 locLogger.info(Production.APPLICATION_STARTED);
47 // ..
48 }
49
50 public void applicationStop() {
51 locLogger.info(Production.APPLICATION_STOPPED);
52 // ...
53 }
54 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import junit.framework.*;
27
28 public class PackageTest extends TestCase {
29
30 public static Test suite() {
31 TestSuite suite = new TestSuite();
32 suite.addTestSuite(LocLoggerTest.class);
33 return suite;
34 }
35 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.cal10n_dummy;
25
26 import ch.qos.cal10n.LocaleData;
27 import ch.qos.cal10n.Locale;
28 import ch.qos.cal10n.BaseName;
29
30 @BaseName("production")
31 @LocaleData({ @Locale("en_UK"), @Locale("fr") })
32 public enum Production {
33 APPLICATION_STARTED, APPLICATION_STOPPED, DB_CONNECTION, DB_CONNECTION_FAILURE;
34 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import java.util.Date;
27 import java.util.Locale;
28 import java.util.TimeZone;
29
30 import junit.framework.TestCase;
31
32 import org.apache.log4j.spi.LocationInfo;
33 import org.apache.log4j.spi.LoggingEvent;
34 import org.slf4j.MDC;
35 import org.slf4j.ext.EventData;
36 import org.slf4j.ext.EventLogger;
37
38 public class EventLoggerTest extends TestCase {
39
40 ListAppender listAppender;
41 org.apache.log4j.Logger log4;
42
43 final static String EXPECTED_FILE_NAME = "EventLoggerTest.java";
44
45 public EventLoggerTest(String name) {
46 super(name);
47 }
48
49 public void setUp() throws Exception {
50 super.setUp();
51
52 // start from a clean slate for each test
53
54 listAppender = new ListAppender();
55 listAppender.extractLocationInfo = true;
56 org.apache.log4j.Logger eventLogger = org.apache.log4j.Logger.getLogger("EventLogger");
57 eventLogger.addAppender(listAppender);
58 eventLogger.setLevel(org.apache.log4j.Level.TRACE);
59 eventLogger.setAdditivity(false);
60 // Items that apply to any activity
61 MDC.put("ipAddress", "192.168.1.110");
62 MDC.put("login", "TestUSer");
63 MDC.put("hostname", "localhost");
64 MDC.put("productName", "SLF4J");
65 MDC.put("locale", Locale.getDefault().getDisplayName());
66 MDC.put("timezone", TimeZone.getDefault().getDisplayName());
67
68 }
69
70 public void tearDown() throws Exception {
71 super.tearDown();
72 MDC.clear();
73 }
74
75 void verify(LoggingEvent le, String expectedMsg) {
76 assertEquals(expectedMsg, le.getMessage());
77 assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName());
78 }
79
80 public void testEventLogger() {
81 EventData data[] = new EventData[2];
82 data[0] = new EventData();
83 data[0].setEventType("Login");
84 data[0].setEventId("1");
85 data[0].setEventDateTime(new Date());
86 data[0].put("Userid", "TestUser");
87 EventLogger.logEvent(data[0]);
88
89 data[1] = new EventData();
90 data[1].setEventType("Update");
91 data[1].setEventId("2");
92 data[1].setEventDateTime(new Date());
93 data[1].put("FileName", "/etc/hosts");
94 EventLogger.logEvent(data[1]);
95
96 assertEquals(2, listAppender.list.size());
97 for (int i = 0; i < 2; ++i) {
98 LoggingEvent event = listAppender.list.get(i);
99 verify(event, data[i].toXML());
100 LocationInfo li = event.getLocationInformation();
101 assertEquals(this.getClass().getName(), li.getClassName());
102 assertEquals(event.getMDC("hostname"), "localhost");
103 }
104 }
105 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.log4j.AppenderSkeleton;
30 import org.apache.log4j.spi.LoggingEvent;
31
32 public class ListAppender extends AppenderSkeleton {
33
34 public List<LoggingEvent> list = new ArrayList<LoggingEvent>();
35
36 public boolean extractLocationInfo = false;
37
38 protected void append(LoggingEvent event) {
39 list.add(event);
40 if (extractLocationInfo) {
41 event.getLocationInformation();
42 }
43 }
44
45 public void close() {
46 }
47
48 public boolean requiresLayout() {
49 return false;
50 }
51
52 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import junit.framework.TestCase;
27
28 import org.slf4j.MDC;
29 import org.slf4j.ext.MDCStrLookup;
30
31 public class MDCStrLookupTest extends TestCase {
32
33 public MDCStrLookupTest(String name) {
34 super(name);
35 }
36
37 public void setUp() throws Exception {
38 super.setUp();
39 }
40
41 public void tearDown() throws Exception {
42 super.tearDown();
43 }
44
45 public void testLookup() throws Exception {
46 MDC.put("key", "value");
47 MDC.put("number", "2");
48 MDCStrLookup lookup = new MDCStrLookup();
49 assertEquals("value", lookup.lookup("key"));
50 assertEquals("2", lookup.lookup("number"));
51 assertEquals(null, lookup.lookup(null));
52 assertEquals(null, lookup.lookup(""));
53 assertEquals(null, lookup.lookup("other"));
54 }
55 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import junit.framework.*;
27
28 public class PackageTest extends TestCase {
29
30 public static Test suite() {
31 TestSuite suite = new TestSuite();
32 suite.addTestSuite(MDCStrLookupTest.class);
33 suite.addTestSuite(XLoggerTest.class);
34 suite.addTestSuite(EventLoggerTest.class);
35 return suite;
36 }
37 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.dummyExt;
25
26 import junit.framework.TestCase;
27
28 import org.apache.log4j.spi.LocationInfo;
29 import org.apache.log4j.spi.LoggingEvent;
30 import org.slf4j.ext.XLogger;
31 import org.slf4j.ext.XLoggerFactory;
32
33 public class XLoggerTest extends TestCase {
34
35 ListAppender listAppender;
36 org.apache.log4j.Logger log4jRoot;
37
38 final static String EXPECTED_FILE_NAME = "XLoggerTest.java";
39
40 public XLoggerTest(String name) {
41 super(name);
42 }
43
44 public void setUp() throws Exception {
45 super.setUp();
46
47 // start from a clean slate for each test
48
49 listAppender = new ListAppender();
50 listAppender.extractLocationInfo = true;
51 log4jRoot = org.apache.log4j.Logger.getRootLogger();
52 log4jRoot.addAppender(listAppender);
53 log4jRoot.setLevel(org.apache.log4j.Level.TRACE);
54 }
55
56 public void tearDown() throws Exception {
57 super.tearDown();
58 }
59
60 void verify(LoggingEvent le, String expectedMsg) {
61 assertEquals(expectedMsg, le.getMessage());
62 assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName());
63 }
64
65 void verifyWithException(LoggingEvent le, String expectedMsg, Throwable t) {
66 verify(le, expectedMsg);
67 assertEquals(t.toString(), le.getThrowableStrRep()[0]);
68 }
69
70 void verifyWithLevelAndException(LoggingEvent le, XLogger.Level level, String expectedMsg, Throwable t) {
71 verify(le, expectedMsg);
72 assertEquals(t.toString(), le.getThrowableStrRep()[0]);
73 assertEquals(le.getLevel().toString(), level.toString());
74 }
75
76 public void testEntering() {
77 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
78 logger.entry();
79 logger.entry(1);
80 logger.entry("test");
81 logger.entry("a", "b", "c", "d");
82 logger.entry("a", "b", "c", "d", "e");
83 logger.entry("a", "b", "c", "d", "e", "f");
84
85 assertEquals(6, listAppender.list.size());
86 verify((LoggingEvent) listAppender.list.get(0), "entry");
87 verify((LoggingEvent) listAppender.list.get(1), "entry with (1)");
88 verify((LoggingEvent) listAppender.list.get(2), "entry with (test)");
89 }
90
91 public void testExiting() {
92 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
93 logger.exit();
94 assertEquals(Integer.valueOf(0), logger.exit(0));
95 assertEquals(Boolean.FALSE, logger.exit(false));
96
97 assertEquals(3, listAppender.list.size());
98 verify((LoggingEvent) listAppender.list.get(0), "exit");
99 verify((LoggingEvent) listAppender.list.get(1), "exit with (0)");
100 verify((LoggingEvent) listAppender.list.get(2), "exit with (false)");
101 }
102
103 public void testThrowing() {
104 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
105 Throwable t = new UnsupportedOperationException("Test");
106 assertEquals(t, logger.throwing(t));
107 assertEquals(t, logger.throwing(XLogger.Level.DEBUG, t));
108 assertEquals(2, listAppender.list.size());
109 verifyWithException((LoggingEvent) listAppender.list.get(0), "throwing", t);
110 LoggingEvent event = (LoggingEvent) listAppender.list.get(1);
111 verifyWithLevelAndException(event, XLogger.Level.DEBUG, "throwing", t);
112 }
113
114 public void testCaught() {
115 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
116 long x = 5;
117 Throwable t = null;
118 try {
119 @SuppressWarnings("unused")
120 long y = x / 0;
121 } catch (Exception ex) {
122 t = ex;
123 logger.catching(ex);
124 logger.catching(XLogger.Level.DEBUG, ex);
125 }
126 verifyWithException((LoggingEvent) listAppender.list.get(0), "catching", t);
127 verifyWithLevelAndException((LoggingEvent) listAppender.list.get(1), XLogger.Level.DEBUG, "catching", t);
128 }
129
130 // See http://bugzilla.slf4j.org/show_bug.cgi?id=114
131 public void testLocationExtraction_Bug114() {
132 XLogger logger = XLoggerFactory.getXLogger("UnitTest");
133 int line = 135; // requires update if line numbers change
134 logger.exit();
135 logger.debug("hello");
136
137 assertEquals(2, listAppender.list.size());
138
139 {
140 LoggingEvent e = listAppender.list.get(0);
141 LocationInfo li = e.getLocationInformation();
142 assertEquals(this.getClass().getName(), li.getClassName());
143 assertEquals("" + line, li.getLineNumber());
144 }
145
146 {
147 LoggingEvent e = listAppender.list.get(1);
148 LocationInfo li = e.getLocationInformation();
149 assertEquals(this.getClass().getName(), li.getClassName());
150 assertEquals("" + (line + 1), li.getLineNumber());
151 }
152
153 }
154 }
0 <html>
1 <body>
2 Tests related to the org.slf4j.ext package. However, location information code
3 required the caller class (XLogger) to have a different prefix than
4 the test class XLoggerTest. This is ensured by having the test class
5 placed in a different package.
6 </body>
7 </html>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.instrumentation;
25
26 import junit.framework.TestCase;
27
28 public class ToStringHelperTest extends TestCase {
29
30 public void testRenderer() {
31 assertEquals("", "null", ToStringHelper.render(null));
32 assertEquals("", "a", ToStringHelper.render("a"));
33 assertEquals("", "[]", ToStringHelper.render(new String[0]));
34
35 assertEquals("", "[a]", ToStringHelper.render(new String[] { "a" }));
36
37 assertEquals("", "[a, b]", ToStringHelper.render(new String[] { "a", "b" }));
38
39 assertEquals("", "[a, b, c]", ToStringHelper.render(new String[] { "a", "b", "c" }));
40
41 assertEquals("", "[[a], [b, c]]", ToStringHelper.render(new String[][] { { "a" }, { "b", "c" } }));
42
43 assertEquals("", "[0, [a], [b, c]]", ToStringHelper.render(new Object[] { "0", new String[] { "a" }, new Object[] { "b", "c" } }));
44
45 assertEquals("", "[1]", ToStringHelper.render(new int[] { 1 }));
46
47 assertEquals("", "[1, 2, 3]", ToStringHelper.render(new int[] { 1, 2, 3 }));
48
49 assertEquals("", "[1, 2, 3]", ToStringHelper.render(new long[] { 1, 2, 3 }));
50
51 assertEquals("", "[1, 2, 3]", ToStringHelper.render(new short[] { 1, 2, 3 }));
52
53 assertEquals("", "[[1, 2], [], [3, 4]]", ToStringHelper.render(new byte[][] { { 1, 2 }, {}, { 3, 4 } }));
54
55 assertEquals("", "[1.0, 2.0, 3.0]", ToStringHelper.render(new float[] { 1, 2, 3 }));
56
57 assertEquals("", "[1.0, 2.0, 3.0]", ToStringHelper.render(new double[] { 1, 2, 3 }));
58
59 assertEquals("", "[[1.0, 2.0, 3.0]]", ToStringHelper.render(new double[][] { { 1, 2, 3 } }));
60
61 assertEquals("", "[true, false, true]", ToStringHelper.render(new boolean[] { true, false, true }));
62 }
63
64 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 *
28 * This demo illustrates usage of SLF4J profilers.
29 *
30 * <p>
31 * We have been given the task of generating a large number, say N, of random
32 * integers. We need to transform that array into a smaller array containing
33 * only prime numbers. The new array has to be sorted.
34 *
35 * <p>
36 * While tackling this problem, we would like to measure the time spent in each
37 * subtask.
38 *
39 * <p>
40 * A typical output for this demo would be:
41 *
42 * <pre>
43 + Profiler [BASIC]
44 |-- elapsed time [A] 213.186 milliseconds.
45 |-- elapsed time [B] 2499.107 milliseconds.
46 |-- elapsed time [OTHER] 3300.752 milliseconds.
47 |-- Total [BASIC] 6014.161 milliseconds.
48 </pre>
49 *
50 * @author Ceki Gulcu
51 */
52 public class BasicProfilerDemo {
53
54 public static void main(String[] args) {
55 // create a profiler called "BASIC"
56 Profiler profiler = new Profiler("BASIC");
57 profiler.start("A");
58 doA();
59
60 profiler.start("B");
61 doB();
62
63 profiler.start("OTHER");
64 doOther();
65 profiler.stop().print();
66 }
67
68 static private void doA() {
69 delay(200);
70 }
71
72 static private void doB() {
73 delay(2500);
74 }
75
76 static private void doOther() {
77 delay(3300);
78 }
79
80 static private void delay(int millis) {
81 try {
82 Thread.sleep(millis);
83 } catch (InterruptedException e) {
84 }
85 }
86 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 /**
27 *
28 * This demo illustrates usage of SLF4J profilers.
29 *
30 * <p>
31 * We have been given the task of generating a large number, say N,
32 * of random integers. We need to transform that array into a smaller array
33 * containing only prime numbers. The new array has to be sorted.
34 *
35 * <p>
36 * While tackling this problem, we would like to measure the
37 * time spent in each subtask.
38 *
39 * <p>
40 * A typical output for this demo would be:
41 <pre>
42 + Profiler [DEMO]
43 |-- elapsed time [RANDOM] 0.089 seconds.
44 |---+ Profiler [SORT_AND_PRUNE]
45 &nbsp;&nbsp;&nbsp;&nbsp;|-- elapsed time [SORT] 0.221 seconds.
46 &nbsp;&nbsp;&nbsp;&nbsp;|-- elapsed time [PRUNE_COMPOSITES] 11.567 seconds.
47 &nbsp;&nbsp;&nbsp;&nbsp;|-- Subtotal [SORT_AND_PRUNE] 11.788 seconds.
48 |-- elapsed time [SORT_AND_PRUNE] 11.788 seconds.
49 |-- Total [DEMO] 11.877 seconds.
50 </pre>
51 *
52 * @author Ceki Gulcu
53 */
54 public class NestedProfilerDemo {
55
56 public static void main(String[] args) {
57 // create a profiler called "DEMO"
58 Profiler profiler = new Profiler("DEMO");
59
60 // register this profiler in the thread context's profiler registry
61 ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
62 profiler.registerWith(profilerRegistry);
63
64 // start a stopwatch called "RANDOM"
65 profiler.start("RANDOM");
66 RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator();
67 int n = 10 * 1000;
68 int[] randomArray = riaGenerator.generate(n);
69
70 // create and start a nested profiler called "SORT_AND_PRUNE"
71 // By virtue of its parent-child relationship with the "DEMO"
72 // profiler, and the previous registration of the parent profiler,
73 // this nested profiler will be automatically registered
74 // with the thread context's profiler registry
75 profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME);
76
77 SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray);
78 pruner.sortAndPruneComposites();
79
80 // stop and print the "DEMO" printer
81 profiler.stop().print();
82 }
83 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 /**
30 *
31 * This demo illustrates usage of SLF4J profilers. It is almost identical to
32 * the first NestProfilerDemo, except that it uses a logger instead of
33 * printing its output on the console.
34 *
35
36 * @author Ceki Gulcu
37 */
38 public class NestedProfilerDemo2 {
39
40 static Logger logger = LoggerFactory.getLogger(NestedProfilerDemo2.class);
41
42 public static void main(String[] args) {
43 Profiler profiler = new Profiler("DEMO");
44 // associate a logger with the profiler
45 profiler.setLogger(logger);
46
47 ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
48 profiler.registerWith(profilerRegistry);
49
50 profiler.start("RANDOM");
51 RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator();
52 int n = 10 * 1000;
53 int[] randomArray = riaGenerator.generate(n);
54
55 profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME);
56
57 SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray);
58 pruner.sortAndPruneComposites();
59
60 // stop and log
61 profiler.stop().log();
62 }
63 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import junit.framework.*;
27
28 public class PackageTest extends TestCase {
29
30 public static Test suite() {
31 TestSuite suite = new TestSuite();
32 suite.addTestSuite(UtilTest.class);
33 suite.addTestSuite(ProfilerTest.class);
34 return suite;
35 }
36 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import junit.framework.TestCase;
27
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 public class ProfilerTest extends TestCase {
32
33 Logger logger = LoggerFactory.getLogger(ProfilerTest.class);
34
35 public void setUp() throws Exception {
36 super.setUp();
37 }
38
39 public void testSmoke() {
40 Profiler profiler = new Profiler("SMOKE");
41 profiler.stop();
42 StopWatch gSW = profiler.globalStopWatch;
43
44 // verify
45 profiler.sanityCheck();
46 assertEquals(TimeInstrumentStatus.STOPPED, gSW.status);
47 assertEquals(0, profiler.childTimeInstrumentList.size());
48 assertNull(profiler.getLastTimeInstrument());
49 }
50
51 public void testBasicProfiling() {
52 Profiler profiler = new Profiler("BAS");
53
54 profiler.start("doX");
55 doX(1);
56
57 profiler.start("doY");
58 doY(10);
59
60 profiler.start("doZ");
61 doZ(2);
62 profiler.stop();
63
64 // verify
65 profiler.sanityCheck();
66 StopWatch gSW = profiler.globalStopWatch;
67 assertEquals(TimeInstrumentStatus.STOPPED, gSW.status);
68 assertEquals(3, profiler.childTimeInstrumentList.size());
69 assertNotNull(profiler.getLastTimeInstrument());
70 assertEquals("doZ", profiler.getLastTimeInstrument().getName());
71 }
72
73 // + Profiler [BAS]
74 // |-- elapsed time [doX] 1.272 milliseconds.
75 // |-- elapsed time [doYYYYY] 25.398 milliseconds.
76 // |--+ Profiler [subtask]
77 // |-- elapsed time [n1] 1.434 milliseconds.
78 // |-- elapsed time [n2] 5.855 milliseconds.
79 // |-- Total elapsed time [subtask] 7.321 milliseconds.
80 // |-- elapsed time [doZ] 3.211 milliseconds.
81 // |-- Total elapsed time [BAS] 30.317 milliseconds.
82 public void testNestedProfiling() {
83
84 Profiler profiler = new Profiler("BAS");
85 profiler.setLogger(logger);
86 profiler.start("doX");
87 doX(1);
88
89 profiler.start("doYYYYY");
90 for (int i = 0; i < 5; i++) {
91 doY(i);
92 }
93 Profiler nested = profiler.startNested("subtask");
94 doSubtask(nested);
95 profiler.start("doZ");
96 doZ(2);
97 profiler.stop();
98
99 // verify
100 profiler.sanityCheck();
101 StopWatch gSW = profiler.globalStopWatch;
102 assertEquals(TimeInstrumentStatus.STOPPED, gSW.status);
103 // assertEquals(3, profiler.stopwatchList.size());
104 assertEquals(4, profiler.childTimeInstrumentList.size());
105 assertNotNull(profiler.getLastTimeInstrument());
106 assertEquals("doZ", profiler.getLastTimeInstrument().getName());
107
108 }
109
110 private void doX(int millis) {
111 delay(millis);
112 }
113
114 private void doY(int millis) {
115 delay(millis);
116 }
117
118 private void doZ(int millis) {
119 delay(millis);
120 }
121
122 public void doSubtask(Profiler nested) {
123 nested.start("n1");
124 doX(1);
125
126 nested.start("n2");
127 doX(5);
128 nested.stop();
129 }
130
131 void delay(int millis) {
132 try {
133 Thread.sleep(millis);
134 } catch (InterruptedException e) {
135 }
136 }
137 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.Random;
27
28 public class RandomIntegerArrayGenerator {
29 Random rand = new Random(11);
30
31 int[] generate(int size) {
32 int[] result = new int[size];
33 for (int i = 0; i < size; i++) {
34 int r = rand.nextInt();
35 result[i] = r;
36 }
37 return result;
38 }
39 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import java.util.ArrayList;
27 import java.util.Arrays;
28
29 public class SortAndPruneComposites {
30
31 static String NESTED_PROFILER_NAME = "SORT_AND_PRUNE";
32
33 final int[] originalArray;
34 final int originalArrrayLength;
35
36 public SortAndPruneComposites(int[] randomArray) {
37 this.originalArray = randomArray;
38 this.originalArrrayLength = randomArray.length;
39
40 }
41
42 public int[] sortAndPruneComposites() {
43 // retrieve previously registered profiler named "SORT_AND_PRUNE"
44 ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
45 Profiler sortProfiler = profilerRegistry.get(NESTED_PROFILER_NAME);
46
47 // start a new stopwatch called SORT
48 sortProfiler.start("SORT");
49 int[] sortedArray = sort();
50 // start a new stopwatch called PRUNE_COMPOSITES
51 sortProfiler.start("PRUNE_COMPOSITES");
52 int result[] = pruneComposites(sortedArray);
53
54 return result;
55 }
56
57 private int[] sort() {
58 int[] sortedArray = new int[originalArrrayLength];
59 System.arraycopy(originalArray, 0, sortedArray, 0, originalArrrayLength);
60 Arrays.sort(sortedArray);
61 return sortedArray;
62 }
63
64 int[] pruneComposites(int[] sortedArray) {
65 ArrayList<Integer> primesArray = new ArrayList<Integer>();
66 for (int i = 0; i < originalArrrayLength; i++) {
67 int n = sortedArray[i];
68 if (isPrime(n)) {
69 primesArray.add(n);
70 }
71 }
72 int resultSize = primesArray.size();
73 int[] result = new int[resultSize];
74
75 for (int i = 0; i < resultSize; i++) {
76 result[i] = primesArray.get(i);
77 }
78 return result;
79 }
80
81 public boolean isPrime(int n) {
82 if (n < 2) {
83 return false;
84 }
85 if (n % 2 == 0) {
86 return false;
87 }
88 for (int i = 3; i * i <= n; i += 2) {
89 if (n % i == 0) {
90 return false;
91 }
92 }
93 return true;
94 }
95 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.profiler;
25
26 import junit.framework.TestCase;
27
28 public class UtilTest extends TestCase {
29
30 public UtilTest(String name) {
31 super(name);
32 }
33
34 protected void setUp() throws Exception {
35 super.setUp();
36 }
37
38 protected void tearDown() throws Exception {
39 super.tearDown();
40 }
41
42 public void testSelectDurationUnitForDisplay() throws InterruptedException {
43 assertEquals(DurationUnit.NANOSECOND, Util.selectDurationUnitForDisplay(10));
44 assertEquals(DurationUnit.NANOSECOND, Util.selectDurationUnitForDisplay(9 * Util.NANOS_IN_ONE_MICROSECOND));
45 assertEquals(DurationUnit.MICROSECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_MICROSECOND));
46 assertEquals(DurationUnit.MICROSECOND, Util.selectDurationUnitForDisplay(9 * Util.NANOS_IN_ONE_MILLISECOND));
47 assertEquals(DurationUnit.MILLISSECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_MILLISECOND));
48 assertEquals(DurationUnit.SECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_SECOND));
49 }
50
51 }
0
1 log4j.rootLogger=DEBUG, CONSOLE
2
3 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
4 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
5 log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
0 JAN=January
1 FEB=February
2 MAR=March
3 APR=April
4 MAY=May
5 JUN=June
0 APPLICATION_STARTED=APPLICATION_STARTED
1 APPLICATION_STOPPED=APPLICATION_STOPPED
2 DB_CONNECTION=DB_CONNECTION
3 DB_CONNECTION_FAILURE=DB_CONNECTION_FAILURE
0 APPLICATION_STARTED=APPLICATION_STARTED
1 APPLICATION_STOPPED=APPLICATION_STOPPED
2 DB_CONNECTION=DB_CONNECTION
3 DB_CONNECTION_FAILURE=DB_CONNECTION_FAILURE
0 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2
3 <modelVersion>4.0.0</modelVersion>
4
5 <parent>
6 <groupId>org.slf4j</groupId>
7 <artifactId>slf4j-parent</artifactId>
8 <version>1.7.12</version>
9 </parent>
10
11 <artifactId>slf4j-jcl</artifactId>
12 <packaging>jar</packaging>
13 <name>SLF4J JCL Binding</name>
14 <description>SLF4J JCL Binding</description>
15
16 <url>http://www.slf4j.org</url>
17
18 <dependencies>
19 <dependency>
20 <groupId>org.slf4j</groupId>
21 <artifactId>slf4j-api</artifactId>
22 </dependency>
23
24 <dependency>
25 <groupId>commons-logging</groupId>
26 <artifactId>commons-logging</artifactId>
27 <version>1.1.1</version>
28 </dependency>
29
30 </dependencies>
31
32 <build>
33 <plugins>
34 <plugin>
35 <groupId>org.apache.maven.plugins</groupId>
36 <artifactId>maven-jar-plugin</artifactId>
37 <configuration>
38 <archive>
39 <manifestEntries>
40 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
41 <Bundle-Description>${project.description}</Bundle-Description>
42 <Implementation-Version>${project.version}</Implementation-Version>
43 </manifestEntries>
44 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
45 </archive>
46 </configuration>
47 </plugin>
48
49 </plugins>
50 </build>
51
52 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j.impl;
26
27 import org.apache.commons.logging.Log;
28 import org.slf4j.Logger;
29 import org.slf4j.helpers.FormattingTuple;
30 import org.slf4j.helpers.MarkerIgnoringBase;
31 import org.slf4j.helpers.MessageFormatter;
32
33 /**
34 * A wrapper over {@link org.apache.commons.logging.Log
35 * org.apache.commons.logging.Log} in conformance with the {@link Logger}
36 * interface.
37 *
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public final class JCLLoggerAdapter extends MarkerIgnoringBase {
41
42 private static final long serialVersionUID = 4141593417490482209L;
43 final Log log;
44
45 // WARN: JCLLoggerAdapter constructor should have only package access so
46 // that only JCLLoggerFactory be able to create one.
47 JCLLoggerAdapter(Log log, String name) {
48 this.log = log;
49 this.name = name;
50 }
51
52 /**
53 * Delegates to the {@link Log#isTraceEnabled} method of the underlying
54 * {@link Log} instance.
55 */
56 public boolean isTraceEnabled() {
57 return log.isTraceEnabled();
58 }
59
60 //
61
62 /**
63 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
64 * {@link Log} instance.
65 *
66 * @param msg - the message object to be logged
67 */
68 public void trace(String msg) {
69 log.trace(msg);
70 }
71
72 /**
73 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
74 * {@link Log} instance.
75 *
76 * <p>
77 * However, this form avoids superfluous object creation when the logger is disabled
78 * for level TRACE.
79 * </p>
80 *
81 * @param format
82 * the format string
83 * @param arg
84 * the argument
85 */
86 public void trace(String format, Object arg) {
87 if (log.isTraceEnabled()) {
88 FormattingTuple ft = MessageFormatter.format(format, arg);
89 log.trace(ft.getMessage(), ft.getThrowable());
90 }
91 }
92
93 /**
94 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
95 * {@link Log} instance.
96 *
97 * <p>
98 * However, this form avoids superfluous object creation when the logger is disabled
99 * for level TRACE.
100 * </p>
101 *
102 * @param format
103 * the format string
104 * @param arg1
105 * the first argument
106 * @param arg2
107 * the second argument
108 */
109 public void trace(String format, Object arg1, Object arg2) {
110 if (log.isTraceEnabled()) {
111 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
112 log.trace(ft.getMessage(), ft.getThrowable());
113 }
114 }
115
116 /**
117 * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying
118 * {@link Log} instance.
119 *
120 * <p>
121 * However, this form avoids superfluous object creation when the logger is disabled
122 * for level TRACE.
123 * </p>
124 *
125 * @param format the format string
126 * @param arguments a list of 3 or more arguments
127 */
128 public void trace(String format, Object... arguments) {
129 if (log.isTraceEnabled()) {
130 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
131 log.trace(ft.getMessage(), ft.getThrowable());
132 }
133 }
134
135 /**
136 * Delegates to the {@link Log#trace(java.lang.Object, java.lang.Throwable)} method of
137 * the underlying {@link Log} instance.
138 *
139 * @param msg
140 * the message accompanying the exception
141 * @param t
142 * the exception (throwable) to log
143 */
144 public void trace(String msg, Throwable t) {
145 log.trace(msg, t);
146 }
147
148 /**
149 * Delegates to the {@link Log#isDebugEnabled} method of the underlying
150 * {@link Log} instance.
151 */
152 public boolean isDebugEnabled() {
153 return log.isDebugEnabled();
154 }
155
156 //
157
158 /**
159 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
160 * {@link Log} instance.
161 *
162 * @param msg - the message object to be logged
163 */
164 public void debug(String msg) {
165 log.debug(msg);
166 }
167
168 /**
169 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
170 * {@link Log} instance.
171 *
172 * <p>
173 * However, this form avoids superfluous object creation when the logger is disabled
174 * for level DEBUG.
175 * </p>
176 *
177 * @param format
178 * the format string
179 * @param arg
180 * the argument
181 */
182 public void debug(String format, Object arg) {
183 if (log.isDebugEnabled()) {
184 FormattingTuple ft = MessageFormatter.format(format, arg);
185 log.debug(ft.getMessage(), ft.getThrowable());
186 }
187 }
188
189 /**
190 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
191 * {@link Log} instance.
192 *
193 * <p>
194 * However, this form avoids superfluous object creation when the logger is disabled
195 * for level DEBUG.
196 * </p>
197 *
198 * @param format
199 * the format string
200 * @param arg1
201 * the first argument
202 * @param arg2
203 * the second argument
204 */
205 public void debug(String format, Object arg1, Object arg2) {
206 if (log.isDebugEnabled()) {
207 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
208 log.debug(ft.getMessage(), ft.getThrowable());
209 }
210 }
211
212 /**
213 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
214 * {@link Log} instance.
215 *
216 * <p>
217 * However, this form avoids superfluous object creation when the logger is disabled
218 * for level DEBUG.
219 * </p>
220 *
221 * @param format the format string
222 * @param arguments a list of 3 or more arguments
223 */
224 public void debug(String format, Object... arguments) {
225 if (log.isDebugEnabled()) {
226 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
227 log.debug(ft.getMessage(), ft.getThrowable());
228 }
229 }
230
231 /**
232 * Delegates to the {@link Log#debug(java.lang.Object, java.lang.Throwable)} method of
233 * the underlying {@link Log} instance.
234 *
235 * @param msg
236 * the message accompanying the exception
237 * @param t
238 * the exception (throwable) to log
239 */
240 public void debug(String msg, Throwable t) {
241 log.debug(msg, t);
242 }
243
244 /**
245 * Delegates to the {@link Log#isInfoEnabled} method of the underlying
246 * {@link Log} instance.
247 */
248 public boolean isInfoEnabled() {
249 return log.isInfoEnabled();
250 }
251
252 /**
253 * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying
254 * {@link Log} instance.
255 *
256 * @param msg - the message object to be logged
257 */
258 public void info(String msg) {
259 log.info(msg);
260 }
261
262 /**
263 * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying
264 * {@link Log} instance.
265 *
266 * <p>
267 * However, this form avoids superfluous object creation when the logger is disabled
268 * for level INFO.
269 * </p>
270 *
271 * @param format
272 * the format string
273 * @param arg
274 * the argument
275 */
276
277 public void info(String format, Object arg) {
278 if (log.isInfoEnabled()) {
279 FormattingTuple ft = MessageFormatter.format(format, arg);
280 log.info(ft.getMessage(), ft.getThrowable());
281 }
282 }
283
284 /**
285 * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying
286 * {@link Log} instance.
287 *
288 * <p>
289 * However, this form avoids superfluous object creation when the logger is disabled
290 * for level INFO.
291 * </p>
292 *
293 * @param format
294 * the format string
295 * @param arg1
296 * the first argument
297 * @param arg2
298 * the second argument
299 */
300 public void info(String format, Object arg1, Object arg2) {
301 if (log.isInfoEnabled()) {
302
303 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
304 log.info(ft.getMessage(), ft.getThrowable());
305 }
306 }
307
308 /**
309 * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying
310 * {@link Log} instance.
311 *
312 * <p>
313 * However, this form avoids superfluous object creation when the logger is disabled
314 * for level INFO.
315 * </p>
316 *
317 * @param format the format string
318 * @param arguments a list of 3 or more arguments
319 */
320 public void info(String format, Object... arguments) {
321 if (log.isInfoEnabled()) {
322 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
323 log.info(ft.getMessage(), ft.getThrowable());
324 }
325 }
326
327 /**
328 * Delegates to the {@link Log#info(java.lang.Object, java.lang.Throwable)} method of
329 * the underlying {@link Log} instance.
330 *
331 * @param msg
332 * the message accompanying the exception
333 * @param t
334 * the exception (throwable) to log
335 */
336 public void info(String msg, Throwable t) {
337 log.info(msg, t);
338 }
339
340 /**
341 * Delegates to the {@link Log#isWarnEnabled} method of the underlying
342 * {@link Log} instance.
343 */
344 public boolean isWarnEnabled() {
345 return log.isWarnEnabled();
346 }
347
348 /**
349 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
350 * {@link Log} instance.
351 *
352 * @param msg - the message object to be logged
353 */
354 public void warn(String msg) {
355 log.warn(msg);
356 }
357
358 /**
359 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
360 * {@link Log} instance.
361 *
362 * <p>
363 * However, this form avoids superfluous object creation when the logger is disabled
364 * for level WARN.
365 * </p>
366 *
367 * @param format
368 * the format string
369 * @param arg
370 * the argument
371 */
372 public void warn(String format, Object arg) {
373 if (log.isWarnEnabled()) {
374 FormattingTuple ft = MessageFormatter.format(format, arg);
375 log.warn(ft.getMessage(), ft.getThrowable());
376 }
377 }
378
379 /**
380 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
381 * {@link Log} instance.
382 *
383 * <p>
384 * However, this form avoids superfluous object creation when the logger is disabled
385 * for level WARN.
386 * </p>
387 *
388 * @param format
389 * the format string
390 * @param arg1
391 * the first argument
392 * @param arg2
393 * the second argument
394 */
395 public void warn(String format, Object arg1, Object arg2) {
396 if (log.isWarnEnabled()) {
397 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
398 log.warn(ft.getMessage(), ft.getThrowable());
399 }
400 }
401
402 /**
403 * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying
404 * {@link Log} instance.
405 *
406 * <p>
407 * However, this form avoids superfluous object creation when the logger is disabled
408 * for level WARN.
409 * </p>
410 *
411 * @param format the format string
412 * @param arguments a list of 3 or more arguments
413 */
414 public void warn(String format, Object... arguments) {
415 if (log.isWarnEnabled()) {
416 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
417 log.warn(ft.getMessage(), ft.getThrowable());
418 }
419 }
420
421 /**
422 * Delegates to the {@link Log#warn(java.lang.Object, java.lang.Throwable)} method of
423 * the underlying {@link Log} instance.
424 *
425 * @param msg
426 * the message accompanying the exception
427 * @param t
428 * the exception (throwable) to log
429 */
430
431 public void warn(String msg, Throwable t) {
432 log.warn(msg, t);
433 }
434
435 /**
436 * Delegates to the {@link Log#isErrorEnabled} method of the underlying
437 * {@link Log} instance.
438 */
439 public boolean isErrorEnabled() {
440 return log.isErrorEnabled();
441 }
442
443 /**
444 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
445 * {@link Log} instance.
446 *
447 * @param msg - the message object to be logged
448 */
449 public void error(String msg) {
450 log.error(msg);
451 }
452
453 /**
454 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
455 * {@link Log} instance.
456 *
457 * <p>
458 * However, this form avoids superfluous object creation when the logger is disabled
459 * for level ERROR.
460 * </p>
461 *
462 * @param format
463 * the format string
464 * @param arg
465 * the argument
466 */
467 public void error(String format, Object arg) {
468 if (log.isErrorEnabled()) {
469 FormattingTuple ft = MessageFormatter.format(format, arg);
470 log.error(ft.getMessage(), ft.getThrowable());
471 }
472 }
473
474 /**
475 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
476 * {@link Log} instance.
477 *
478 * <p>
479 * However, this form avoids superfluous object creation when the logger is disabled
480 * for level ERROR.
481 * </p>
482 *
483 * @param format
484 * the format string
485 * @param arg1
486 * the first argument
487 * @param arg2
488 * the second argument
489 */
490 public void error(String format, Object arg1, Object arg2) {
491 if (log.isErrorEnabled()) {
492 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
493 log.error(ft.getMessage(), ft.getThrowable());
494 }
495 }
496
497 /**
498 * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying
499 * {@link Log} instance.
500 *
501 * <p>
502 * However, this form avoids superfluous object creation when the logger is disabled
503 * for level ERROR.
504 * </p>
505 *
506 * @param format the format string
507 * @param arguments a list of 3 or more arguments
508 */
509 public void error(String format, Object... arguments) {
510 if (log.isErrorEnabled()) {
511 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
512 log.error(ft.getMessage(), ft.getThrowable());
513 }
514 }
515
516 /**
517 * Delegates to the {@link Log#error(java.lang.Object, java.lang.Throwable)} method of
518 * the underlying {@link Log} instance.
519 *
520 * @param msg
521 * the message accompanying the exception
522 * @param t
523 * the exception (throwable) to log
524 */
525
526 public void error(String msg, Throwable t) {
527 log.error(msg, t);
528 }
529
530 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.apache.commons.logging.LogFactory;
30 import org.slf4j.ILoggerFactory;
31 import org.slf4j.Logger;
32 import org.slf4j.helpers.Util;
33
34 /**
35 * JCLLoggerFactory is an implementation of {@link ILoggerFactory} returning the
36 * appropriately named {@link JCLLoggerAdapter} instance.
37 *
38 * @author Ceki G&uuml;lc&uuml;
39 */
40 public class JCLLoggerFactory implements ILoggerFactory {
41
42 private static final String JCL_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#jclDelegationLoop";
43
44 // check for delegation loops
45 static {
46 try {
47 Class.forName("org.apache.commons.logging.impl.SLF4JLogFactory");
48 String part1 = "Detected both jcl-over-slf4j.jar AND slf4j-jcl.jar on the class path, preempting StackOverflowError. ";
49 String part2 = "See also " + JCL_DELEGATION_LOOP_URL + " for more details.";
50
51 Util.report(part1);
52 Util.report(part2);
53 throw new IllegalStateException(part1 + part2);
54 } catch (ClassNotFoundException e) {
55 // this is the good case
56 }
57 }
58
59 // key: name (String), value: a JCLLoggerAdapter;
60 ConcurrentMap<String, Logger> loggerMap;
61
62 public JCLLoggerFactory() {
63 loggerMap = new ConcurrentHashMap<String, Logger>();
64 }
65
66 /*
67 * (non-Javadoc)
68 *
69 * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String)
70 */
71 public Logger getLogger(String name) {
72 Logger slf4jLogger = loggerMap.get(name);
73 if (slf4jLogger != null) {
74 return slf4jLogger;
75 } else {
76 org.apache.commons.logging.Log jclLogger = LogFactory.getLog(name);
77 Logger newInstance = new JCLLoggerAdapter(jclLogger, name);
78 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
79 return oldInstance == null ? newInstance : oldInstance;
80 }
81 }
82 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class StaticLoggerBinder implements LoggerFactoryBinder {
37
38 /**
39 * The unique instance of this class.
40 */
41 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
42
43 /**
44 * Return the singleton of this class.
45 *
46 * @return the StaticLoggerBinder singleton
47 */
48 public static final StaticLoggerBinder getSingleton() {
49 return SINGLETON;
50 }
51
52 /**
53 * Version tag used to check compatibility. The value of this field is
54 * modified with each release.
55 */
56
57 // to avoid constant folding by the compiler, this field must *not* be final
58 public static String REQUESTED_API_VERSION = "1.6.99";
59
60 // Binding specific code:
61 private static final String loggerFactoryClassStr = JCLLoggerFactory.class.getName();
62
63 /**
64 * The ILoggerFactory instance returned by the {@link #getLoggerFactory}
65 * method should always be the same object
66 */
67 private final ILoggerFactory loggerFactory;
68
69 private StaticLoggerBinder() {
70 // Binding specific code:
71 loggerFactory = new JCLLoggerFactory();
72 }
73
74 public ILoggerFactory getLoggerFactory() {
75 return loggerFactory;
76 }
77
78 public String getLoggerFactoryClassStr() {
79 return loggerFactoryClassStr;
80 }
81 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Currently this method always returns an instance of
46 * {@link NOPMDCAdapter}.
47 *
48 * @return instance of NOPMDCAdapter
49 */
50 public MDCAdapter getMDCA() {
51 return new NOPMDCAdapter();
52 }
53
54 public String getMDCAdapterClassStr() {
55 return NOPMDCAdapter.class.getName();
56 }
57 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Currently this method always returns an instance of
52 * {@link BasicMarkerFactory}.
53 */
54 public IMarkerFactory getMarkerFactory() {
55 return markerFactory;
56 }
57
58 /**
59 * Currently, this method returns the class name of
60 * {@link BasicMarkerFactory}.
61 */
62 public String getMarkerFactoryClassStr() {
63 return BasicMarkerFactory.class.getName();
64 }
65
66 }
0 Implementation-Title: slf4j-jcl
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.jcl
3 Bundle-Name: slf4j-jcl
4 Bundle-Vendor: SLF4J.ORG
5 Require-Bundle: slf4j.api
6 Bundle-RequiredExecutionEnvironment: J2SE-1.5
7 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
8 Import-Package: org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, org.apache.commons.logging
9 Fragment-Host: slf4j.api
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.util.logging.Level;
27
28 import junit.framework.TestCase;
29
30 /**
31 * Test whether invoking the SLF4J API causes problems or not.
32 *
33 * @author Ceki Gulcu
34 *
35 */
36 public class InvocationTest extends TestCase {
37
38 Level oldLevel;
39 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
40
41 public InvocationTest(String arg0) {
42 super(arg0);
43 }
44
45 protected void setUp() throws Exception {
46 super.setUp();
47 oldLevel = root.getLevel();
48 root.setLevel(Level.OFF);
49 }
50
51 protected void tearDown() throws Exception {
52 super.tearDown();
53 root.setLevel(oldLevel);
54 }
55
56 public void test1() {
57 Logger logger = LoggerFactory.getLogger("test1");
58 logger.debug("Hello world.");
59 }
60
61 public void test2() {
62 Integer i1 = new Integer(1);
63 Integer i2 = new Integer(2);
64 Integer i3 = new Integer(3);
65 Exception e = new Exception("This is a test exception.");
66 Logger logger = LoggerFactory.getLogger("test2");
67
68 logger.debug("Hello world 1.");
69 logger.debug("Hello world {}", i1);
70 logger.debug("val={} val={}", i1, i2);
71 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
72
73 logger.debug("Hello world 2", e);
74 logger.info("Hello world 2.");
75
76 logger.warn("Hello world 3.");
77 logger.warn("Hello world 3", e);
78
79 logger.error("Hello world 4.");
80 logger.error("Hello world {}", new Integer(3));
81 logger.error("Hello world 4.", e);
82 }
83
84 public void testNull() {
85 Logger logger = LoggerFactory.getLogger("testNull");
86 logger.debug(null);
87 logger.info(null);
88 logger.warn(null);
89 logger.error(null);
90
91 Exception e = new Exception("This is a test exception.");
92 logger.debug(null, e);
93 logger.info(null, e);
94 logger.warn(null, e);
95 logger.error(null, e);
96 }
97
98 public void testMarker() {
99 Logger logger = LoggerFactory.getLogger("testMarker");
100 Marker blue = MarkerFactory.getMarker("BLUE");
101 logger.debug(blue, "hello");
102 logger.info(blue, "hello");
103 logger.warn(blue, "hello");
104 logger.error(blue, "hello");
105
106 logger.debug(blue, "hello {}", "world");
107 logger.info(blue, "hello {}", "world");
108 logger.warn(blue, "hello {}", "world");
109 logger.error(blue, "hello {}", "world");
110
111 logger.debug(blue, "hello {} and {} ", "world", "universe");
112 logger.info(blue, "hello {} and {} ", "world", "universe");
113 logger.warn(blue, "hello {} and {} ", "world", "universe");
114 logger.error(blue, "hello {} and {} ", "world", "universe");
115 }
116
117 public void testMDC() {
118 MDC.put("k", "v");
119 assertNull(MDC.get("k"));
120 MDC.remove("k");
121 assertNull(MDC.get("k"));
122 MDC.clear();
123 }
124 }
0 <project
1 xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
5 <modelVersion>4.0.0</modelVersion>
6
7 <parent>
8 <groupId>org.slf4j</groupId>
9 <artifactId>slf4j-parent</artifactId>
10 <version>1.7.12</version>
11 </parent>
12
13 <artifactId>slf4j-jdk14</artifactId>
14
15 <packaging>jar</packaging>
16 <name>SLF4J JDK14 Binding</name>
17 <description>SLF4J JDK14 Binding</description>
18 <url>http://www.slf4j.org</url>
19
20
21 <dependencies>
22 <dependency>
23 <groupId>org.slf4j</groupId>
24 <artifactId>slf4j-api</artifactId>
25 </dependency>
26
27 <dependency>
28 <groupId>org.slf4j</groupId>
29 <artifactId>slf4j-api</artifactId>
30 <type>test-jar</type>
31 <version>${project.version}</version>
32 <scope>test</scope>
33 </dependency>
34 </dependencies>
35
36 <build>
37 <plugins>
38 <plugin>
39 <groupId>org.apache.maven.plugins</groupId>
40 <artifactId>maven-jar-plugin</artifactId>
41 <configuration>
42 <archive>
43 <manifestEntries>
44 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
45 <Bundle-Description>${project.description}</Bundle-Description>
46 <Implementation-Version>${project.version}</Implementation-Version>
47 </manifestEntries>
48 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
49 </archive>
50 </configuration>
51 </plugin>
52 </plugins>
53 </build>
54
55 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.logging.Level;
27 import java.util.logging.LogRecord;
28
29 import org.slf4j.Logger;
30 import org.slf4j.Marker;
31 import org.slf4j.helpers.FormattingTuple;
32 import org.slf4j.helpers.MarkerIgnoringBase;
33 import org.slf4j.helpers.MessageFormatter;
34 import org.slf4j.spi.LocationAwareLogger;
35
36 /**
37 * A wrapper over {@link java.util.logging.Logger java.util.logging.Logger} in
38 * conformity with the {@link Logger} interface. Note that the logging levels
39 * mentioned in this class refer to those defined in the java.util.logging
40 * package.
41 *
42 * @author Ceki G&uuml;lc&uuml;
43 * @author Peter Royal
44 */
45 public final class JDK14LoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger {
46
47 private static final long serialVersionUID = -8053026990503422791L;
48
49 transient final java.util.logging.Logger logger;
50
51 // WARN: JDK14LoggerAdapter constructor should have only package access so
52 // that only JDK14LoggerFactory be able to create one.
53 JDK14LoggerAdapter(java.util.logging.Logger logger) {
54 this.logger = logger;
55 this.name = logger.getName();
56 }
57
58 /**
59 * Is this logger instance enabled for the FINEST level?
60 *
61 * @return True if this Logger is enabled for level FINEST, false otherwise.
62 */
63 public boolean isTraceEnabled() {
64 return logger.isLoggable(Level.FINEST);
65 }
66
67 /**
68 * Log a message object at level FINEST.
69 *
70 * @param msg
71 * - the message object to be logged
72 */
73 public void trace(String msg) {
74 if (logger.isLoggable(Level.FINEST)) {
75 log(SELF, Level.FINEST, msg, null);
76 }
77 }
78
79 /**
80 * Log a message at level FINEST according to the specified format and
81 * argument.
82 *
83 * <p>
84 * This form avoids superfluous object creation when the logger is disabled
85 * for level FINEST.
86 * </p>
87 *
88 * @param format
89 * the format string
90 * @param arg
91 * the argument
92 */
93 public void trace(String format, Object arg) {
94 if (logger.isLoggable(Level.FINEST)) {
95 FormattingTuple ft = MessageFormatter.format(format, arg);
96 log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable());
97 }
98 }
99
100 /**
101 * Log a message at level FINEST according to the specified format and
102 * arguments.
103 *
104 * <p>
105 * This form avoids superfluous object creation when the logger is disabled
106 * for the FINEST level.
107 * </p>
108 *
109 * @param format
110 * the format string
111 * @param arg1
112 * the first argument
113 * @param arg2
114 * the second argument
115 */
116 public void trace(String format, Object arg1, Object arg2) {
117 if (logger.isLoggable(Level.FINEST)) {
118 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
119 log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable());
120 }
121 }
122
123 /**
124 * Log a message at level FINEST according to the specified format and
125 * arguments.
126 *
127 * <p>
128 * This form avoids superfluous object creation when the logger is disabled
129 * for the FINEST level.
130 * </p>
131 *
132 * @param format
133 * the format string
134 * @param argArray
135 * an array of arguments
136 */
137 public void trace(String format, Object... argArray) {
138 if (logger.isLoggable(Level.FINEST)) {
139 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
140 log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable());
141 }
142 }
143
144 /**
145 * Log an exception (throwable) at level FINEST with an accompanying message.
146 *
147 * @param msg
148 * the message accompanying the exception
149 * @param t
150 * the exception (throwable) to log
151 */
152 public void trace(String msg, Throwable t) {
153 if (logger.isLoggable(Level.FINEST)) {
154 log(SELF, Level.FINEST, msg, t);
155 }
156 }
157
158 /**
159 * Is this logger instance enabled for the FINE level?
160 *
161 * @return True if this Logger is enabled for level FINE, false otherwise.
162 */
163 public boolean isDebugEnabled() {
164 return logger.isLoggable(Level.FINE);
165 }
166
167 /**
168 * Log a message object at level FINE.
169 *
170 * @param msg
171 * - the message object to be logged
172 */
173 public void debug(String msg) {
174 if (logger.isLoggable(Level.FINE)) {
175 log(SELF, Level.FINE, msg, null);
176 }
177 }
178
179 /**
180 * Log a message at level FINE according to the specified format and argument.
181 *
182 * <p>
183 * This form avoids superfluous object creation when the logger is disabled
184 * for level FINE.
185 * </p>
186 *
187 * @param format
188 * the format string
189 * @param arg
190 * the argument
191 */
192 public void debug(String format, Object arg) {
193 if (logger.isLoggable(Level.FINE)) {
194 FormattingTuple ft = MessageFormatter.format(format, arg);
195 log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable());
196 }
197 }
198
199 /**
200 * Log a message at level FINE according to the specified format and
201 * arguments.
202 *
203 * <p>
204 * This form avoids superfluous object creation when the logger is disabled
205 * for the FINE level.
206 * </p>
207 *
208 * @param format
209 * the format string
210 * @param arg1
211 * the first argument
212 * @param arg2
213 * the second argument
214 */
215 public void debug(String format, Object arg1, Object arg2) {
216 if (logger.isLoggable(Level.FINE)) {
217 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
218 log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable());
219 }
220 }
221
222 /**
223 * Log a message at level FINE according to the specified format and
224 * arguments.
225 *
226 * <p>
227 * This form avoids superfluous object creation when the logger is disabled
228 * for the FINE level.
229 * </p>
230 *
231 * @param format
232 * the format string
233 * @param argArray
234 * an array of arguments
235 */
236 public void debug(String format, Object... argArray) {
237 if (logger.isLoggable(Level.FINE)) {
238 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
239 log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable());
240 }
241 }
242
243 /**
244 * Log an exception (throwable) at level FINE with an accompanying message.
245 *
246 * @param msg
247 * the message accompanying the exception
248 * @param t
249 * the exception (throwable) to log
250 */
251 public void debug(String msg, Throwable t) {
252 if (logger.isLoggable(Level.FINE)) {
253 log(SELF, Level.FINE, msg, t);
254 }
255 }
256
257 /**
258 * Is this logger instance enabled for the INFO level?
259 *
260 * @return True if this Logger is enabled for the INFO level, false otherwise.
261 */
262 public boolean isInfoEnabled() {
263 return logger.isLoggable(Level.INFO);
264 }
265
266 /**
267 * Log a message object at the INFO level.
268 *
269 * @param msg
270 * - the message object to be logged
271 */
272 public void info(String msg) {
273 if (logger.isLoggable(Level.INFO)) {
274 log(SELF, Level.INFO, msg, null);
275 }
276 }
277
278 /**
279 * Log a message at level INFO according to the specified format and argument.
280 *
281 * <p>
282 * This form avoids superfluous object creation when the logger is disabled
283 * for the INFO level.
284 * </p>
285 *
286 * @param format
287 * the format string
288 * @param arg
289 * the argument
290 */
291 public void info(String format, Object arg) {
292 if (logger.isLoggable(Level.INFO)) {
293 FormattingTuple ft = MessageFormatter.format(format, arg);
294 log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable());
295 }
296 }
297
298 /**
299 * Log a message at the INFO level according to the specified format and
300 * arguments.
301 *
302 * <p>
303 * This form avoids superfluous object creation when the logger is disabled
304 * for the INFO level.
305 * </p>
306 *
307 * @param format
308 * the format string
309 * @param arg1
310 * the first argument
311 * @param arg2
312 * the second argument
313 */
314 public void info(String format, Object arg1, Object arg2) {
315 if (logger.isLoggable(Level.INFO)) {
316 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
317 log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable());
318 }
319 }
320
321 /**
322 * Log a message at level INFO according to the specified format and
323 * arguments.
324 *
325 * <p>
326 * This form avoids superfluous object creation when the logger is disabled
327 * for the INFO level.
328 * </p>
329 *
330 * @param format
331 * the format string
332 * @param argArray
333 * an array of arguments
334 */
335 public void info(String format, Object... argArray) {
336 if (logger.isLoggable(Level.INFO)) {
337 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
338 log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable());
339 }
340 }
341
342 /**
343 * Log an exception (throwable) at the INFO level with an accompanying
344 * message.
345 *
346 * @param msg
347 * the message accompanying the exception
348 * @param t
349 * the exception (throwable) to log
350 */
351 public void info(String msg, Throwable t) {
352 if (logger.isLoggable(Level.INFO)) {
353 log(SELF, Level.INFO, msg, t);
354 }
355 }
356
357 /**
358 * Is this logger instance enabled for the WARNING level?
359 *
360 * @return True if this Logger is enabled for the WARNING level, false
361 * otherwise.
362 */
363 public boolean isWarnEnabled() {
364 return logger.isLoggable(Level.WARNING);
365 }
366
367 /**
368 * Log a message object at the WARNING level.
369 *
370 * @param msg
371 * - the message object to be logged
372 */
373 public void warn(String msg) {
374 if (logger.isLoggable(Level.WARNING)) {
375 log(SELF, Level.WARNING, msg, null);
376 }
377 }
378
379 /**
380 * Log a message at the WARNING level according to the specified format and
381 * argument.
382 *
383 * <p>
384 * This form avoids superfluous object creation when the logger is disabled
385 * for the WARNING level.
386 * </p>
387 *
388 * @param format
389 * the format string
390 * @param arg
391 * the argument
392 */
393 public void warn(String format, Object arg) {
394 if (logger.isLoggable(Level.WARNING)) {
395 FormattingTuple ft = MessageFormatter.format(format, arg);
396 log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable());
397 }
398 }
399
400 /**
401 * Log a message at the WARNING level according to the specified format and
402 * arguments.
403 *
404 * <p>
405 * This form avoids superfluous object creation when the logger is disabled
406 * for the WARNING level.
407 * </p>
408 *
409 * @param format
410 * the format string
411 * @param arg1
412 * the first argument
413 * @param arg2
414 * the second argument
415 */
416 public void warn(String format, Object arg1, Object arg2) {
417 if (logger.isLoggable(Level.WARNING)) {
418 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
419 log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable());
420 }
421 }
422
423 /**
424 * Log a message at level WARNING according to the specified format and
425 * arguments.
426 *
427 * <p>
428 * This form avoids superfluous object creation when the logger is disabled
429 * for the WARNING level.
430 * </p>
431 *
432 * @param format
433 * the format string
434 * @param argArray
435 * an array of arguments
436 */
437 public void warn(String format, Object... argArray) {
438 if (logger.isLoggable(Level.WARNING)) {
439 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
440 log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable());
441 }
442 }
443
444 /**
445 * Log an exception (throwable) at the WARNING level with an accompanying
446 * message.
447 *
448 * @param msg
449 * the message accompanying the exception
450 * @param t
451 * the exception (throwable) to log
452 */
453 public void warn(String msg, Throwable t) {
454 if (logger.isLoggable(Level.WARNING)) {
455 log(SELF, Level.WARNING, msg, t);
456 }
457 }
458
459 /**
460 * Is this logger instance enabled for level SEVERE?
461 *
462 * @return True if this Logger is enabled for level SEVERE, false otherwise.
463 */
464 public boolean isErrorEnabled() {
465 return logger.isLoggable(Level.SEVERE);
466 }
467
468 /**
469 * Log a message object at the SEVERE level.
470 *
471 * @param msg
472 * - the message object to be logged
473 */
474 public void error(String msg) {
475 if (logger.isLoggable(Level.SEVERE)) {
476 log(SELF, Level.SEVERE, msg, null);
477 }
478 }
479
480 /**
481 * Log a message at the SEVERE level according to the specified format and
482 * argument.
483 *
484 * <p>
485 * This form avoids superfluous object creation when the logger is disabled
486 * for the SEVERE level.
487 * </p>
488 *
489 * @param format
490 * the format string
491 * @param arg
492 * the argument
493 */
494 public void error(String format, Object arg) {
495 if (logger.isLoggable(Level.SEVERE)) {
496 FormattingTuple ft = MessageFormatter.format(format, arg);
497 log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable());
498 }
499 }
500
501 /**
502 * Log a message at the SEVERE level according to the specified format and
503 * arguments.
504 *
505 * <p>
506 * This form avoids superfluous object creation when the logger is disabled
507 * for the SEVERE level.
508 * </p>
509 *
510 * @param format
511 * the format string
512 * @param arg1
513 * the first argument
514 * @param arg2
515 * the second argument
516 */
517 public void error(String format, Object arg1, Object arg2) {
518 if (logger.isLoggable(Level.SEVERE)) {
519 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
520 log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable());
521 }
522 }
523
524 /**
525 * Log a message at level SEVERE according to the specified format and
526 * arguments.
527 *
528 * <p>
529 * This form avoids superfluous object creation when the logger is disabled
530 * for the SEVERE level.
531 * </p>
532 *
533 * @param format
534 * the format string
535 * @param arguments
536 * an array of arguments
537 */
538 public void error(String format, Object... arguments) {
539 if (logger.isLoggable(Level.SEVERE)) {
540 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
541 log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable());
542 }
543 }
544
545 /**
546 * Log an exception (throwable) at the SEVERE level with an accompanying
547 * message.
548 *
549 * @param msg
550 * the message accompanying the exception
551 * @param t
552 * the exception (throwable) to log
553 */
554 public void error(String msg, Throwable t) {
555 if (logger.isLoggable(Level.SEVERE)) {
556 log(SELF, Level.SEVERE, msg, t);
557 }
558 }
559
560 /**
561 * Log the message at the specified level with the specified throwable if any.
562 * This method creates a LogRecord and fills in caller date before calling
563 * this instance's JDK14 logger.
564 *
565 * See bug report #13 for more details.
566 *
567 * @param level
568 * @param msg
569 * @param t
570 */
571 private void log(String callerFQCN, Level level, String msg, Throwable t) {
572 // millis and thread are filled by the constructor
573 LogRecord record = new LogRecord(level, msg);
574 record.setLoggerName(getName());
575 record.setThrown(t);
576 fillCallerData(callerFQCN, record);
577 logger.log(record);
578
579 }
580
581 static String SELF = JDK14LoggerAdapter.class.getName();
582 static String SUPER = MarkerIgnoringBase.class.getName();
583
584 /**
585 * Fill in caller data if possible.
586 *
587 * @param record
588 * The record to update
589 */
590 final private void fillCallerData(String callerFQCN, LogRecord record) {
591 StackTraceElement[] steArray = new Throwable().getStackTrace();
592
593 int selfIndex = -1;
594 for (int i = 0; i < steArray.length; i++) {
595 final String className = steArray[i].getClassName();
596 if (className.equals(callerFQCN) || className.equals(SUPER)) {
597 selfIndex = i;
598 break;
599 }
600 }
601
602 int found = -1;
603 for (int i = selfIndex + 1; i < steArray.length; i++) {
604 final String className = steArray[i].getClassName();
605 if (!(className.equals(callerFQCN) || className.equals(SUPER))) {
606 found = i;
607 break;
608 }
609 }
610
611 if (found != -1) {
612 StackTraceElement ste = steArray[found];
613 // setting the class name has the side effect of setting
614 // the needToInferCaller variable to false.
615 record.setSourceClassName(ste.getClassName());
616 record.setSourceMethodName(ste.getMethodName());
617 }
618 }
619
620 public void log(Marker marker, String callerFQCN, int level, String message, Object[] argArray, Throwable t) {
621 Level julLevel;
622 switch (level) {
623 case LocationAwareLogger.TRACE_INT:
624 julLevel = Level.FINEST;
625 break;
626 case LocationAwareLogger.DEBUG_INT:
627 julLevel = Level.FINE;
628 break;
629 case LocationAwareLogger.INFO_INT:
630 julLevel = Level.INFO;
631 break;
632 case LocationAwareLogger.WARN_INT:
633 julLevel = Level.WARNING;
634 break;
635 case LocationAwareLogger.ERROR_INT:
636 julLevel = Level.SEVERE;
637 break;
638 default:
639 throw new IllegalStateException("Level number " + level + " is not recognized.");
640 }
641 // the logger.isLoggable check avoids the unconditional
642 // construction of location data for disabled log
643 // statements. As of 2008-07-31, callers of this method
644 // do not perform this check. See also
645 // http://bugzilla.slf4j.org/show_bug.cgi?id=90
646 if (logger.isLoggable(julLevel)) {
647 log(callerFQCN, julLevel, message, t);
648 }
649 }
650 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.Logger;
27 import org.slf4j.ILoggerFactory;
28
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31
32 /**
33 * JDK14LoggerFactory is an implementation of {@link ILoggerFactory} returning
34 * the appropriately named {@link JDK14LoggerAdapter} instance.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class JDK14LoggerFactory implements ILoggerFactory {
39
40 // key: name (String), value: a JDK14LoggerAdapter;
41 ConcurrentMap<String, Logger> loggerMap;
42
43 public JDK14LoggerFactory() {
44 loggerMap = new ConcurrentHashMap<String, Logger>();
45 }
46
47 /*
48 * (non-Javadoc)
49 *
50 * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String)
51 */
52 public Logger getLogger(String name) {
53 // the root logger is called "" in JUL
54 if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) {
55 name = "";
56 }
57
58 Logger slf4jLogger = loggerMap.get(name);
59 if (slf4jLogger != null)
60 return slf4jLogger;
61 else {
62 java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(name);
63 Logger newInstance = new JDK14LoggerAdapter(julLogger);
64 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
65 return oldInstance == null ? newInstance : oldInstance;
66 }
67 }
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class StaticLoggerBinder implements LoggerFactoryBinder {
37
38 /**
39 * The unique instance of this class.
40 *
41 */
42 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
43
44 /**
45 * Return the singleton of this class.
46 *
47 * @return the StaticLoggerBinder singleton
48 */
49 public static final StaticLoggerBinder getSingleton() {
50 return SINGLETON;
51 }
52
53 /**
54 * Declare the version of the SLF4J API this implementation is compiled against.
55 * The value of this field is usually modified with each release.
56 */
57 // to avoid constant folding by the compiler, this field must *not* be final
58 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
59
60 private static final String loggerFactoryClassStr = org.slf4j.impl.JDK14LoggerFactory.class.getName();
61
62 /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method
63 * should always be the same object
64 */
65 private final ILoggerFactory loggerFactory;
66
67 private StaticLoggerBinder() {
68 // Note: JCL gets substituted at build time by an appropriate Ant task
69 loggerFactory = new org.slf4j.impl.JDK14LoggerFactory();
70 }
71
72 public ILoggerFactory getLoggerFactory() {
73 return loggerFactory;
74 }
75
76 public String getLoggerFactoryClassStr() {
77 return loggerFactoryClassStr;
78 }
79 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.BasicMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link BasicMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Currently this method always returns an instance of
46 * {@link BasicMDCAdapter}.
47 */
48 public MDCAdapter getMDCA() {
49 // note that this method is invoked only from within the static initializer of
50 // the org.slf4j.MDC class.
51 return new BasicMDCAdapter();
52 }
53
54 public String getMDCAdapterClassStr() {
55 return BasicMDCAdapter.class.getName();
56 }
57 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Currently this method always returns an instance of
52 * {@link BasicMarkerFactory}.
53 */
54 public IMarkerFactory getMarkerFactory() {
55 return markerFactory;
56 }
57
58 /**
59 * Currently, this method returns the class name of
60 * {@link BasicMarkerFactory}.
61 */
62 public String getMarkerFactoryClassStr() {
63 return BasicMarkerFactory.class.getName();
64 }
65
66 }
0 Implementation-Title: slf4j-jdk14
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.jdk14
3 Bundle-Name: slf4j-jdk14
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}
8 Fragment-Host: slf4j.api
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import org.junit.After;
27 import org.junit.Assert;
28 import org.junit.Before;
29 import org.junit.Test;
30
31 import java.util.ArrayList;
32 import java.util.List;
33 import java.util.logging.Handler;
34 import java.util.logging.Level;
35 import java.util.logging.LogRecord;
36
37 import static junit.framework.Assert.assertNotNull;
38 import static junit.framework.Assert.assertNull;
39 import static org.junit.Assert.assertEquals;
40 import static org.junit.Assert.fail;
41
42 /**
43 * Test whether invoking the SLF4J API causes problems or not.
44 *
45 * @author Ceki Gulcu
46 */
47 public class InvocationTest {
48
49 Level oldLevel;
50 java.util.logging.Logger root = java.util.logging.Logger.getLogger("");
51
52 ListHandler listHandler = new ListHandler();
53
54 @Before
55 public void setUp() throws Exception {
56 oldLevel = root.getLevel();
57 root.setLevel(Level.FINE);
58 // removeAllHandlers(root);
59 root.addHandler(listHandler);
60 }
61
62 @After
63 public void tearDown() throws Exception {
64 root.setLevel(oldLevel);
65 removeListHandlers(root);
66 }
67
68 @Test
69 public void test1() {
70 Logger logger = LoggerFactory.getLogger("test1");
71 logger.debug("Hello world.");
72 assertLogMessage("Hello world.", 0);
73 }
74
75 @Test
76 public void verifyMessageFormatting() {
77 Integer i1 = new Integer(1);
78 Integer i2 = new Integer(2);
79 Integer i3 = new Integer(3);
80 Exception e = new Exception("This is a test exception.");
81 Logger logger = LoggerFactory.getLogger("test2");
82
83 int index = 0;
84 logger.debug("Hello world");
85 assertLogMessage("Hello world", index++);
86
87 logger.debug("Hello world {}", i1);
88 assertLogMessage("Hello world " + i1, index++);
89
90 logger.debug("val={} val={}", i1, i2);
91 assertLogMessage("val=1 val=2", index++);
92
93 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
94 assertLogMessage("val=1 val=2 val=3", index++);
95
96 logger.debug("Hello world 2", e);
97 assertLogMessage("Hello world 2", index);
98 assertException(e.getClass(), index++);
99 logger.info("Hello world 2.");
100
101 logger.warn("Hello world 3.");
102 logger.warn("Hello world 3", e);
103
104 logger.error("Hello world 4.");
105 logger.error("Hello world {}", new Integer(3));
106 logger.error("Hello world 4.", e);
107 }
108
109 @Test
110 public void testNull() {
111 Logger logger = LoggerFactory.getLogger("testNull");
112 logger.debug(null);
113 logger.info(null);
114 logger.warn(null);
115 logger.error(null);
116
117 Exception e = new Exception("This is a test exception.");
118 logger.debug(null, e);
119 logger.info(null, e);
120 logger.warn(null, e);
121 logger.error(null, e);
122 }
123
124 @Test
125 public void testMarker() {
126 Logger logger = LoggerFactory.getLogger("testMarker");
127 Marker blue = MarkerFactory.getMarker("BLUE");
128 logger.debug(blue, "hello");
129 logger.info(blue, "hello");
130 logger.warn(blue, "hello");
131 logger.error(blue, "hello");
132
133 logger.debug(blue, "hello {}", "world");
134 logger.info(blue, "hello {}", "world");
135 logger.warn(blue, "hello {}", "world");
136 logger.error(blue, "hello {}", "world");
137
138 logger.debug(blue, "hello {} and {} ", "world", "universe");
139 logger.info(blue, "hello {} and {} ", "world", "universe");
140 logger.warn(blue, "hello {} and {} ", "world", "universe");
141 logger.error(blue, "hello {} and {} ", "world", "universe");
142 }
143
144 @Test
145 public void testMDC() {
146 MDC.put("k", "v");
147 assertNotNull(MDC.get("k"));
148 assertEquals("v", MDC.get("k"));
149
150 MDC.remove("k");
151 assertNull(MDC.get("k"));
152
153 MDC.put("k1", "v1");
154 assertEquals("v1", MDC.get("k1"));
155 MDC.clear();
156 assertNull(MDC.get("k1"));
157
158 try {
159 MDC.put(null, "x");
160 fail("null keys are invalid");
161 } catch (IllegalArgumentException e) {
162 }
163 }
164
165 private void assertLogMessage(String expected, int index) {
166 LogRecord logRecord = listHandler.recordList.get(index);
167 Assert.assertNotNull(logRecord);
168 assertEquals(expected, logRecord.getMessage());
169 }
170
171 private void assertException(Class<? extends Throwable> exceptionType, int index) {
172 LogRecord logRecord = listHandler.recordList.get(index);
173 Assert.assertNotNull(logRecord);
174 assertEquals(exceptionType, logRecord.getThrown().getClass());
175 }
176
177 void removeListHandlers(java.util.logging.Logger logger) {
178 Handler[] handlers = logger.getHandlers();
179 for (Handler h : handlers) {
180 if (h instanceof ListHandler)
181 logger.removeHandler(h);
182 }
183 }
184
185 static private class ListHandler extends java.util.logging.Handler {
186
187 List<LogRecord> recordList = new ArrayList<LogRecord>();
188
189 @Override
190 public void publish(LogRecord record) {
191 recordList.add(record);
192 }
193
194 @Override
195 public void flush() {
196 }
197
198 @Override
199 public void close() throws SecurityException {
200 }
201 }
202 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.logging.Handler;
27 import java.util.logging.LogRecord;
28 import java.util.logging.Logger;
29
30 import junit.framework.TestCase;
31
32 public class JDK14AdapterLoggerNameTest extends TestCase {
33 private MockHandler mockHandler;
34
35 protected void setUp() throws Exception {
36 super.setUp();
37 Logger logger = Logger.getLogger("TEST");
38 mockHandler = new MockHandler();
39 removeHandlers(logger);
40 logger.addHandler(mockHandler);
41 }
42
43 protected void tearDown() throws Exception {
44 removeHandlers(Logger.getLogger("TEST"));
45 super.tearDown();
46 }
47
48 public void testLoggerNameusingJdkLogging() throws Exception {
49 Logger.getLogger("TEST").info("test message");
50 assertCorrectLoggerName();
51
52 }
53
54 public void testLoggerNameUsingSlf4j() throws Exception {
55 JDK14LoggerFactory factory = new JDK14LoggerFactory();
56 org.slf4j.Logger logger = factory.getLogger("TEST");
57 logger.info("test message");
58 assertCorrectLoggerName();
59 }
60
61 private void removeHandlers(Logger logger) {
62 logger.setUseParentHandlers(false);
63 Handler[] handlers = logger.getHandlers();
64 for (int i = 0; i < handlers.length; i++) {
65 logger.removeHandler(handlers[i]);
66 }
67 }
68
69 private void assertCorrectLoggerName() {
70 assertNotNull("no log record", mockHandler.record);
71 assertNotNull("missing logger name", mockHandler.record.getLoggerName());
72 }
73
74 private class MockHandler extends java.util.logging.Handler {
75 public LogRecord record;
76
77 public void close() throws SecurityException {
78 }
79
80 public void flush() {
81 }
82
83 public void publish(LogRecord record) {
84 this.record = record;
85 }
86
87 }
88 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import junit.framework.TestCase;
27
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.slf4j.helpers.BogoPerf;
31
32 public class PerfTest extends TestCase {
33
34 static long REFERENCE_BIPS = 9000;
35
36 public PerfTest(String name) {
37 super(name);
38 }
39
40 protected void setUp() throws Exception {
41 super.setUp();
42 }
43
44 protected void tearDown() throws Exception {
45 super.tearDown();
46 }
47
48 public void testBug72() {
49
50 int LEN = 1000 * 1000 * 10;
51 debugLoop(LEN); // warm up
52 double avg = debugLoop(LEN);
53 long referencePerf = 93;
54 BogoPerf.assertDuration(avg, referencePerf, REFERENCE_BIPS);
55
56 // when the code is guarded by a logger.isLoggable condition,
57 // duration is about 16 *micro*seconds for 1000 iterations
58 // when it is not guarded the figure is 90 milliseconds,
59 // i.e a ration of 1 to 5000
60 }
61
62 double debugLoop(int len) {
63 Logger logger = LoggerFactory.getLogger(PerfTest.class);
64 long start = System.currentTimeMillis();
65 for (int i = 0; i < len; i++) {
66 logger.debug("hello");
67 }
68
69 long end = System.currentTimeMillis();
70
71 long duration = end - start;
72 return duration;
73 }
74
75 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.issue;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.ObjectInputStream;
31 import java.io.ObjectOutputStream;
32 import java.io.Serializable;
33
34 import junit.framework.Assert;
35
36 import junit.framework.TestCase;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41 * See http://bugzilla.slf4j.org/show_bug.cgi?id=261
42 * @author Thorbjorn Ravn Andersen
43 */
44 public class LoggerSerializationTest extends TestCase {
45
46 static class LoggerHolder implements Serializable {
47 private static final long serialVersionUID = 1L;
48
49 private Logger log = LoggerFactory.getLogger(LoggerHolder.class);
50
51 public String toString() {
52 return "log=" + getLog();
53 }
54
55 public Logger getLog() {
56 return log;
57 }
58 }
59
60 public void testCanLoggerBeSerialized() throws IOException, ClassNotFoundException {
61
62 LoggerHolder lh1 = new LoggerHolder();
63
64 ByteArrayOutputStream baos = new ByteArrayOutputStream();
65 ObjectOutputStream out = new ObjectOutputStream(baos);
66 out.writeObject(lh1);
67 out.close();
68
69 lh1 = null;
70
71 byte[] serializedLoggerHolder = baos.toByteArray();
72
73 InputStream is = new ByteArrayInputStream(serializedLoggerHolder);
74 ObjectInputStream in = new ObjectInputStream(is);
75 LoggerHolder lh2 = (LoggerHolder) in.readObject();
76
77 Assert.assertNotNull(lh2);
78 Assert.assertNotNull(lh2.getLog());
79 lh2.getLog().info("You must see this message as a log message");
80 }
81
82 }
0 <project
1 xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
5 <modelVersion>4.0.0</modelVersion>
6
7 <parent>
8 <groupId>org.slf4j</groupId>
9 <artifactId>slf4j-parent</artifactId>
10 <version>1.7.12</version>
11 </parent>
12
13 <artifactId>slf4j-log4j12</artifactId>
14
15 <packaging>jar</packaging>
16 <name>SLF4J LOG4J-12 Binding</name>
17 <description>SLF4J LOG4J-12 Binding</description>
18 <url>http://www.slf4j.org</url>
19
20
21 <dependencies>
22 <dependency>
23 <groupId>org.slf4j</groupId>
24 <artifactId>slf4j-api</artifactId>
25 </dependency>
26
27 <dependency>
28 <groupId>log4j</groupId>
29 <artifactId>log4j</artifactId>
30 </dependency>
31 </dependencies>
32
33 <build>
34 <plugins>
35 <plugin>
36 <groupId>org.apache.maven.plugins</groupId>
37 <artifactId>maven-jar-plugin</artifactId>
38 <configuration>
39 <archive>
40 <manifestEntries>
41 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
42 <Bundle-Description>${project.description}</Bundle-Description>
43 <Implementation-Version>${project.version}</Implementation-Version>
44 </manifestEntries>
45 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
46 </archive>
47 </configuration>
48 </plugin>
49 </plugins>
50 </build>
51
52 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.io.Serializable;
27
28 import org.apache.log4j.Level;
29 import org.slf4j.Logger;
30 import org.slf4j.Marker;
31 import org.slf4j.helpers.FormattingTuple;
32 import org.slf4j.helpers.MarkerIgnoringBase;
33 import org.slf4j.helpers.MessageFormatter;
34 import org.slf4j.spi.LocationAwareLogger;
35
36 /**
37 * A wrapper over {@link org.apache.log4j.Logger org.apache.log4j.Logger} in
38 * conforming to the {@link Logger} interface.
39 *
40 * <p>
41 * Note that the logging levels mentioned in this class refer to those defined
42 * in the <a
43 * href="http://logging.apache.org/log4j/docs/api/org/apache/log4j/Level.html">
44 * <code>org.apache.log4j.Level</code></a> class.
45 *
46 * <p>
47 * The TRACE level was introduced in log4j version 1.2.12. In order to avoid
48 * crashing the host application, in the case the log4j version in use predates
49 * 1.2.12, the TRACE level will be mapped as DEBUG. See also <a
50 * href="http://bugzilla.slf4j.org/show_bug.cgi?id=68">bug 68</a>.
51 *
52 * @author Ceki G&uuml;lc&uuml;
53 */
54 public final class Log4jLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger, Serializable {
55
56 private static final long serialVersionUID = 6182834493563598289L;
57
58 final transient org.apache.log4j.Logger logger;
59
60 /**
61 * Following the pattern discussed in pages 162 through 168 of "The complete
62 * log4j manual".
63 */
64 final static String FQCN = Log4jLoggerAdapter.class.getName();
65
66 // Does the log4j version in use recognize the TRACE level?
67 // The trace level was introduced in log4j 1.2.12.
68 final boolean traceCapable;
69
70 // WARN: Log4jLoggerAdapter constructor should have only package access so
71 // that
72 // only Log4jLoggerFactory be able to create one.
73 Log4jLoggerAdapter(org.apache.log4j.Logger logger) {
74 this.logger = logger;
75 this.name = logger.getName();
76 traceCapable = isTraceCapable();
77 }
78
79 private boolean isTraceCapable() {
80 try {
81 logger.isTraceEnabled();
82 return true;
83 } catch (NoSuchMethodError e) {
84 return false;
85 }
86 }
87
88 /**
89 * Is this logger instance enabled for the TRACE level?
90 *
91 * @return True if this Logger is enabled for level TRACE, false otherwise.
92 */
93 public boolean isTraceEnabled() {
94 if (traceCapable) {
95 return logger.isTraceEnabled();
96 } else {
97 return logger.isDebugEnabled();
98 }
99 }
100
101 /**
102 * Log a message object at level TRACE.
103 *
104 * @param msg
105 * - the message object to be logged
106 */
107 public void trace(String msg) {
108 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, null);
109 }
110
111 /**
112 * Log a message at level TRACE according to the specified format and
113 * argument.
114 *
115 * <p>
116 * This form avoids superfluous object creation when the logger is disabled
117 * for level TRACE.
118 * </p>
119 *
120 * @param format
121 * the format string
122 * @param arg
123 * the argument
124 */
125 public void trace(String format, Object arg) {
126 if (isTraceEnabled()) {
127 FormattingTuple ft = MessageFormatter.format(format, arg);
128 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable());
129 }
130 }
131
132 /**
133 * Log a message at level TRACE according to the specified format and
134 * arguments.
135 *
136 * <p>
137 * This form avoids superfluous object creation when the logger is disabled
138 * for the TRACE level.
139 * </p>
140 *
141 * @param format
142 * the format string
143 * @param arg1
144 * the first argument
145 * @param arg2
146 * the second argument
147 */
148 public void trace(String format, Object arg1, Object arg2) {
149 if (isTraceEnabled()) {
150 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
151 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable());
152 }
153 }
154
155 /**
156 * Log a message at level TRACE according to the specified format and
157 * arguments.
158 *
159 * <p>
160 * This form avoids superfluous object creation when the logger is disabled
161 * for the TRACE level.
162 * </p>
163 *
164 * @param format
165 * the format string
166 * @param arguments
167 * an array of arguments
168 */
169 public void trace(String format, Object... arguments) {
170 if (isTraceEnabled()) {
171 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
172 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable());
173 }
174 }
175
176 /**
177 * Log an exception (throwable) at level TRACE with an accompanying message.
178 *
179 * @param msg
180 * the message accompanying the exception
181 * @param t
182 * the exception (throwable) to log
183 */
184 public void trace(String msg, Throwable t) {
185 logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, t);
186 }
187
188 /**
189 * Is this logger instance enabled for the DEBUG level?
190 *
191 * @return True if this Logger is enabled for level DEBUG, false otherwise.
192 */
193 public boolean isDebugEnabled() {
194 return logger.isDebugEnabled();
195 }
196
197 /**
198 * Log a message object at level DEBUG.
199 *
200 * @param msg
201 * - the message object to be logged
202 */
203 public void debug(String msg) {
204 logger.log(FQCN, Level.DEBUG, msg, null);
205 }
206
207 /**
208 * Log a message at level DEBUG according to the specified format and
209 * argument.
210 *
211 * <p>
212 * This form avoids superfluous object creation when the logger is disabled
213 * for level DEBUG.
214 * </p>
215 *
216 * @param format
217 * the format string
218 * @param arg
219 * the argument
220 */
221 public void debug(String format, Object arg) {
222 if (logger.isDebugEnabled()) {
223 FormattingTuple ft = MessageFormatter.format(format, arg);
224 logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
225 }
226 }
227
228 /**
229 * Log a message at level DEBUG according to the specified format and
230 * arguments.
231 *
232 * <p>
233 * This form avoids superfluous object creation when the logger is disabled
234 * for the DEBUG level.
235 * </p>
236 *
237 * @param format
238 * the format string
239 * @param arg1
240 * the first argument
241 * @param arg2
242 * the second argument
243 */
244 public void debug(String format, Object arg1, Object arg2) {
245 if (logger.isDebugEnabled()) {
246 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
247 logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
248 }
249 }
250
251 /**
252 * Log a message at level DEBUG according to the specified format and
253 * arguments.
254 *
255 * <p>
256 * This form avoids superfluous object creation when the logger is disabled
257 * for the DEBUG level.
258 * </p>
259 *
260 * @param format
261 * the format string
262 * @param arguments an array of arguments
263 */
264 public void debug(String format, Object... arguments) {
265 if (logger.isDebugEnabled()) {
266 FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
267 logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable());
268 }
269 }
270
271 /**
272 * Log an exception (throwable) at level DEBUG with an accompanying message.
273 *
274 * @param msg
275 * the message accompanying the exception
276 * @param t
277 * the exception (throwable) to log
278 */
279 public void debug(String msg, Throwable t) {
280 logger.log(FQCN, Level.DEBUG, msg, t);
281 }
282
283 /**
284 * Is this logger instance enabled for the INFO level?
285 *
286 * @return True if this Logger is enabled for the INFO level, false otherwise.
287 */
288 public boolean isInfoEnabled() {
289 return logger.isInfoEnabled();
290 }
291
292 /**
293 * Log a message object at the INFO level.
294 *
295 * @param msg
296 * - the message object to be logged
297 */
298 public void info(String msg) {
299 logger.log(FQCN, Level.INFO, msg, null);
300 }
301
302 /**
303 * Log a message at level INFO according to the specified format and argument.
304 *
305 * <p>
306 * This form avoids superfluous object creation when the logger is disabled
307 * for the INFO level.
308 * </p>
309 *
310 * @param format
311 * the format string
312 * @param arg
313 * the argument
314 */
315 public void info(String format, Object arg) {
316 if (logger.isInfoEnabled()) {
317 FormattingTuple ft = MessageFormatter.format(format, arg);
318 logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
319 }
320 }
321
322 /**
323 * Log a message at the INFO level according to the specified format and
324 * arguments.
325 *
326 * <p>
327 * This form avoids superfluous object creation when the logger is disabled
328 * for the INFO level.
329 * </p>
330 *
331 * @param format
332 * the format string
333 * @param arg1
334 * the first argument
335 * @param arg2
336 * the second argument
337 */
338 public void info(String format, Object arg1, Object arg2) {
339 if (logger.isInfoEnabled()) {
340 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
341 logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
342 }
343 }
344
345 /**
346 * Log a message at level INFO according to the specified format and
347 * arguments.
348 *
349 * <p>
350 * This form avoids superfluous object creation when the logger is disabled
351 * for the INFO level.
352 * </p>
353 *
354 * @param format
355 * the format string
356 * @param argArray
357 * an array of arguments
358 */
359 public void info(String format, Object... argArray) {
360 if (logger.isInfoEnabled()) {
361 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
362 logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable());
363 }
364 }
365
366 /**
367 * Log an exception (throwable) at the INFO level with an accompanying
368 * message.
369 *
370 * @param msg
371 * the message accompanying the exception
372 * @param t
373 * the exception (throwable) to log
374 */
375 public void info(String msg, Throwable t) {
376 logger.log(FQCN, Level.INFO, msg, t);
377 }
378
379 /**
380 * Is this logger instance enabled for the WARN level?
381 *
382 * @return True if this Logger is enabled for the WARN level, false otherwise.
383 */
384 public boolean isWarnEnabled() {
385 return logger.isEnabledFor(Level.WARN);
386 }
387
388 /**
389 * Log a message object at the WARN level.
390 *
391 * @param msg
392 * - the message object to be logged
393 */
394 public void warn(String msg) {
395 logger.log(FQCN, Level.WARN, msg, null);
396 }
397
398 /**
399 * Log a message at the WARN level according to the specified format and
400 * argument.
401 *
402 * <p>
403 * This form avoids superfluous object creation when the logger is disabled
404 * for the WARN level.
405 * </p>
406 *
407 * @param format
408 * the format string
409 * @param arg
410 * the argument
411 */
412 public void warn(String format, Object arg) {
413 if (logger.isEnabledFor(Level.WARN)) {
414 FormattingTuple ft = MessageFormatter.format(format, arg);
415 logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
416 }
417 }
418
419 /**
420 * Log a message at the WARN level according to the specified format and
421 * arguments.
422 *
423 * <p>
424 * This form avoids superfluous object creation when the logger is disabled
425 * for the WARN level.
426 * </p>
427 *
428 * @param format
429 * the format string
430 * @param arg1
431 * the first argument
432 * @param arg2
433 * the second argument
434 */
435 public void warn(String format, Object arg1, Object arg2) {
436 if (logger.isEnabledFor(Level.WARN)) {
437 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
438 logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
439 }
440 }
441
442 /**
443 * Log a message at level WARN according to the specified format and
444 * arguments.
445 *
446 * <p>
447 * This form avoids superfluous object creation when the logger is disabled
448 * for the WARN level.
449 * </p>
450 *
451 * @param format
452 * the format string
453 * @param argArray
454 * an array of arguments
455 */
456 public void warn(String format, Object... argArray) {
457 if (logger.isEnabledFor(Level.WARN)) {
458 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
459 logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable());
460 }
461 }
462
463 /**
464 * Log an exception (throwable) at the WARN level with an accompanying
465 * message.
466 *
467 * @param msg
468 * the message accompanying the exception
469 * @param t
470 * the exception (throwable) to log
471 */
472 public void warn(String msg, Throwable t) {
473 logger.log(FQCN, Level.WARN, msg, t);
474 }
475
476 /**
477 * Is this logger instance enabled for level ERROR?
478 *
479 * @return True if this Logger is enabled for level ERROR, false otherwise.
480 */
481 public boolean isErrorEnabled() {
482 return logger.isEnabledFor(Level.ERROR);
483 }
484
485 /**
486 * Log a message object at the ERROR level.
487 *
488 * @param msg
489 * - the message object to be logged
490 */
491 public void error(String msg) {
492 logger.log(FQCN, Level.ERROR, msg, null);
493 }
494
495 /**
496 * Log a message at the ERROR level according to the specified format and
497 * argument.
498 *
499 * <p>
500 * This form avoids superfluous object creation when the logger is disabled
501 * for the ERROR level.
502 * </p>
503 *
504 * @param format
505 * the format string
506 * @param arg
507 * the argument
508 */
509 public void error(String format, Object arg) {
510 if (logger.isEnabledFor(Level.ERROR)) {
511 FormattingTuple ft = MessageFormatter.format(format, arg);
512 logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
513 }
514 }
515
516 /**
517 * Log a message at the ERROR level according to the specified format and
518 * arguments.
519 *
520 * <p>
521 * This form avoids superfluous object creation when the logger is disabled
522 * for the ERROR level.
523 * </p>
524 *
525 * @param format
526 * the format string
527 * @param arg1
528 * the first argument
529 * @param arg2
530 * the second argument
531 */
532 public void error(String format, Object arg1, Object arg2) {
533 if (logger.isEnabledFor(Level.ERROR)) {
534 FormattingTuple ft = MessageFormatter.format(format, arg1, arg2);
535 logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
536 }
537 }
538
539 /**
540 * Log a message at level ERROR according to the specified format and
541 * arguments.
542 *
543 * <p>
544 * This form avoids superfluous object creation when the logger is disabled
545 * for the ERROR level.
546 * </p>
547 *
548 * @param format
549 * the format string
550 * @param argArray
551 * an array of arguments
552 */
553 public void error(String format, Object... argArray) {
554 if (logger.isEnabledFor(Level.ERROR)) {
555 FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
556 logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable());
557 }
558 }
559
560 /**
561 * Log an exception (throwable) at the ERROR level with an accompanying
562 * message.
563 *
564 * @param msg
565 * the message accompanying the exception
566 * @param t
567 * the exception (throwable) to log
568 */
569 public void error(String msg, Throwable t) {
570 logger.log(FQCN, Level.ERROR, msg, t);
571 }
572
573 public void log(Marker marker, String callerFQCN, int level, String msg, Object[] argArray, Throwable t) {
574 Level log4jLevel;
575 switch (level) {
576 case LocationAwareLogger.TRACE_INT:
577 log4jLevel = traceCapable ? Level.TRACE : Level.DEBUG;
578 break;
579 case LocationAwareLogger.DEBUG_INT:
580 log4jLevel = Level.DEBUG;
581 break;
582 case LocationAwareLogger.INFO_INT:
583 log4jLevel = Level.INFO;
584 break;
585 case LocationAwareLogger.WARN_INT:
586 log4jLevel = Level.WARN;
587 break;
588 case LocationAwareLogger.ERROR_INT:
589 log4jLevel = Level.ERROR;
590 break;
591 default:
592 throw new IllegalStateException("Level number " + level + " is not recognized.");
593 }
594 logger.log(callerFQCN, log4jLevel, msg, t);
595 }
596
597 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.apache.log4j.LogManager;
30 import org.slf4j.ILoggerFactory;
31 import org.slf4j.Logger;
32
33 /**
34 * Log4jLoggerFactory is an implementation of {@link ILoggerFactory} returning
35 * the appropriate named {@link Log4jLoggerAdapter} instance.
36 *
37 * @author Ceki G&uuml;lc&uuml;
38 */
39 public class Log4jLoggerFactory implements ILoggerFactory {
40
41 // key: name (String), value: a Log4jLoggerAdapter;
42 ConcurrentMap<String, Logger> loggerMap;
43
44 public Log4jLoggerFactory() {
45 loggerMap = new ConcurrentHashMap<String, Logger>();
46 }
47
48 /*
49 * (non-Javadoc)
50 *
51 * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String)
52 */
53 public Logger getLogger(String name) {
54 Logger slf4jLogger = loggerMap.get(name);
55 if (slf4jLogger != null) {
56 return slf4jLogger;
57 } else {
58 org.apache.log4j.Logger log4jLogger;
59 if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME))
60 log4jLogger = LogManager.getRootLogger();
61 else
62 log4jLogger = LogManager.getLogger(name);
63
64 Logger newInstance = new Log4jLoggerAdapter(log4jLogger);
65 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
66 return oldInstance == null ? newInstance : oldInstance;
67 }
68 }
69 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.Map;
29
30 import org.slf4j.spi.MDCAdapter;
31
32 public class Log4jMDCAdapter implements MDCAdapter {
33
34 public void clear() {
35 @SuppressWarnings("rawtypes")
36 Map map = org.apache.log4j.MDC.getContext();
37 if (map != null) {
38 map.clear();
39 }
40 }
41
42 public String get(String key) {
43 return (String) org.apache.log4j.MDC.get(key);
44 }
45
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 }
61
62 public void remove(String key) {
63 org.apache.log4j.MDC.remove(key);
64 }
65
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 }
75
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 }
90 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.apache.log4j.Level;
27 import org.slf4j.ILoggerFactory;
28 import org.slf4j.LoggerFactory;
29 import org.slf4j.helpers.Util;
30 import org.slf4j.spi.LoggerFactoryBinder;
31
32 /**
33 * The binding of {@link LoggerFactory} class with an actual instance of
34 * {@link ILoggerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticLoggerBinder implements LoggerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 *
43 */
44 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
45
46 /**
47 * Return the singleton of this class.
48 *
49 * @return the StaticLoggerBinder singleton
50 */
51 public static final StaticLoggerBinder getSingleton() {
52 return SINGLETON;
53 }
54
55 /**
56 * Declare the version of the SLF4J API this implementation is compiled
57 * against. The value of this field is usually modified with each release.
58 */
59 // to avoid constant folding by the compiler, this field must *not* be final
60 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
61
62 private static final String loggerFactoryClassStr = Log4jLoggerFactory.class.getName();
63
64 /**
65 * The ILoggerFactory instance returned by the {@link #getLoggerFactory}
66 * method should always be the same object
67 */
68 private final ILoggerFactory loggerFactory;
69
70 private StaticLoggerBinder() {
71 loggerFactory = new Log4jLoggerFactory();
72 try {
73 @SuppressWarnings("unused")
74 Level level = Level.TRACE;
75 } catch (NoSuchFieldError nsfe) {
76 Util.report("This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version");
77 }
78 }
79
80 public ILoggerFactory getLoggerFactory() {
81 return loggerFactory;
82 }
83
84 public String getLoggerFactoryClassStr() {
85 return loggerFactoryClassStr;
86 }
87 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.spi.MDCAdapter;
27
28 /**
29 * This implementation is bound to {@link Log4jMDCAdapter}.
30 *
31 * @author Ceki G&uuml;lc&uuml;
32 */
33 public class StaticMDCBinder {
34
35 /**
36 * The unique instance of this class.
37 */
38 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
39
40 private StaticMDCBinder() {
41 }
42
43 /**
44 * Currently this method always returns an instance of
45 * {@link StaticMDCBinder}.
46 */
47 public MDCAdapter getMDCA() {
48 return new Log4jMDCAdapter();
49 }
50
51 public String getMDCAdapterClassStr() {
52 return Log4jMDCAdapter.class.getName();
53 }
54 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Currently this method always returns an instance of
52 * {@link BasicMarkerFactory}.
53 */
54 public IMarkerFactory getMarkerFactory() {
55 return markerFactory;
56 }
57
58 /**
59 * Currently, this method returns the class name of
60 * {@link BasicMarkerFactory}.
61 */
62 public String getMarkerFactoryClassStr() {
63 return BasicMarkerFactory.class.getName();
64 }
65
66 }
0 Implementation-Title: slf4j-log4j12
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.log4j12
3 Bundle-Name: slf4j-log4j12
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, org.apache.log4j
8 Fragment-Host: slf4j.api
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.util.HashMap;
27 import java.util.Map;
28
29 import org.apache.log4j.spi.LoggingEvent;
30
31 import junit.framework.TestCase;
32
33 /**
34 * Test whether invoking the SLF4J API causes problems or not.
35 *
36 * @author Ceki Gulcu
37 *
38 */
39 public class InvocationTest extends TestCase {
40
41 ListAppender listAppender = new ListAppender();
42 org.apache.log4j.Logger root;
43
44 public InvocationTest(String arg0) {
45 super(arg0);
46 }
47
48 protected void setUp() throws Exception {
49 super.setUp();
50 root = org.apache.log4j.Logger.getRootLogger();
51 root.addAppender(listAppender);
52
53 }
54
55 protected void tearDown() throws Exception {
56 super.tearDown();
57 root.getLoggerRepository().resetConfiguration();
58 }
59
60 public void test1() {
61 Logger logger = LoggerFactory.getLogger("test1");
62 logger.debug("Hello world.");
63 assertEquals(1, listAppender.list.size());
64 }
65
66 public void test2() {
67 Integer i1 = new Integer(1);
68 Integer i2 = new Integer(2);
69 Integer i3 = new Integer(3);
70 Exception e = new Exception("This is a test exception.");
71 Logger logger = LoggerFactory.getLogger("test2");
72
73 logger.trace("Hello trace.");
74
75 logger.debug("Hello world 1.");
76 logger.debug("Hello world {}", i1);
77 logger.debug("val={} val={}", i1, i2);
78 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
79
80 logger.debug("Hello world 2", e);
81 logger.info("Hello world 2.");
82
83 logger.warn("Hello world 3.");
84 logger.warn("Hello world 3", e);
85
86 logger.error("Hello world 4.");
87 logger.error("Hello world {}", new Integer(3));
88 logger.error("Hello world 4.", e);
89 assertEquals(11, listAppender.list.size());
90 }
91
92 public void testNull() {
93 Logger logger = LoggerFactory.getLogger("testNull");
94 logger.trace(null);
95 logger.debug(null);
96 logger.info(null);
97 logger.warn(null);
98 logger.error(null);
99
100 Exception e = new Exception("This is a test exception.");
101 logger.debug(null, e);
102 logger.info(null, e);
103 logger.warn(null, e);
104 logger.error(null, e);
105 assertEquals(8, listAppender.list.size());
106 }
107
108 // http://bugzilla.slf4j.org/show_bug.cgi?id=78
109 public void testNullParameter_BUG78() {
110 Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78");
111 String[] parameters = null;
112 String msg = "hello {}";
113
114 logger.debug(msg, parameters);
115 assertEquals(1, listAppender.list.size());
116 LoggingEvent e = (LoggingEvent) listAppender.list.get(0);
117 assertEquals(msg, e.getMessage());
118 }
119
120 public void testMarker() {
121 Logger logger = LoggerFactory.getLogger("testMarker");
122 Marker blue = MarkerFactory.getMarker("BLUE");
123 logger.trace(blue, "hello");
124 logger.debug(blue, "hello");
125 logger.info(blue, "hello");
126 logger.warn(blue, "hello");
127 logger.error(blue, "hello");
128
129 logger.debug(blue, "hello {}", "world");
130 logger.info(blue, "hello {}", "world");
131 logger.warn(blue, "hello {}", "world");
132 logger.error(blue, "hello {}", "world");
133
134 logger.debug(blue, "hello {} and {} ", "world", "universe");
135 logger.info(blue, "hello {} and {} ", "world", "universe");
136 logger.warn(blue, "hello {} and {} ", "world", "universe");
137 logger.error(blue, "hello {} and {} ", "world", "universe");
138 assertEquals(12, listAppender.list.size());
139 }
140
141 public void testMDC() {
142 MDC.put("k", "v");
143 assertNotNull(MDC.get("k"));
144 assertEquals("v", MDC.get("k"));
145
146 MDC.remove("k");
147 assertNull(MDC.get("k"));
148
149 MDC.put("k1", "v1");
150 assertEquals("v1", MDC.get("k1"));
151 MDC.clear();
152 assertNull(MDC.get("k1"));
153
154 try {
155 MDC.put(null, "x");
156 fail("null keys are invalid");
157 } catch (IllegalArgumentException e) {
158 }
159 }
160
161 public void testMDCContextMapValues() {
162 Map<String, String> map = new HashMap<String, String>();
163 map.put("ka", "va");
164 map.put("kb", "vb");
165
166 MDC.put("k", "v");
167 assertEquals("v", MDC.get("k"));
168 MDC.setContextMap(map);
169 assertNull(MDC.get("k"));
170 assertEquals("va", MDC.get("ka"));
171 assertEquals("vb", MDC.get("kb"));
172 }
173
174 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.apache.log4j.AppenderSkeleton;
30 import org.apache.log4j.spi.LoggingEvent;
31
32 public class ListAppender extends AppenderSkeleton {
33
34 public List<LoggingEvent> list = new ArrayList<LoggingEvent>();
35
36 public boolean extractLocationInfo = false;
37
38 protected void append(LoggingEvent event) {
39 list.add(event);
40 if (extractLocationInfo) {
41 event.getLocationInformation();
42 }
43 }
44
45 public void close() {
46 }
47
48 public boolean requiresLayout() {
49 return false;
50 }
51
52 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.Random;
27
28 import org.apache.log4j.AppenderSkeleton;
29 import org.apache.log4j.spi.LoggingEvent;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 public class RecursiveAppender extends AppenderSkeleton {
34
35 int diff = new Random().nextInt();
36
37 public RecursiveAppender() {
38 System.out.println("in RecursiveAppender constructor");
39 Logger logger = LoggerFactory.getLogger("RecursiveAppender" + diff);
40 System.out.println("logger class=" + logger.getClass().getName());
41 logger.info("Calling a logger in the constructor");
42 }
43
44 protected void append(LoggingEvent arg0) {
45 }
46
47 public void close() {
48 }
49
50 public boolean requiresLayout() {
51 return false;
52 }
53 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.Random;
27
28 import junit.framework.TestCase;
29
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 public class RecursiveInitializationTest extends TestCase {
34
35 // value of LogManager.DEFAULT_CONFIGURATION_KEY;
36 static String CONFIG_FILE_KEY = "log4j.configuration";
37
38 int diff = new Random().nextInt(10000);
39
40 protected void setUp() throws Exception {
41 System.setProperty(CONFIG_FILE_KEY, "recursiveInit.properties");
42 super.setUp();
43 }
44
45 protected void tearDown() throws Exception {
46 System.clearProperty(CONFIG_FILE_KEY);
47 super.tearDown();
48 }
49
50 public void testLog4j() {
51 Logger logger = LoggerFactory.getLogger("x" + diff);
52 System.out.println("logger class=" + logger.getClass().getName());
53 logger.info("hello");
54 }
55
56 }
0 log4j.debug=true
1 log4j.rootLogger=DEBUG, RECURSIVE
2
3 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
4 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
5 log4j.appender.CONSOLE.layout.ConversionPattern=%d [%t] %c - %m%n
6
7 log4j.appender.RECURSIVE=org.slf4j.impl.RecursiveAppender
0 <project
1 xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
5 <modelVersion>4.0.0</modelVersion>
6
7 <parent>
8 <groupId>org.slf4j</groupId>
9 <artifactId>slf4j-parent</artifactId>
10 <version>1.7.12</version>
11 </parent>
12
13 <artifactId>slf4j-migrator</artifactId>
14
15 <packaging>jar</packaging>
16 <name>SLF4J Migrator</name>
17 <description>SLF4J Migrator</description>
18
19
20 <build>
21 <plugins>
22 <plugin>
23 <groupId>org.apache.maven.plugins</groupId>
24 <artifactId>maven-compiler-plugin</artifactId>
25 <configuration>
26 <source>${required.jdk.version}</source>
27 <target>${required.jdk.version}</target>
28 </configuration>
29 </plugin>
30
31 <plugin>
32 <groupId>org.apache.maven.plugins</groupId>
33 <artifactId>maven-jar-plugin</artifactId>
34 <configuration>
35 <archive>
36 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
37 </archive>
38 </configuration>
39 </plugin>
40
41 </plugins>
42
43 </build>
44
45 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 public class Constant {
27
28 public final static int JCL_TO_SLF4J = 0;
29 public final static int LOG4J_TO_SLF4J = 1;
30 public final static int JUL_TO_SLF4J = 2;
31 public final static int NOP_TO_SLF4J = 3;
32
33 public final static int NB_FILES_MAX = 1;
34
35 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 public class ConversionException extends Exception {
27
28 /**
29 *
30 */
31 private static final long serialVersionUID = 498961799888576668L;
32
33 private String detail;
34
35 public static final String NOT_IMPLEMENTED = "Conversion mode not implemented yet";
36 public static final String INVALID_DIRECTORY = "Invalid source directory";
37 public static final String FILE_COPY = "Error during file copy";
38
39 public ConversionException(String message) {
40 super(message);
41 }
42
43 public ConversionException(String message, String detail) {
44 super(message);
45 this.detail = detail;
46 }
47
48 public String getDetail() {
49 return detail;
50 }
51
52 public void setDetail(String detail) {
53 this.detail = detail;
54 }
55
56 public void print() {
57 if (getMessage() != null) {
58 System.out.println(getMessage());
59 }
60 }
61
62 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 import org.slf4j.migrator.internal.ProgressListener;
31
32 public class FileSelector {
33
34 private List<File> javaFileList = new ArrayList<File>();
35
36 ProgressListener pl;
37
38 FileSelector(ProgressListener pl) {
39 this.pl = pl;
40 }
41
42 public List<File> selectJavaFilesInFolder(File folder) {
43 if (folder.isDirectory()) {
44 selectFiles(folder);
45 return javaFileList;
46 } else {
47 throw new IllegalArgumentException("[" + folder + "] is not a directory");
48 }
49 }
50
51 private void selectFiles(File file) {
52 if (file.isDirectory()) {
53 pl.onDirectory(file);
54 File[] files = file.listFiles();
55 if (files != null) {
56 for (int i = 0; i < files.length; i++) {
57 selectFiles(files[i]);
58 }
59 }
60 } else {
61 if (file.getName().endsWith(".java")) {
62 pl.onFileAddition(file);
63 javaFileList.add(file);
64 }
65
66 }
67 }
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.BufferedReader;
27 import java.io.ByteArrayInputStream;
28 import java.io.ByteArrayOutputStream;
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.FileOutputStream;
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.io.OutputStream;
35 import java.io.Reader;
36
37 import org.slf4j.migrator.internal.ProgressListener;
38 import org.slf4j.migrator.line.LineConverter;
39 import org.slf4j.migrator.line.RuleSet;
40
41 public class InplaceFileConverter {
42
43 final static int BUFFER_LEN = 8 * 1024;
44 final LineConverter lineConverter;
45 final String lineTerminator;
46 final ProgressListener pl;
47
48 InplaceFileConverter(RuleSet ruleSet, ProgressListener pl) {
49 this.lineConverter = new LineConverter(ruleSet);
50 lineTerminator = System.getProperty("line.separator");
51 this.pl = pl;
52 }
53
54 private byte[] readIntoByteArray(File file) throws IOException {
55 FileInputStream fis = new FileInputStream(file);
56 ByteArrayOutputStream baos = new ByteArrayOutputStream();
57 int n = 0;
58 byte[] buffer = new byte[BUFFER_LEN];
59 while ((n = fis.read(buffer)) != -1) {
60 // System.out.println("ba="+new String(buffer, "UTF-8"));
61 baos.write(buffer, 0, n);
62 }
63 fis.close();
64 return baos.toByteArray();
65 }
66
67 void convert(File file) throws IOException {
68 byte[] originalBytes = readIntoByteArray(file);
69 byte[] convertedBytes = convertIntoTempByteArray(originalBytes);
70 if (lineConverter.atLeastOneMatchOccured()) {
71 // System.out.println("Converting ["+file+"]");
72 writeConvertedBytesIntoFile(file, convertedBytes);
73 pl.onInplaceConversion(file);
74 } else {
75 // System.out.println("Not touching ["+file+"]");
76 }
77 }
78
79 private void writeConvertedBytesIntoFile(File file, byte[] convertedBytes) throws IOException {
80 FileOutputStream fos = new FileOutputStream(file);
81 fos.write(convertedBytes);
82 fos.flush();
83 fos.close();
84 }
85
86 private byte[] convertIntoTempByteArray(byte[] input) throws IOException {
87 ByteArrayInputStream bais = new ByteArrayInputStream(input);
88 Reader reader = new InputStreamReader(bais);
89 BufferedReader breader = new BufferedReader(reader);
90 ByteArrayOutputStream baos = new ByteArrayOutputStream();
91 while (true) {
92 String line = breader.readLine();
93 if (line != null) {
94 String[] replacement = lineConverter.getReplacement(line);
95 writeReplacement(baos, replacement);
96 } else {
97 break;
98 }
99 }
100 return baos.toByteArray();
101 }
102
103 private void writeReplacement(OutputStream os, String[] replacement) throws IOException {
104 for (int i = 0; i < replacement.length; i++) {
105 os.write(replacement[i].getBytes());
106 os.write(lineTerminator.getBytes());
107 }
108 }
109 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j.migrator;
26
27 import javax.swing.SwingUtilities;
28
29 import org.slf4j.migrator.internal.MigratorFrame;
30
31 /**
32 * Main entry point to the migrator.
33 *
34 * @author Ceki G&uuml;lc&uuml;
35 */
36 public class Main {
37
38 public static void main(String[] args) {
39 System.out.println("Starting SLF4J Migrator");
40 SwingUtilities.invokeLater(new Runnable() {
41 public void run() {
42 MigratorFrame inst = new MigratorFrame();
43 inst.setLocationRelativeTo(null);
44 inst.setVisible(true);
45 }
46 });
47 }
48
49 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Iterator;
30 import java.util.List;
31
32 import javax.swing.SwingUtilities;
33
34 import org.slf4j.migrator.internal.MigratorFrame;
35 import org.slf4j.migrator.internal.ProgressListener;
36 import org.slf4j.migrator.line.RuleSet;
37
38 public class ProjectConverter {
39
40 private RuleSet ruleSet;
41 private List<ConversionException> exception;
42
43 ProgressListener progressListener;
44
45 public static void main(String[] args) throws IOException {
46 SwingUtilities.invokeLater(new Runnable() {
47 public void run() {
48 MigratorFrame inst = new MigratorFrame();
49 inst.setLocationRelativeTo(null);
50 inst.setVisible(true);
51 }
52 });
53 }
54
55 /**
56 * Ask for concrete matcher implementation depending on the conversion mode
57 * Ask for user confirmation to convert the selected source directory if valid
58 * Ask for user confirmation in case of number of files to convert > 1000
59 *
60 * @param conversionType
61 * @param progressListener
62 */
63 public ProjectConverter(int conversionType, ProgressListener progressListener) {
64 this.progressListener = progressListener;
65 ruleSet = RuleSetFactory.getMatcherImpl(conversionType);
66 if (ruleSet == null) {
67 addException(new ConversionException(ConversionException.NOT_IMPLEMENTED));
68 }
69 }
70
71 public void convertProject(File folder) {
72 FileSelector fs = new FileSelector(progressListener);
73 List<File> fileList = fs.selectJavaFilesInFolder(folder);
74 scanFileList(fileList);
75 progressListener.onDone();
76 }
77
78 /**
79 * Convert a list of files
80 *
81 * @param lstFiles
82 */
83 private void scanFileList(List<File> lstFiles) {
84 progressListener.onFileScanBegin();
85 Iterator<File> itFile = lstFiles.iterator();
86 while (itFile.hasNext()) {
87 File currentFile = itFile.next();
88 progressListener.onFileScan(currentFile);
89 scanFile(currentFile);
90 }
91 }
92
93 /**
94 * Convert the specified file Read each line and ask matcher implementation
95 * for conversion Rewrite the line returned by matcher
96 *
97 * @param file
98 */
99 private void scanFile(File file) {
100 try {
101 InplaceFileConverter fc = new InplaceFileConverter(ruleSet, progressListener);
102 fc.convert(file);
103 } catch (IOException exc) {
104 addException(new ConversionException(exc.toString()));
105 }
106 }
107
108 public void addException(ConversionException exc) {
109 if (exception == null) {
110 exception = new ArrayList<ConversionException>();
111 }
112 exception.add(exc);
113 }
114
115 public void printException() {
116 if (exception != null) {
117 Iterator<ConversionException> iterator = exception.iterator();
118 while (iterator.hasNext()) {
119 ConversionException exc = (ConversionException) iterator.next();
120 exc.print();
121 }
122 exception = null;
123 }
124 }
125 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import org.slf4j.migrator.line.EmptyRuleSet;
27 import org.slf4j.migrator.line.JCLRuleSet;
28 import org.slf4j.migrator.line.JULRuleSet;
29 import org.slf4j.migrator.line.Log4jRuleSet;
30 import org.slf4j.migrator.line.RuleSet;
31
32 /**
33 * This class runs Pattern matching with java.util.regex using Patterns defined
34 * in concrete implementations
35 *
36 * @author jean-noelcharpin
37 *
38 */
39 public abstract class RuleSetFactory {
40
41 /**
42 * Return matcher implementation depending on the conversion mode
43 *
44 * @param conversionType
45 * @return AbstractMatcher implementation
46 */
47 public static RuleSet getMatcherImpl(int conversionType) {
48 switch (conversionType) {
49 case Constant.JCL_TO_SLF4J:
50 return new JCLRuleSet();
51 case Constant.LOG4J_TO_SLF4J:
52 return new Log4jRuleSet();
53 case Constant.JUL_TO_SLF4J:
54 return new JULRuleSet();
55 case Constant.NOP_TO_SLF4J:
56 return new EmptyRuleSet();
57 default:
58 return null;
59 }
60 }
61 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 public class Abbreviator {
27 static final String FILLER = "...";
28
29 final char folderSeparator;
30 final int invariantPrefixLength;
31 final int desiredLength;
32
33 public Abbreviator(int invariantPrefixLength, int desiredLength, char folderSeparator) {
34 this.invariantPrefixLength = invariantPrefixLength;
35 this.desiredLength = desiredLength;
36 this.folderSeparator = folderSeparator;
37 }
38
39 public String abbreviate(String filename) {
40 if (filename.length() <= desiredLength) {
41 return filename;
42 } else {
43
44 int firstIndex = filename.indexOf(folderSeparator, invariantPrefixLength);
45 if (firstIndex == -1) {
46 // we cant't process this string
47 return filename;
48 }
49 StringBuilder buf = new StringBuilder(desiredLength);
50 buf.append(filename.substring(0, firstIndex + 1));
51 buf.append(FILLER);
52 int nextIndex = computeNextIndex(filename, firstIndex);
53 if (nextIndex != -1) {
54 buf.append(filename.substring(nextIndex));
55 } else {
56 // better long than wrong
57 return filename;
58 }
59
60 if (buf.length() < filename.length()) {
61 return buf.toString();
62 } else {
63 // we tried our best but we are still could not shorten the input
64 return filename;
65 }
66 }
67 }
68
69 int computeNextIndex(String filename, int firstIndex) {
70 int nextIndex = firstIndex + 1;
71 int hitCount = 0;
72 int minToRemove = filename.length() - desiredLength + FILLER.length();
73 while (nextIndex < firstIndex + minToRemove) {
74 int tmpIndex = filename.indexOf(folderSeparator, nextIndex + 1);
75 if (tmpIndex == -1) {
76 if (hitCount == 0) {
77 return -1;
78 } else {
79 return nextIndex;
80 }
81 } else {
82 hitCount++;
83 nextIndex = tmpIndex;
84 }
85 }
86 return nextIndex;
87 }
88 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import java.awt.Component;
27
28 import javax.swing.SpringLayout;
29
30 public class SpringLayoutHelper {
31
32 final SpringLayout sl;
33 final int basicPadding;
34
35 public SpringLayoutHelper(SpringLayout springLayout, int basicPadding) {
36 sl = springLayout;
37 this.basicPadding = basicPadding;
38 }
39
40 public void placeToTheRight(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) {
41 sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, SpringLayout.EAST, relativeTo);
42
43 sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, SpringLayout.NORTH, relativeTo);
44 }
45
46 public void placeToTheRight(Component relativeTo, Component componentToPlace) {
47 placeToTheRight(relativeTo, componentToPlace, basicPadding, 0);
48 }
49
50 public void placeBelow(Component relativeTo, Component componentToPlace) {
51 placeBelow(relativeTo, componentToPlace, 0, basicPadding);
52 }
53
54 public void placeBelow(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) {
55 sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, SpringLayout.WEST, relativeTo);
56
57 sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, SpringLayout.SOUTH, relativeTo);
58 }
59
60 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27
28 import org.slf4j.migrator.ProjectConverter;
29
30 public class ConversionTask implements Runnable {
31
32 final File folder;
33 final MigratorFrame frame;
34 final int conversionType;
35
36 ConversionTask(File folder, MigratorFrame frame, int conversionType) {
37 this.folder = folder;
38 this.frame = frame;
39 this.conversionType = conversionType;
40 }
41
42 public void run() {
43 ProgressListener pl = new ProgressListenerImpl(folder, frame);
44 pl.onMigrationBegin();
45 ProjectConverter converter = new ProjectConverter(conversionType, pl);
46 converter.convertProject(folder);
47 }
48
49 public void launch() {
50 Thread t = new Thread(this);
51 t.setDaemon(true);
52 t.start();
53 }
54
55 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.awt.event.ActionEvent;
27 import java.awt.event.ActionListener;
28 import java.io.File;
29 import java.util.ArrayList;
30 import java.util.List;
31
32 import javax.swing.ButtonGroup;
33 import javax.swing.JButton;
34 import javax.swing.JCheckBox;
35 import javax.swing.JFileChooser;
36 import javax.swing.JFrame;
37 import javax.swing.JLabel;
38 import javax.swing.JOptionPane;
39 import javax.swing.JProgressBar;
40 import javax.swing.JRadioButton;
41 import javax.swing.JTextField;
42 import javax.swing.SpringLayout;
43 import javax.swing.WindowConstants;
44
45 import org.slf4j.migrator.Constant;
46 import org.slf4j.migrator.helper.SpringLayoutHelper;
47
48 /**
49 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
50 * Builder, which is free for non-commercial use. If Jigloo is being used
51 * commercially (ie, by a corporation, company or business for any purpose
52 * whatever) then you should purchase a license for each developer using Jigloo.
53 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
54 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
55 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
56 * ANY CORPORATE OR COMMERCIAL PURPOSE.
57 */
58 public class MigratorFrame extends JFrame implements ActionListener {
59 private static final long serialVersionUID = 1L;
60
61 private static final int BASIC_PADDING = 10;
62 private static final int FOLDER_COLUMNS = 40;
63 private static final String MIGRATE_COMMAND = "MIGRATE_COMMAND";
64 private static final String BROWSE_COMMAND = "BROWSE_COMMAND";
65 static final String EXIT_COMMAND = "EXIT_COMMAND";
66
67 static final int X_SIZE = 700;
68 static final int Y_SIZE = 400;
69
70 private SpringLayout layoutManager = new SpringLayout();
71 private SpringLayoutHelper slh = new SpringLayoutHelper(layoutManager, BASIC_PADDING);
72
73 private JLabel migrationLabel;
74
75 private JRadioButton radioLog4j;
76 private JRadioButton radioJCL;
77 private JRadioButton radioJUL;
78 private ButtonGroup buttonGroup;
79
80 private JTextField folderTextField;
81 private JLabel warningLabel;
82 JButton migrateButton;
83 private JButton browseButton;
84 private JLabel folderLabel;
85
86 private JCheckBox awareCheckBox;
87 private JLabel awareLabel;
88
89 JLabel otherLabel;
90 JProgressBar progressBar;
91 private JFileChooser fileChooser;
92
93 public MigratorFrame() {
94 super();
95 initGUI();
96 }
97
98 private void initGUI() {
99 try {
100 setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
101 getContentPane().setLayout(layoutManager);
102 this.setTitle("SLF4J migrator");
103
104 createComponents();
105 constrainAll();
106 addAllComponentsToContextPane();
107 pack();
108 this.setSize(700, 400);
109 } catch (Exception e) {
110 e.printStackTrace();
111 }
112 }
113
114 private void createComponents() {
115 createMigrationLabel();
116 createRadioJCL();
117 createRadioLog4j();
118 createRadioJUL();
119 createButtonGroup();
120 createFolderLabel();
121 createFolderTextField();
122 createBrowseButton();
123 createMigrateButton();
124 createAwareCheckbox();
125 createAwareLabel();
126 createWarningLabel();
127 createFileChooser();
128
129 otherLabel = new JLabel();
130 otherLabel.setText("");
131 createProgressBar();
132
133 }
134
135 /**
136 *
137 */
138 private void constrainAll() {
139
140 // contrain migration label
141 layoutManager.putConstraint(SpringLayout.WEST, migrationLabel, BASIC_PADDING, SpringLayout.EAST, this);
142
143 layoutManager.putConstraint(SpringLayout.NORTH, migrationLabel, BASIC_PADDING, SpringLayout.NORTH, this);
144
145 slh.placeToTheRight(migrationLabel, radioJCL, BASIC_PADDING, -BASIC_PADDING / 2);
146 slh.placeBelow(radioJCL, radioLog4j, 0, 0);
147
148 slh.placeBelow(radioLog4j, radioJUL, 0, 0);
149
150 slh.placeBelow(migrationLabel, folderLabel, 0, BASIC_PADDING * 6);
151 slh.placeToTheRight(folderLabel, folderTextField);
152 slh.placeToTheRight(folderTextField, browseButton, BASIC_PADDING, -BASIC_PADDING / 2);
153
154 slh.placeBelow(folderLabel, warningLabel, 0, BASIC_PADDING * 3);
155
156 slh.placeBelow(warningLabel, awareCheckBox, 0, (int) (BASIC_PADDING * 1.5));
157 slh.placeToTheRight(awareCheckBox, awareLabel);
158
159 slh.placeBelow(awareCheckBox, migrateButton, 0, BASIC_PADDING * 3);
160
161 slh.placeBelow(migrateButton, otherLabel, 0, BASIC_PADDING * 2);
162
163 slh.placeBelow(otherLabel, progressBar, 0, BASIC_PADDING);
164 }
165
166 private void addAllComponentsToContextPane() {
167 getContentPane().add(migrationLabel);
168 getContentPane().add(radioJCL);
169 getContentPane().add(radioLog4j);
170 getContentPane().add(radioJUL);
171
172 getContentPane().add(folderLabel);
173 getContentPane().add(folderTextField);
174 getContentPane().add(browseButton);
175 getContentPane().add(migrateButton);
176
177 getContentPane().add(awareCheckBox);
178 getContentPane().add(awareLabel);
179
180 getContentPane().add(warningLabel);
181
182 getContentPane().add(otherLabel);
183 getContentPane().add(progressBar);
184 }
185
186 private void createButtonGroup() {
187 buttonGroup = new ButtonGroup();
188 buttonGroup.add(radioJCL);
189 buttonGroup.add(radioLog4j);
190 buttonGroup.add(radioJUL);
191 }
192
193 private void createMigrationLabel() {
194 migrationLabel = new JLabel();
195 migrationLabel.setText("Migration Type");
196 }
197
198 private void createRadioJCL() {
199 radioJCL = new JRadioButton();
200 radioJCL.setText("from Jakarta Commons Logging to SLF4J");
201 radioJCL.setToolTipText("Select this button if you wish to migrate a Java project using Jakarta Commons Logging to use SLF4J.");
202 }
203
204 private void createRadioLog4j() {
205 radioLog4j = new JRadioButton();
206 radioLog4j.setText("from log4j to SLF4J ");
207 radioLog4j.setToolTipText("Select this button if you wish to migrate a Java project using log4j to use SLF4J.");
208 }
209
210 private void createRadioJUL() {
211 radioJUL = new JRadioButton();
212 radioJUL.setText("from JUL to SLF4J ");
213 radioJUL.setToolTipText("Select this button if you wish to migrate a Java project using java.utl.logging (JUL) to use SLF4J.");
214 }
215
216 private void createFolderLabel() {
217 folderLabel = new JLabel();
218 folderLabel.setText("Project Directory");
219 }
220
221 private void createFolderTextField() {
222 folderTextField = new JTextField();
223 folderTextField.setColumns(FOLDER_COLUMNS);
224 }
225
226 private void createBrowseButton() {
227 browseButton = new JButton();
228 browseButton.setText("Browse");
229 browseButton.addActionListener(this);
230 browseButton.setActionCommand(BROWSE_COMMAND);
231 browseButton.setToolTipText("Click this button to browse the file systems on your computer.");
232 }
233
234 private void createAwareCheckbox() {
235 awareCheckBox = new JCheckBox();
236 awareCheckBox.setToolTipText("<html><p>Check this box of you understand that the migration tool<p>will <b>not</b> backup your Java source files.</html>");
237 }
238
239 private void createAwareLabel() {
240 awareLabel = new JLabel();
241 awareLabel.setText("<html>" + "<p>I am aware that this tool will directly modify all Java source files</p>"
242 + "<p>in the selected folder without creating backup files.</p>" + "</html>");
243 }
244
245 private void createWarningLabel() {
246 warningLabel = new JLabel();
247 warningLabel.setText("<html>" + "<p><span color=\"red\">WARNING:</span> This SLF4J migration tool will directly modify all Java source files</p>"
248 + "<p>in the selected project folder without creating a backup of the original files.</p>" + "</html>");
249 }
250
251 private void createMigrateButton() {
252 migrateButton = new JButton();
253 migrateButton.setText("Migrate Project to SLF4J");
254 migrateButton.setToolTipText("Click this button to initiate migration of your project.");
255 migrateButton.addActionListener(this);
256 migrateButton.setActionCommand(MIGRATE_COMMAND);
257 }
258
259 private void createFileChooser() {
260 fileChooser = new JFileChooser();
261 fileChooser.setDialogTitle("Source folder selector");
262 fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
263 }
264
265 private void createProgressBar() {
266 progressBar = new JProgressBar(0, 1);
267 progressBar.setPreferredSize(new java.awt.Dimension((int) (X_SIZE * 0.8), 5));
268 progressBar.setVisible(false);
269 }
270
271 public void disableInput() {
272 radioJCL.setEnabled(false);
273 radioLog4j.setEnabled(false);
274
275 browseButton.setEnabled(false);
276
277 folderTextField.setEnabled(false);
278 awareCheckBox.setEnabled(false);
279 migrateButton.setText("Migration in progress");
280 migrateButton.setEnabled(false);
281
282 }
283
284 public void actionPerformed(ActionEvent e) {
285
286 if (MIGRATE_COMMAND.equals(e.getActionCommand())) {
287
288 List<String> errorList = doSanityAnalysis();
289 if (errorList.size() > 0) {
290 showDialogBox(errorList);
291 } else {
292
293 File projectFolder = new File(folderTextField.getText());
294 int conversionType;
295 if (radioJCL.isSelected()) {
296 conversionType = Constant.JCL_TO_SLF4J;
297 } else if (radioLog4j.isSelected()) {
298 conversionType = Constant.LOG4J_TO_SLF4J;
299 } else if (radioJUL.isSelected()) {
300 conversionType = Constant.JUL_TO_SLF4J;
301 } else {
302 // we cannot possibly reach here
303 throw new IllegalStateException("One of JCL or log4j project must have been previously chosen.");
304 }
305 ConversionTask task = new ConversionTask(projectFolder, this, conversionType);
306 task.launch();
307 }
308 } else if (BROWSE_COMMAND.equals(e.getActionCommand())) {
309 showFileChooser();
310 } else if (EXIT_COMMAND.equals(e.getActionCommand())) {
311 this.dispose();
312 }
313 }
314
315 void showFileChooser() {
316 int returnVal = fileChooser.showOpenDialog(this);
317 if (returnVal == JFileChooser.APPROVE_OPTION) {
318 File selectedFile = fileChooser.getSelectedFile();
319 folderTextField.setText(selectedFile.getAbsolutePath());
320 }
321 }
322
323 List<String> doSanityAnalysis() {
324
325 List<String> errorList = new ArrayList<String>();
326 if (!radioJCL.isSelected() && !radioLog4j.isSelected() && !radioJUL.isSelected()) {
327 errorList.add("Please select the migration type: JCL, log4j, or JUL to SLF4J.");
328 }
329
330 String folder = folderTextField.getText();
331
332 if (folder == null || folder.length() == 0) {
333 errorList.add("Please select the folder of the project to migrate");
334 } else if (!isDirectory(folder)) {
335 errorList.add("[" + folder + "] does not look like a valid folder");
336 }
337
338 if (!awareCheckBox.isSelected()) {
339 errorList.add("Cannot initiate migration unless you acknowledge<p>that files will be modified without creating backup files");
340 }
341 return errorList;
342 }
343
344 void showDialogBox(List<String> errorList) {
345 StringBuilder buf = new StringBuilder();
346 buf.append("<html>");
347 int i = 1;
348 for (String msg : errorList) {
349 buf.append("<p>");
350 buf.append(i);
351 buf.append(". ");
352 buf.append(msg);
353 buf.append("</p>");
354 i++;
355 }
356 buf.append("</html>");
357
358 JOptionPane.showMessageDialog(this, buf.toString(), "", JOptionPane.ERROR_MESSAGE);
359 }
360
361 boolean isDirectory(String filename) {
362 if (filename == null) {
363 return false;
364 }
365 File file = new File(filename);
366 if (file.exists() && file.isDirectory()) {
367 return true;
368 } else {
369 return false;
370 }
371 }
372 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27
28 public interface ProgressListener {
29
30 public void onMigrationBegin();
31
32 public void onDirectory(File file);
33
34 public void onFileAddition(File file);
35
36 public void onFileScanBegin();
37
38 public void onFileScan(File file);
39
40 public void onInplaceConversion(File file);
41
42 public void onDone();
43
44 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27 import java.io.IOException;
28
29 import org.slf4j.migrator.helper.Abbreviator;
30
31 public class ProgressListenerImpl implements ProgressListener {
32
33 static final int TARGET_FILE_LENGTH = 85;
34 static final int UPDATE_THRESHOLD = 100;
35
36 int addFileCount = 0;
37 int scanFileCount = 0;
38 int inplaceConversionCount = 0;
39 final MigratorFrame frame;
40
41 Abbreviator abbr;
42
43 long lastUpdate = 0;
44
45 public ProgressListenerImpl(File projectFolder, MigratorFrame frame) {
46 this.frame = frame;
47 this.abbr = new Abbreviator((int) projectFolder.length(), TARGET_FILE_LENGTH, File.separatorChar);
48 }
49
50 public void onMigrationBegin() {
51 frame.disableInput();
52 }
53
54 boolean isTooSoon() {
55 long now = System.currentTimeMillis();
56 if (now - lastUpdate < UPDATE_THRESHOLD) {
57 return true;
58 } else {
59 lastUpdate = now;
60 return false;
61 }
62 }
63
64 public void onDirectory(File file) {
65 if (isTooSoon())
66 return;
67
68 String abbreviatedName = getShortName(file);
69 frame.otherLabel.setText("<html><p>Searching folder [" + abbreviatedName + "]<p>Found " + addFileCount + " java files to scan.</html>");
70 }
71
72 public void onDone() {
73 frame.progressBar.setVisible(false);
74 frame.otherLabel.setText("<html><font color='BLUE'>Scanned " + addFileCount + " java files, " + inplaceConversionCount
75 + " files were modified.</font></html>");
76
77 frame.migrateButton.setActionCommand(MigratorFrame.EXIT_COMMAND);
78 frame.migrateButton.setText("Exit");
79 frame.migrateButton.setToolTipText("Click on this button to exit this application.");
80 frame.migrateButton.setEnabled(true);
81
82 }
83
84 public void onFileAddition(File file) {
85 addFileCount++;
86 }
87
88 public void onFileScan(File file) {
89
90 scanFileCount++;
91 if (isTooSoon())
92 return;
93 String abbreviatedName = getShortName(file);
94
95 frame.otherLabel.setText("<html><p>Scanning file [" + abbreviatedName + "]<p></html>");
96 // File + scanFileCount + " out of "+ addFileCount+" files to scan."+
97 // inplaceConversionCount+ " files converted." +
98
99 frame.progressBar.setValue(scanFileCount);
100 }
101
102 public void onInplaceConversion(File file) {
103 inplaceConversionCount++;
104 }
105
106 String getShortName(File file) {
107 try {
108 return abbr.abbreviate(file.getCanonicalPath());
109 } catch (IOException e) {
110 return file.toString();
111 }
112 }
113
114 public void onFileScanBegin() {
115 frame.progressBar.setMaximum(addFileCount);
116 frame.progressBar.setValue(0);
117 frame.progressBar.setVisible(true);
118 }
119
120 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 public interface ConversionRule {
30
31 public Pattern getPattern();
32
33 /**
34 * Given replacement rules, replace each capturing group in matcher's pattern
35 *
36 * @param matcher
37 * @return String
38 */
39 public String replace(Matcher matcher);
40
41 /**
42 * Returns a non-null value if there should be an additional line
43 * following a match of this rule. In most cases this method
44 * returns null.
45 *
46 * @return String
47 */
48 public String getAdditionalLine();
49
50 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.List;
29
30 public class EmptyRuleSet implements RuleSet {
31
32 List<ConversionRule> list = new ArrayList<ConversionRule>();
33
34 public Iterator<ConversionRule> iterator() {
35 return list.iterator();
36 }
37
38 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 /**
31 * This class represents JCL to SLF4J conversion rules
32 *
33 * @author Jean-Noel Charpin
34 *
35 */
36 public class JCLRuleSet implements RuleSet {
37
38 private ArrayList<ConversionRule> conversionRuleList;
39
40 public JCLRuleSet() {
41 // matching : import org.apache.commons.logging.LogFactory;
42 SingleConversionRule cr0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.LogFactory;"),
43 "import org.slf4j.LoggerFactory;");
44
45 // matching : import org.apache.commons.logging.Log;
46 SingleConversionRule cr1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.Log;"), "import org.slf4j.Logger;");
47
48 SingleConversionRule cr2 = new SingleConversionRule(Pattern.compile("(\\sLog\\b)"), " Logger");
49
50 SingleConversionRule cr3 = new SingleConversionRule(Pattern.compile("(^Log\\b)"), "Logger");
51
52 SingleConversionRule cr4 = new SingleConversionRule(Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("), "LoggerFactory.getLogger(");
53
54 SingleConversionRule cr5 = new SingleConversionRule(Pattern.compile("LogFactory.getLog\\("), "LoggerFactory.getLogger(");
55
56 conversionRuleList = new ArrayList<ConversionRule>();
57 conversionRuleList.add(cr0);
58 conversionRuleList.add(cr1);
59 conversionRuleList.add(cr2);
60 conversionRuleList.add(cr3);
61 conversionRuleList.add(cr4);
62 conversionRuleList.add(cr5);
63 }
64
65 public Iterator<ConversionRule> iterator() {
66 return conversionRuleList.iterator();
67 }
68 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 /**
31 * This class represents java.util.logging (JUL) to SLF4J conversion rules
32 *
33 * @author Jean-Noel Charpin
34 * @author Ceki Gulcu
35 */
36 public class JULRuleSet implements RuleSet {
37
38 private ArrayList<ConversionRule> conversionRuleList;
39
40 public JULRuleSet() {
41
42 SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.Logger;"), "import org.slf4j.Logger;",
43 "import org.slf4j.LoggerFactory;");
44
45 SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;");
46
47 SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.*;"), "import org.slf4j.Logger;",
48 "import org.slf4j.LoggerFactory;");
49
50 SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger(");
51
52 SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger(");
53
54 SingleConversionRule crWarning = new SingleConversionRule(Pattern.compile("\\.warning\\("), ".warn(");
55 SingleConversionRule crSevere = new SingleConversionRule(Pattern.compile("\\.severe\\("), ".error(");
56
57 conversionRuleList = new ArrayList<ConversionRule>();
58 conversionRuleList.add(crImport0);
59 conversionRuleList.add(crImport1);
60 conversionRuleList.add(crImport2);
61 conversionRuleList.add(crFactory0);
62 conversionRuleList.add(crFactory1);
63 conversionRuleList.add(crWarning);
64 conversionRuleList.add(crSevere);
65 }
66
67 public Iterator<ConversionRule> iterator() {
68 return conversionRuleList.iterator();
69 }
70
71 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.Arrays;
27 import java.util.Iterator;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30
31 public class LineConverter {
32
33 final RuleSet ruleSet;
34 boolean atLeastOneMatchOccured = false;
35
36 public LineConverter(RuleSet ruleSet) {
37 this.ruleSet = ruleSet;
38 }
39
40 /**
41 * Check if the specified text is matching some conversions rules.
42 * If a rule matches, ask for line replacement.
43 *
44 * <p>In case no rule can be applied, then the input text is
45 * returned without change.
46 *
47 * @param text
48 * @return String
49 */
50 public String[] getReplacement(String text) {
51 ConversionRule conversionRule;
52 Pattern pattern;
53 Matcher matcher;
54 Iterator<ConversionRule> conversionRuleIterator = ruleSet.iterator();
55 String additionalLine = null;
56 while (conversionRuleIterator.hasNext()) {
57 conversionRule = conversionRuleIterator.next();
58 pattern = conversionRule.getPattern();
59 matcher = pattern.matcher(text);
60 if (matcher.find()) {
61 // System.out.println("matching " + text);
62 atLeastOneMatchOccured = true;
63 String replacementText = conversionRule.replace(matcher);
64 text = matcher.replaceAll(replacementText);
65 if (conversionRule.getAdditionalLine() != null) {
66 additionalLine = conversionRule.getAdditionalLine();
67 }
68 }
69 }
70
71 if (additionalLine == null) {
72 return new String[] { text };
73 } else {
74 return new String[] { text, additionalLine };
75 }
76 }
77
78 public String getOneLineReplacement(String text) {
79 String[] r = getReplacement(text);
80 if (r.length != 1) {
81 throw new IllegalStateException("Expecting a single string but got " + Arrays.toString(r));
82 } else {
83 return r[0];
84 }
85 }
86
87 public boolean atLeastOneMatchOccured() {
88 return atLeastOneMatchOccured;
89 }
90 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 public class Log4jRuleSet implements RuleSet {
31
32 private ArrayList<ConversionRule> conversionRuleList;
33
34 public Log4jRuleSet() {
35
36 SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Logger;"), "import org.slf4j.Logger;",
37 "import org.slf4j.LoggerFactory;");
38
39 SingleConversionRule catImport = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Category;"), "import org.slf4j.Logger;",
40 "import org.slf4j.LoggerFactory;");
41
42 SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;");
43
44 SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.*;"), "import org.slf4j.Logger;",
45 "import org.slf4j.LoggerFactory;");
46
47 SingleConversionRule crImportMDC = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.MDC;"), "import org.slf4j.MDC;");
48
49 SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger(");
50
51 SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("\\sCategory.getInstance\\("), " LoggerFactory.getLogger(");
52
53 SingleConversionRule crFactory2 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger(");
54
55 SingleConversionRule variable0 = new SingleConversionRule(Pattern.compile("(\\sCategory\\b)"), " Logger");
56
57 SingleConversionRule variable1 = new SingleConversionRule(Pattern.compile("(^Category\\b)"), "Logger");
58
59 conversionRuleList = new ArrayList<ConversionRule>();
60 conversionRuleList.add(crImport0);
61 conversionRuleList.add(catImport);
62 conversionRuleList.add(crImport1);
63 conversionRuleList.add(crImport2);
64 conversionRuleList.add(crImportMDC);
65 conversionRuleList.add(crFactory0);
66 conversionRuleList.add(crFactory1);
67 conversionRuleList.add(crFactory2);
68
69 conversionRuleList.add(variable0);
70 conversionRuleList.add(variable1);
71 }
72
73 public Iterator<ConversionRule> iterator() {
74 return conversionRuleList.iterator();
75 }
76
77 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 /**
30 * This class represents a conversion rule It uses a Pattern and defines for
31 * each capturing group of this Pattern a replacement text
32 *
33 * @author jean-noelcharpin
34 *
35 */
36 public class MultiGroupConversionRule implements ConversionRule {
37
38 // It is extremely unlikely to encounter more than 10 groups in one of
39 // our conversion reg-expressions
40 final private static int MAX_GROUPS = 10;
41
42 private Pattern pattern;
43 private String[] replacementTable = new String[MAX_GROUPS];
44
45 public MultiGroupConversionRule(Pattern pattern) {
46 this.pattern = pattern;
47 }
48
49 /*
50 * (non-Javadoc)
51 *
52 * @see org.slf4j.converter.ConversionRule#getPattern()
53 */
54 public Pattern getPattern() {
55 return pattern;
56 }
57
58 public void addReplacement(int groupIndex, String replacement) {
59 if (groupIndex == 0) {
60 throw new IllegalArgumentException("regex groups start at 1, not zero");
61 }
62 replacementTable[groupIndex] = replacement;
63 }
64
65 /*
66 * (non-Javadoc)
67 *
68 * @see org.slf4j.converter.ConversionRule#getReplacement(java.lang.Integer)
69 */
70 public String getReplacement(int groupIndex) {
71 return replacementTable[groupIndex];
72 }
73
74 /*
75 * (non-Javadoc)
76 *
77 * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher)
78 */
79 public String replace(Matcher matcher) {
80 StringBuilder replacementBuffer = new StringBuilder();
81 String replacementText;
82
83 for (int group = 1; group <= matcher.groupCount(); group++) {
84 replacementText = getReplacement(group);
85 if (replacementText != null) {
86 // System.out.println("replacing group " + group + " : "
87 // + matcher.group(group) + " with " + replacementText);
88 replacementBuffer.append(replacementText);
89 } else {
90 replacementBuffer.append(matcher.group(group));
91 }
92 }
93 return replacementBuffer.toString();
94 }
95
96 public String getAdditionalLine() {
97 return null;
98 }
99 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.Iterator;
27
28 public interface RuleSet {
29
30 Iterator<ConversionRule> iterator();
31
32 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 /**
30 * This class represents a conversion rule It uses a Pattern and defines for
31 * each capturing group of this Pattern a replacement text
32 *
33 * @author jean-noelcharpin
34 *
35 */
36 public class SingleConversionRule implements ConversionRule {
37
38 final private Pattern pattern;
39 final private String replacementText;
40 final private String additionalLine;
41
42 public SingleConversionRule(Pattern pattern, String replacementText) {
43 this(pattern, replacementText, null);
44 }
45
46 public SingleConversionRule(Pattern pattern, String replacementText, String additionalLine) {
47 this.pattern = pattern;
48 this.replacementText = replacementText;
49 this.additionalLine = additionalLine;
50 }
51
52 /*
53 * (non-Javadoc)
54 *
55 * @see org.slf4j.converter.ConversionRule#getPattern()
56 */
57 public Pattern getPattern() {
58 return pattern;
59 }
60
61 /*
62 * (non-Javadoc)
63 *
64 * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher)
65 */
66 public String replace(Matcher matcher) {
67 return replacementText;
68 }
69
70 public String getAdditionalLine() {
71 return additionalLine;
72 }
73
74 }
0 Main-Class: org.slf4j.migrator.Main
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ org.slf4j.migrator.PackageTest.class, org.slf4j.migrator.line.PackageTest.class, org.slf4j.migrator.helper.PackageTest.class })
32 public class AllTest {
33
34 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 import org.slf4j.migrator.line.MultiGroupConversionRule;
30
31 import junit.framework.TestCase;
32
33 public class AternativeApproach extends TestCase {
34
35 /**
36 * In this test we see that we cans use more simple Pattern to do the
37 * conversion
38 *
39 */
40 public void test() {
41 MultiGroupConversionRule cr2 = new MultiGroupConversionRule(Pattern.compile("(.*)(Log)"));
42 cr2.addReplacement(2, "LOGGER");
43
44 String s = "abcd Log";
45 Pattern pat = cr2.getPattern();
46 Matcher m = pat.matcher(s);
47
48 assertTrue(m.matches());
49 String r = cr2.replace(m);
50 assertEquals("abcd LOGGER", r);
51
52 System.out.println(r);
53 }
54
55 /**
56 * In this test we replace, using the simple Pattern (Log), the full Log
57 * declaration and instanciation. This is not convenient because we will also
58 * replace all String containing "Log".
59 */
60 public void test2() {
61 Pattern pat = Pattern.compile("(Log)");
62 String s = "abcd Log =";
63 Matcher m = pat.matcher(s);
64 assertTrue(m.find());
65 String r = m.replaceAll("Logger");
66 assertEquals("abcd Logger =", r);
67
68 String s1 = "Log l = LogFactory.getLog(MyClass.class);";
69 m = pat.matcher(s1);
70 assertTrue(m.find());
71 r = m.replaceAll("Logger");
72 assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", r);
73
74 String s2 = "Logabc ";
75 m = pat.matcher(s2);
76 assertTrue(m.find());
77
78 String s3 = "abcLog";
79 m = pat.matcher(s3);
80 assertTrue(m.find());
81 }
82
83 /**
84 * In this test we use a simple Pattern to replace the log instanciation
85 * without influence on Log declaration.
86 *
87 */
88 public void test3() {
89 Pattern pat = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\(");
90 String s = "Log log = LogFactory.getFactory().getInstance(\"x\");";
91 Matcher m = pat.matcher(s);
92 assertTrue(m.find());
93 String r = m.replaceAll("LoggerFactory.getLogger(");
94 assertEquals("Log log = LoggerFactory.getLogger(\"x\");", r);
95
96 String nonMatching = "Log log = xxx;";
97 pat.matcher(nonMatching);
98 assertFalse(m.find());
99 }
100
101 /**
102 * In this test we try to replace keyword Log without influence on String
103 * containg Log We see that we have to use two differents Patterns
104 */
105 public void test4() {
106 Pattern pat = Pattern.compile("(\\sLog\\b)");
107 String s = "abcd Log =";
108 Matcher m = pat.matcher(s);
109 assertTrue(m.find());
110 String r = m.replaceAll(" Logger");
111 assertEquals("abcd Logger =", r);
112
113 String s2 = "Logabcd ";
114 m = pat.matcher(s2);
115 assertFalse(m.find());
116
117 String s3 = "abcdLogabcd ";
118 m = pat.matcher(s3);
119 assertFalse(m.find());
120
121 String s4 = "abcdLog";
122 m = pat.matcher(s4);
123 assertFalse(m.find());
124
125 String s5 = "Log myLog";
126 m = pat.matcher(s5);
127 assertFalse(m.find());
128
129 Pattern pat2 = Pattern.compile("^Log\\b");
130 Matcher m2 = pat2.matcher(s5);
131 assertTrue(m2.find());
132 r = m2.replaceAll("Logger");
133 assertEquals("Logger myLog", r);
134 }
135
136 /**
137 * In this test we combine two Pattern to achieve the intended conversion
138 */
139 public void test5() {
140 Pattern pat = Pattern.compile("(\\sLog\\b)");
141 String s = "public Log myLog =LogFactory.getFactory().getInstance(myClass.class);";
142 Matcher m = pat.matcher(s);
143 assertTrue(m.find());
144 String r = m.replaceAll(" Logger");
145 assertEquals("public Logger myLog =LogFactory.getFactory().getInstance(myClass.class);", r);
146
147 Pattern pat2 = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\(");
148 m = pat2.matcher(r);
149 assertTrue(m.find());
150 r = m.replaceAll("LoggerFactory.getLogger(");
151 assertEquals("public Logger myLog =LoggerFactory.getLogger(myClass.class);", r);
152 }
153 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27 import java.io.IOException;
28
29 import junit.framework.TestCase;
30
31 import org.slf4j.migrator.InplaceFileConverter;
32 import org.slf4j.migrator.internal.NopProgressListener;
33 import org.slf4j.migrator.line.EmptyRuleSet;
34
35 public class FileConverterTest extends TestCase {
36
37 public FileConverterTest(String arg0) {
38 super(arg0);
39 }
40
41 protected void setUp() throws Exception {
42 super.setUp();
43 }
44
45 protected void tearDown() throws Exception {
46 super.tearDown();
47 }
48
49 public void test() {
50 }
51
52 public void XtestNOP() throws IOException {
53 InplaceFileConverter fc = new InplaceFileConverter(new EmptyRuleSet(), new NopProgressListener());
54 fc.convert(new File("c:/varargs.txt"));
55 }
56 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ AternativeApproach.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator;
25
26 import java.io.File;
27
28 import org.slf4j.migrator.Constant;
29 import org.slf4j.migrator.ProjectConverter;
30 import org.slf4j.migrator.internal.NopProgressListener;
31
32 import junit.framework.TestCase;
33
34 public class ProjectConverterTest extends TestCase {
35
36 public void test() {
37 }
38
39 public void XtestBarracuda() {
40 ProjectConverter pc = new ProjectConverter(Constant.LOG4J_TO_SLF4J, new NopProgressListener());
41 File projectFolder = new File("c:/home/ceki//Varia/Barracuda");
42 pc.convertProject(projectFolder);
43 }
44 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import org.slf4j.migrator.helper.Abbreviator;
27
28 import junit.framework.TestCase;
29
30 public class AbbreviatorTest extends TestCase {
31
32 static final char FS = '/';
33 static final String INPUT_0 = "/abc/123456/ABC";
34 static final String INPUT_1 = "/abc/123456/xxxxx/ABC";
35
36 RandomHelper rh = new RandomHelper(FS);
37
38 public AbbreviatorTest(String arg0) {
39 super(arg0);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 }
45
46 protected void tearDown() throws Exception {
47 super.tearDown();
48 }
49
50 public void testSmoke() {
51 {
52 Abbreviator abb = new Abbreviator(2, 100, FS);
53 String r = abb.abbreviate(INPUT_0);
54 assertEquals(INPUT_0, r);
55 }
56
57 {
58 Abbreviator abb = new Abbreviator(3, 8, FS);
59 String r = abb.abbreviate(INPUT_0);
60 assertEquals("/abc/.../ABC", r);
61 }
62 {
63 Abbreviator abb = new Abbreviator(3, 8, FS);
64 String r = abb.abbreviate(INPUT_0);
65 assertEquals("/abc/.../ABC", r);
66 }
67 }
68
69 public void testImpossibleToAbbreviate() {
70 Abbreviator abb = new Abbreviator(2, 20, FS);
71 String in = "iczldqwivpgm/mgrmvbjdxrwmqgprdjusth";
72 String r = abb.abbreviate(in);
73 assertEquals(in, r);
74 }
75
76 public void testNoFS() {
77 Abbreviator abb = new Abbreviator(2, 100, FS);
78 String r = abb.abbreviate("hello");
79 assertEquals("hello", r);
80
81 }
82
83 public void testZeroPrefix() {
84 {
85 Abbreviator abb = new Abbreviator(0, 100, FS);
86 String r = abb.abbreviate(INPUT_0);
87 assertEquals(INPUT_0, r);
88 }
89 }
90
91 public void testTheories() {
92 int MAX_RANDOM_FIXED_LEN = 20;
93 int MAX_RANDOM_AVG_LEN = 20;
94 int MAX_RANDOM_MAX_LEN = 100;
95 for (int i = 0; i < 10000; i++) {
96
97 // System.out.println("Test number " + i);
98
99 // 0 <= fixedLen < MAX_RANDOM_FIXED_LEN
100 int fixedLen = rh.nextInt(MAX_RANDOM_FIXED_LEN);
101 // 5 <= averageLen < MAX_RANDOM_AVG_LEN
102 int averageLen = rh.nextInt(MAX_RANDOM_AVG_LEN) + 3;
103 // System.out.println("fixedLen="+fixedLen+", averageLen="+averageLen);
104
105 int maxLen = rh.nextInt(MAX_RANDOM_MAX_LEN) + fixedLen;
106 if (maxLen <= 1) {
107 continue;
108 }
109 // System.out.println("maxLen="+maxLen);
110 int targetLen = (maxLen / 2) + rh.nextInt(maxLen / 2) + 1;
111
112 if (targetLen > maxLen) {
113 targetLen = maxLen;
114 }
115 String filename = rh.buildRandomFileName(averageLen, maxLen);
116
117 Abbreviator abb = new Abbreviator(fixedLen, targetLen, FS);
118 String result = abb.abbreviate(filename);
119 assertTheory0(averageLen, filename, result, fixedLen, targetLen);
120 assertUsefulness(averageLen, filename, result, fixedLen, targetLen);
121 assertTheory1(filename, result, fixedLen, targetLen);
122 assertTheory2(filename, result, fixedLen, targetLen);
123 }
124 }
125
126 // result length is smaller than original length
127 void assertTheory0(int averageLen, String filename, String result, int fixedLen, int targetLength) {
128 assertTrue("filename=[" + filename + "] result=[" + result + "]", result.length() <= filename.length());
129 }
130
131 // if conditions allow, result length should be to target length
132 void assertUsefulness(int averageLen, String filename, String result, int fixedLen, int targetLength) {
133 int resLen = result.length();
134
135 int margin = averageLen * 4;
136 if (targetLength > fixedLen + margin) {
137 assertTrue("filename=[" + filename + "], result=[" + result + "] resultLength=" + resLen + " fixedLength=" + fixedLen + ", targetLength="
138 + targetLength + ", avgLen=" + averageLen, result.length() <= targetLength + averageLen);
139 }
140 }
141
142 // result start with prefix found in filename
143 void assertTheory1(String filename, String result, int fixedLen, int targetLength) {
144 String prefix = filename.substring(0, fixedLen);
145 assertTrue(result.startsWith(prefix));
146 }
147
148 // The string /.../ is found in the result once at a position higher
149 // than fixedLen
150 void assertTheory2(String filename, String result, int fixedLen, int targetLength) {
151 if (filename == result) {
152 return;
153 }
154 int fillerIndex = result.indexOf(Abbreviator.FILLER);
155 assertTrue(fillerIndex >= fixedLen);
156 }
157 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ AbbreviatorTest.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.helper;
25
26 import java.util.Random;
27
28 public class RandomHelper {
29
30 private Random random = new Random(100);
31 final char folderSeparator;
32
33 RandomHelper(char folderSeparator) {
34 this.folderSeparator = folderSeparator;
35 }
36
37 private String randomString(int len) {
38 StringBuilder buf = new StringBuilder();
39 for (int i = 0; i < len; i++) {
40 int offset = random.nextInt(26);
41 char c = (char) ('a' + offset);
42 buf.append(c);
43 }
44 return buf.toString();
45 }
46
47 int nextInt(int n) {
48 return random.nextInt(n);
49 }
50
51 String buildRandomFileName(int averageNodeLength, int totalLength) {
52 StringBuilder buf = new StringBuilder();
53 int MAX_NODE_LENGTH = averageNodeLength * 2;
54 while (buf.length() < totalLength) {
55 int remaining = totalLength - buf.length();
56 int currentNodeLength;
57 if (remaining > MAX_NODE_LENGTH) {
58 currentNodeLength = random.nextInt(MAX_NODE_LENGTH) + 1;
59 buf.append(randomString(currentNodeLength));
60 buf.append('/');
61 } else {
62 currentNodeLength = remaining;
63 buf.append(randomString(currentNodeLength));
64 }
65 }
66 return buf.toString();
67 }
68
69 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.internal;
25
26 import java.io.File;
27
28 import org.slf4j.migrator.internal.ProgressListener;
29
30 public class NopProgressListener implements ProgressListener {
31
32 public void onDirectory(File file) {
33 }
34
35 public void onDone() {
36 }
37
38 public void onFileAddition(File file) {
39 }
40
41 public void onFileScan(File file) {
42 }
43
44 public void onInplaceConversion(File file) {
45 }
46
47 public void onFileScanBegin() {
48 }
49
50 public void onMigrationBegin() {
51 }
52
53 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import org.slf4j.migrator.line.JCLRuleSet;
27 import org.slf4j.migrator.line.LineConverter;
28
29 import junit.framework.TestCase;
30
31 public class JCLRuleSetTest extends TestCase {
32
33 LineConverter jclConverter = new LineConverter(new JCLRuleSet());
34
35 public void testImportReplacement() {
36 // LogFactory import replacement
37 assertEquals("import org.slf4j.LoggerFactory;", jclConverter.getOneLineReplacement("import org.apache.commons.logging.LogFactory;"));
38 // Log import replacement
39 assertEquals("import org.slf4j.Logger;", jclConverter.getOneLineReplacement("import org.apache.commons.logging.Log;"));
40 }
41
42 public void testLogFactoryGetLogReplacement() {
43 // Logger declaration and instanciation without modifier
44 assertEquals(" Logger l = LoggerFactory.getLogger(MyClass.class);",
45 jclConverter.getOneLineReplacement(" Log l = LogFactory.getLog(MyClass.class);"));
46 // Logger declaration and instanciation with one modifier
47 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
48 jclConverter.getOneLineReplacement("public Log mylog=LogFactory.getLog(MyClass.class);"));
49 // Logger declaration and instanciation with two modifier
50 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
51 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class);"));
52 // Logger declaration and instanciation with two modifier and comment at the
53 // end of line
54 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); //logger instanciation and declaration",
55 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class); //logger instanciation and declaration"));
56 // Logger instanciation without declaration and comment at the end of line
57 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
58 jclConverter.getOneLineReplacement(" myLog = LogFactory.getLog(MyClass.class);//logger instanciation"));
59 // commented Logger declaration and instanciation with two modifier
60 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
61 jclConverter.getOneLineReplacement("//public static Log mylog1 = LogFactory.getLog(MyClass.class);"));
62 // commented Logger instanciation without declaration
63 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
64 jclConverter.getOneLineReplacement("// myLog = LogFactory.getLog(MyClass.class);//logger instanciation"));
65 }
66
67 public void testLogFactoryGetFactoryReplacement() {
68
69 // Logger declaration and instanciation without modifier
70 assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);",
71 jclConverter.getOneLineReplacement("Log l = LogFactory.getFactory().getInstance(MyClass.class);"));
72 // Logger declaration and instanciation with one modifier
73 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
74 jclConverter.getOneLineReplacement("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);"));
75 // Logger declaration and instanciation with modifiers
76 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
77 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class);"));
78 // Logger declaration and instanciation with two modifier and comment at the
79 // end of line
80 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); //logger instanciation and declaration",
81 jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class); //logger instanciation and declaration"));
82 // Logger instanciation without declaration and comment at the end of line
83 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
84 jclConverter.getOneLineReplacement(" myLog = LogFactory.getFactory().getInstance(MyClass.class);//logger instanciation"));
85 // commented Logger declaration and instanciation with two modifier
86 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
87 jclConverter.getOneLineReplacement("//public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class);"));
88 // commented Logger instanciation without declaration
89 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
90 jclConverter.getOneLineReplacement("// myLog = LogFactory.getFactory().getInstance(MyClass.class);//logger instanciation"));
91 }
92
93 public void testLogDeclarationReplacement() {
94
95 // simple Logger declaration
96 assertEquals("Logger mylog;", jclConverter.getOneLineReplacement("Log mylog;"));
97 // Logger declaration with a modifier
98 assertEquals("private Logger mylog;", jclConverter.getOneLineReplacement("private Log mylog;"));
99
100 // Logger declaration with modifiers
101 assertEquals("public static final Logger myLog;", jclConverter.getOneLineReplacement("public static final Log myLog;"));
102 // Logger declaration with modifiers and comment at the end of line
103 assertEquals("public Logger myLog;//logger declaration", jclConverter.getOneLineReplacement("public Log myLog;//logger declaration"));
104 // commented Logger declaration
105 assertEquals("//private Logger myLog;", jclConverter.getOneLineReplacement("//private Log myLog;"));
106 }
107
108 public void testMultiLineReplacement() {
109 // Logger declaration on a line
110 assertEquals("protected Logger log =", jclConverter.getOneLineReplacement("protected Log log ="));
111
112 // Logger instanciation on the next line
113 assertEquals(" LoggerFactory.getLogger(MyComponent.class);", jclConverter.getOneLineReplacement(" LogFactory.getLog(MyComponent.class);"));
114 // Logger declaration on a line
115 assertEquals("protected Logger log ", jclConverter.getOneLineReplacement("protected Log log "));
116 // Logger instanciation on the next line
117 assertEquals(" = LoggerFactory.getLogger(MyComponent.class);",
118 jclConverter.getOneLineReplacement(" = LogFactory.getFactory().getInstance(MyComponent.class);"));
119 }
120 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.Arrays;
27
28 import org.junit.Test;
29 import org.slf4j.migrator.line.LineConverter;
30 import org.slf4j.migrator.line.Log4jRuleSet;
31
32 import static org.junit.Assert.assertEquals;
33 import static org.junit.Assert.assertTrue;
34
35 public class Log4jRuleSetTest {
36
37 LineConverter log4jConverter = new LineConverter(new Log4jRuleSet());
38
39 @Test
40 public void testImportReplacement() {
41 // LogFactory import replacement
42 assertEquals("import org.slf4j.LoggerFactory;", log4jConverter.getOneLineReplacement("import org.apache.log4j.LogManager;"));
43 // Log import replacement
44 assertTrue(Arrays.equals(new String[] { "import org.slf4j.Logger;", "import org.slf4j.LoggerFactory;" },
45 log4jConverter.getReplacement("import org.apache.log4j.Logger;")));
46 }
47
48 @Test
49 public void testLogManagerGetLoggerReplacement() {
50 // Logger declaration and instanciation without modifier
51 assertEquals(" Logger l = LoggerFactory.getLogger(MyClass.class);",
52 log4jConverter.getOneLineReplacement(" Logger l = LogManager.getLogger(MyClass.class);"));
53 // Logger declaration and instanciation with one modifier
54 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
55 log4jConverter.getOneLineReplacement("public Logger mylog=LogManager.getLogger(MyClass.class);"));
56 // Logger declaration and instanciation with two modifier
57 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
58 log4jConverter.getOneLineReplacement("public static Logger mylog1 = LogManager.getLogger(MyClass.class);"));
59 // Logger declaration and instanciation with two modifier and comment at the
60 // end of line
61 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);//logger instanciation and declaration",
62 log4jConverter.getOneLineReplacement("public static Logger mylog1 = LogManager.getLogger(MyClass.class);//logger instanciation and declaration"));
63 // Logger instanciation without declaration and comment at the end of line
64 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
65 log4jConverter.getOneLineReplacement(" myLog = LogManager.getLogger(MyClass.class);//logger instanciation"));
66 // commented Logger declaration and instanciation with two modifier
67 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
68 log4jConverter.getOneLineReplacement("//public static Logger mylog1 = LogManager.getLogger(MyClass.class);"));
69 // commented Logger instanciation without declaration
70 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
71 log4jConverter.getOneLineReplacement("// myLog = LogManager.getLogger(MyClass.class);//logger instanciation"));
72 }
73
74 @Test
75 public void testLoggerGetLoggerReplacement() {
76 // Logger declaration and instanciation without modifier
77 assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", log4jConverter.getOneLineReplacement("Logger l = Logger.getLogger(MyClass.class);"));
78 // Logger declaration and instanciation with one modifier
79 assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);",
80 log4jConverter.getOneLineReplacement("public Logger mylog=Logger.getLogger(MyClass.class);"));
81 // Logger declaration and instanciation with modifiers
82 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
83 log4jConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class);"));
84 // Logger declaration and instanciation with two modifier and comment at the
85 // end of line
86 assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); // logger instanciation and declaration",
87 log4jConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class); // logger instanciation and declaration"));
88 // Logger instanciation without declaration and comment at the end of line
89 assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
90 log4jConverter.getOneLineReplacement(" myLog = Logger.getLogger(MyClass.class);//logger instanciation"));
91 // commented Logger declaration and instanciation with two modifier
92 assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);",
93 log4jConverter.getOneLineReplacement("//public static Logger mylog1 = Logger.getLogger(MyClass.class);"));
94 // commented Logger instanciation without declaration
95 assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation",
96 log4jConverter.getOneLineReplacement("// myLog = Logger.getLogger(MyClass.class);//logger instanciation"));
97 }
98
99 @Test
100 public void testLogDeclarationReplacement() {
101 // simple Logger declaration
102 assertEquals("Logger mylog;", log4jConverter.getOneLineReplacement("Logger mylog;"));
103 // Logger declaration with a modifier
104 assertEquals("private Logger mylog;", log4jConverter.getOneLineReplacement("private Logger mylog;"));
105
106 // Logger declaration with modifiers
107 assertEquals("public static final Logger myLog;", log4jConverter.getOneLineReplacement("public static final Logger myLog;"));
108 // Logger declaration with modifiers and comment at the end of line
109 assertEquals("public Logger myLog;//logger declaration", log4jConverter.getOneLineReplacement("public Logger myLog;//logger declaration"));
110 // commented Logger declaration
111 assertEquals("//private Logger myLog;", log4jConverter.getOneLineReplacement("//private Logger myLog;"));
112 }
113
114 @Test
115 public void testMultiLineReplacement() {
116 // Logger declaration on a line
117 assertEquals("protected Logger log =", log4jConverter.getOneLineReplacement("protected Logger log ="));
118
119 // Logger instanciation on the next line
120 assertEquals(" LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" LogManager.getLogger(MyComponent.class);"));
121 // Logger declaration on a line
122 assertEquals("protected Logger log ", log4jConverter.getOneLineReplacement("protected Logger log "));
123 // Logger instanciation on the next line
124 assertEquals(" = LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" = LogManager.getLogger(MyComponent.class);"));
125 }
126
127 @Test
128 public void categoryReplacement() {
129 // Category declaration on a line
130 assertEquals("protected Logger cat =", log4jConverter.getOneLineReplacement("protected Category cat ="));
131
132 assertEquals(" LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" Category.getInstance(MyComponent.class);"));
133 }
134
135 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import org.slf4j.migrator.line.JCLRuleSet;
27 import org.slf4j.migrator.line.LineConverter;
28 import org.slf4j.migrator.line.Log4jRuleSet;
29
30 import junit.framework.TestCase;
31
32 public class NoConversionTest extends TestCase {
33
34 /**
35 * This test shows that performing JCL to SLF4J conversion has no impact on
36 * Log4j implementation
37 */
38 public void testJclOverLog4jConversion() {
39 // running jcl to slf4j conversion
40 // JCLMatcher jclMatcher =
41 LineConverter jclLineConverter = new LineConverter(new JCLRuleSet());
42 // no changes on log4j.LogManager import
43 assertEquals("import org.apache.log4j.LogManager;", jclLineConverter.getOneLineReplacement("import org.apache.log4j.LogManager;"));
44 // no changes on log4j.Logger import
45 assertEquals("import org.apache.log4j.Logger;", jclLineConverter.getOneLineReplacement("import org.apache.log4j.Logger;"));
46 // no changes on Logger instanciation using LogManager
47 assertEquals("Logger log = LogManager.getLogger(MyClass.class);",
48 jclLineConverter.getOneLineReplacement("Logger log = LogManager.getLogger(MyClass.class);"));
49 // no changes on Logger instanciation using Logger.getLogger
50 assertEquals("public static Logger mylog1 = Logger.getLogger(MyClass.class);",
51 jclLineConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class);"));
52 }
53
54 /**
55 * This test shows that performing Log4j to SLF4J conversion has no impact on
56 * JCL implementation
57 */
58 public void testLog4jOverJclConversion() {
59 // running log4j to slf4j conversion
60 LineConverter log4jConverter = new LineConverter(new Log4jRuleSet());
61
62 // no changes on LogFactory import
63 assertEquals("import org.apache.commons.logging.LogFactory;", log4jConverter.getOneLineReplacement("import org.apache.commons.logging.LogFactory;"));
64 // no changes on Log import
65 assertEquals("import org.apache.commons.logging.Log;", log4jConverter.getOneLineReplacement("import org.apache.commons.logging.Log;"));
66 // no changes on Log instanciation using Logfactory.getLog
67 assertEquals("public static Log mylog1 = LogFactory.getLog(MyClass.class);",
68 log4jConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class);"));
69 // no changes on log instanciation using LogFactory.getFactory().getInstance
70 assertEquals("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);",
71 log4jConverter.getOneLineReplacement("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);"));
72
73 }
74 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import org.junit.runner.RunWith;
27 import org.junit.runners.Suite;
28 import org.junit.runners.Suite.SuiteClasses;
29
30 @RunWith(Suite.class)
31 @SuiteClasses({ TrivialMatcherTest.class, JCLRuleSetTest.class, Log4jRuleSetTest.class, NoConversionTest.class })
32 public class PackageTest {
33 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import java.util.ArrayList;
27 import java.util.Iterator;
28 import java.util.regex.Pattern;
29
30 import org.slf4j.migrator.line.ConversionRule;
31 import org.slf4j.migrator.line.MultiGroupConversionRule;
32 import org.slf4j.migrator.line.RuleSet;
33 import org.slf4j.migrator.line.SingleConversionRule;
34
35 class TrivialMatcher implements RuleSet {
36
37 private ArrayList<ConversionRule> conversionRuleList;
38
39 public TrivialMatcher() {
40 // simple rule no capturing group is defined, we use default capturing group which is group zero
41 SingleConversionRule cr = new SingleConversionRule(Pattern.compile("import org.slf4j.converter"), "simple replacement with an unique capturing group");
42
43 // we define 4 differents capturing groups
44 MultiGroupConversionRule cr1 = new MultiGroupConversionRule(Pattern.compile("(first group)( second group)( third group)( 4th group)"));
45 // group zero is ignored during treatment
46 // replacement for the first
47 cr1.addReplacement(1, "1st group");
48 // no replacement for the second group it will remains the same
49 // empty string for the third group it will be deleted
50 cr1.addReplacement(3, "");
51 // no replacement for the third group it will remains the same
52
53 conversionRuleList = new ArrayList<ConversionRule>();
54 conversionRuleList.add(cr);
55 conversionRuleList.add(cr1);
56 }
57
58 public Iterator<ConversionRule> iterator() {
59 return conversionRuleList.iterator();
60 }
61
62 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.migrator.line;
25
26 import org.slf4j.migrator.line.LineConverter;
27
28 import junit.framework.TestCase;
29
30 public class TrivialMatcherTest extends TestCase {
31
32 public void testSimpleReplacement() {
33 LineConverter trivialLC = new LineConverter(new TrivialMatcher());
34
35 // "import org.slf4j.converter" -- > simple replacement with an unique
36 // capturing group
37 assertEquals("simple replacement with an unique capturing group", trivialLC.getOneLineReplacement("import org.slf4j.converter"));
38
39 assertEquals("1st group second group 4th group", trivialLC.getOneLineReplacement("first group second group third group 4th group"));
40
41 }
42
43 }
0 <project
1 xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4
5 <modelVersion>4.0.0</modelVersion>
6
7 <parent>
8 <groupId>org.slf4j</groupId>
9 <artifactId>slf4j-parent</artifactId>
10 <version>1.7.12</version>
11 </parent>
12
13 <artifactId>slf4j-nop</artifactId>
14
15 <packaging>jar</packaging>
16 <name>SLF4J NOP Binding</name>
17 <description>SLF4J NOP Binding</description>
18 <url>http://www.slf4j.org</url>
19
20
21 <dependencies>
22 <dependency>
23 <groupId>org.slf4j</groupId>
24 <artifactId>slf4j-api</artifactId>
25 </dependency>
26 </dependencies>
27
28 <build>
29 <plugins>
30
31 <plugin>
32 <groupId>org.apache.maven.plugins</groupId>
33 <artifactId>maven-jar-plugin</artifactId>
34 <configuration>
35 <archive>
36 <manifestEntries>
37 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
38 <Bundle-Description>${project.description}</Bundle-Description>
39 <Implementation-Version>${project.version}</Implementation-Version>
40 </manifestEntries>
41 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
42 </archive>
43 </configuration>
44 </plugin>
45 </plugins>
46
47 </build>
48
49 </project>
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.helpers.NOPLoggerFactory;
29 import org.slf4j.spi.LoggerFactoryBinder;
30
31 /**
32 * The binding of {@link LoggerFactory} class with an actual instance of
33 * {@link ILoggerFactory} is performed using information returned by this class.
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public class StaticLoggerBinder implements LoggerFactoryBinder {
38
39 /**
40 * The unique instance of this class.
41 *
42 */
43 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticLoggerBinder singleton
49 */
50 public static final StaticLoggerBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Declare the version of the SLF4J API this implementation is compiled against.
56 * The value of this field is usually modified with each release.
57 */
58 // to avoid constant folding by the compiler, this field must *not* be final
59 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
60
61 private static final String loggerFactoryClassStr = NOPLoggerFactory.class.getName();
62
63 /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method
64 * should always be the same object
65 */
66 private final ILoggerFactory loggerFactory;
67
68 private StaticLoggerBinder() {
69 loggerFactory = new NOPLoggerFactory();
70 }
71
72 public ILoggerFactory getLoggerFactory() {
73 return loggerFactory;
74 }
75
76 public String getLoggerFactoryClassStr() {
77 return loggerFactoryClassStr;
78 }
79 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Currently this method always returns an instance of
46 * {@link StaticMDCBinder}.
47 */
48 public MDCAdapter getMDCA() {
49 return new NOPMDCAdapter();
50 }
51
52 public String getMDCAdapterClassStr() {
53 return NOPMDCAdapter.class.getName();
54 }
55 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.IMarkerFactory;
27 import org.slf4j.MarkerFactory;
28 import org.slf4j.helpers.BasicMarkerFactory;
29 import org.slf4j.spi.MarkerFactoryBinder;
30
31 /**
32 *
33 * The binding of {@link MarkerFactory} class with an actual instance of
34 * {@link IMarkerFactory} is performed using information returned by this class.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class StaticMarkerBinder implements MarkerFactoryBinder {
39
40 /**
41 * The unique instance of this class.
42 */
43 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
44
45 final IMarkerFactory markerFactory = new BasicMarkerFactory();
46
47 private StaticMarkerBinder() {
48 }
49
50 /**
51 * Currently this method always returns an instance of
52 * {@link BasicMarkerFactory}.
53 */
54 public IMarkerFactory getMarkerFactory() {
55 return markerFactory;
56 }
57
58 /**
59 * Currently, this method returns the class name of
60 * {@link BasicMarkerFactory}.
61 */
62 public String getMarkerFactoryClassStr() {
63 return BasicMarkerFactory.class.getName();
64 }
65
66 }
0 Implementation-Title: slf4j-nop
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.nop
3 Bundle-Name: slf4j-nop
4 Bundle-Vendor: SLF4J.ORG
5 Bundle-RequiredExecutionEnvironment: J2SE-1.5
6 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
7 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}
8 Fragment-Host: slf4j.api
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.Closeable;
27 import java.io.IOException;
28 import junit.framework.TestCase;
29
30 /**
31 * Test whether invoking the SLF4J API causes problems or not.
32 *
33 * @author Ceki Gulcu
34 *
35 */
36 public class InvocationTest extends TestCase {
37
38 public InvocationTest(String arg0) {
39 super(arg0);
40 }
41
42 protected void setUp() throws Exception {
43 super.setUp();
44 }
45
46 protected void tearDown() throws Exception {
47 super.tearDown();
48 }
49
50 public void test1() {
51 Logger logger = LoggerFactory.getLogger("test1");
52 logger.debug("Hello world.");
53 }
54
55 public void test2() {
56 Integer i1 = new Integer(1);
57 Integer i2 = new Integer(2);
58 Integer i3 = new Integer(3);
59 Exception e = new Exception("This is a test exception.");
60 Logger logger = LoggerFactory.getLogger("test2");
61
62 logger.debug("Hello world 1.");
63 logger.debug("Hello world {}", i1);
64 logger.debug("val={} val={}", i1, i2);
65 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
66
67 logger.debug("Hello world 2", e);
68 logger.info("Hello world 2.");
69
70 logger.warn("Hello world 3.");
71 logger.warn("Hello world 3", e);
72
73 logger.error("Hello world 4.");
74 logger.error("Hello world {}", new Integer(3));
75 logger.error("Hello world 4.", e);
76 }
77
78 public void testNull() {
79 Logger logger = LoggerFactory.getLogger("testNull");
80 logger.debug(null);
81 logger.info(null);
82 logger.warn(null);
83 logger.error(null);
84
85 Exception e = new Exception("This is a test exception.");
86 logger.debug(null, e);
87 logger.info(null, e);
88 logger.warn(null, e);
89 logger.error(null, e);
90 }
91
92 public void testMarker() {
93 Logger logger = LoggerFactory.getLogger("testMarker");
94 Marker blue = MarkerFactory.getMarker("BLUE");
95 logger.debug(blue, "hello");
96 logger.info(blue, "hello");
97 logger.warn(blue, "hello");
98 logger.error(blue, "hello");
99
100 logger.debug(blue, "hello {}", "world");
101 logger.info(blue, "hello {}", "world");
102 logger.warn(blue, "hello {}", "world");
103 logger.error(blue, "hello {}", "world");
104
105 logger.debug(blue, "hello {} and {} ", "world", "universe");
106 logger.info(blue, "hello {} and {} ", "world", "universe");
107 logger.warn(blue, "hello {} and {} ", "world", "universe");
108 logger.error(blue, "hello {} and {} ", "world", "universe");
109 }
110
111 public void testMDC() {
112 MDC.put("k", "v");
113 assertNull(MDC.get("k"));
114 MDC.remove("k");
115 assertNull(MDC.get("k"));
116 MDC.clear();
117 }
118
119 public void testMDCCloseable() {
120 MDC.MDCCloseable closeable = MDC.putCloseable("k", "v");
121 assertNull(MDC.get("k"));
122 closeable.close();
123 assertNull(MDC.get("k"));
124 MDC.clear();
125 }
126 }
0 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
1 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2
3 <modelVersion>4.0.0</modelVersion>
4
5 <parent>
6 <groupId>org.slf4j</groupId>
7 <artifactId>slf4j-parent</artifactId>
8 <version>1.7.12</version>
9 </parent>
10
11 <artifactId>slf4j-simple</artifactId>
12 <packaging>jar</packaging>
13 <name>SLF4J Simple Binding</name>
14 <description>SLF4J Simple binding</description>
15 <url>http://www.slf4j.org</url>
16
17 <dependencies>
18 <dependency>
19 <groupId>org.slf4j</groupId>
20 <artifactId>slf4j-api</artifactId>
21 </dependency>
22 </dependencies>
23
24
25 <build>
26 <plugins>
27 <plugin>
28 <groupId>org.apache.maven.plugins</groupId>
29 <artifactId>maven-jar-plugin</artifactId>
30 <configuration>
31 <archive>
32 <manifestEntries>
33 <Bundle-Version>${parsedVersion.osgiVersion}</Bundle-Version>
34 <Bundle-Description>${project.description}</Bundle-Description>
35 <Implementation-Version>${project.version}</Implementation-Version>
36 </manifestEntries>
37 <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
38 </archive>
39 </configuration>
40 </plugin>
41
42 </plugins>
43 </build>
44
45
46 </project>
0 /**
1 * Copyright (c) 2004-2012 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.io.FileNotFoundException;
27 import java.io.FileOutputStream;
28 import java.io.InputStream;
29 import java.io.PrintStream;
30 import java.security.AccessController;
31 import java.security.PrivilegedAction;
32 import java.text.DateFormat;
33 import java.text.SimpleDateFormat;
34 import java.util.Date;
35 import java.util.Properties;
36
37 import org.slf4j.Logger;
38 import org.slf4j.helpers.FormattingTuple;
39 import org.slf4j.helpers.MarkerIgnoringBase;
40 import org.slf4j.helpers.MessageFormatter;
41 import org.slf4j.helpers.Util;
42 import org.slf4j.spi.LocationAwareLogger;
43
44 /**
45 * <p>Simple implementation of {@link Logger} that sends all enabled log messages,
46 * for all defined loggers, to the console ({@code System.err}).
47 * The following system properties are supported to configure the behavior of this logger:</p>
48 *
49 * <ul>
50 * <li><code>org.slf4j.simpleLogger.logFile</code> - The output target which can be the <em>path</em> to a file, or
51 * the special values "System.out" and "System.err". Default is "System.err".
52 *
53 * <li><code>org.slf4j.simpleLogger.defaultLogLevel</code> - Default log level for all instances of SimpleLogger.
54 * Must be one of ("trace", "debug", "info", "warn", or "error"). If not specified, defaults to "info". </li>
55 *
56 * <li><code>org.slf4j.simpleLogger.log.<em>a.b.c</em></code> - Logging detail level for a SimpleLogger instance
57 * named "a.b.c". Right-side value must be one of "trace", "debug", "info", "warn", or "error". When a SimpleLogger
58 * named "a.b.c" is initialized, its level is assigned from this property. If unspecified, the level of nearest parent
59 * logger will be used, and if none is set, then the value specified by
60 * <code>org.slf4j.simpleLogger.defaultLogLevel</code> will be used.</li>
61 *
62 * <li><code>org.slf4j.simpleLogger.showDateTime</code> - Set to <code>true</code> if you want the current date and
63 * time to be included in output messages. Default is <code>false</code></li>
64 *
65 * <li><code>org.slf4j.simpleLogger.dateTimeFormat</code> - The date and time format to be used in the output messages.
66 * The pattern describing the date and time format is defined by
67 * <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html"><code>SimpleDateFormat</code></a>.
68 * If the format is not specified or is invalid, the number of milliseconds since start up will be output. </li>
69 *
70 * <li><code>org.slf4j.simpleLogger.showThreadName</code> -Set to <code>true</code> if you want to output the current
71 * thread name. Defaults to <code>true</code>.</li>
72 *
73 * <li><code>org.slf4j.simpleLogger.showLogName</code> - Set to <code>true</code> if you want the Logger instance name
74 * to be included in output messages. Defaults to <code>true</code>.</li>
75 *
76 * <li><code>org.slf4j.simpleLogger.showShortLogName</code> - Set to <code>true</code> if you want the last component
77 * of the name to be included in output messages. Defaults to <code>false</code>.</li>
78 *
79 * <li><code>org.slf4j.simpleLogger.levelInBrackets</code> - Should the level string be output in brackets? Defaults
80 * to <code>false</code>.</li>
81 *
82 * <li><code>org.slf4j.simpleLogger.warnLevelString</code> - The string value output for the warn level. Defaults
83 * to <code>WARN</code>.</li>
84
85 * </ul>
86 *
87 * <p>In addition to looking for system properties with the names specified above, this implementation also checks for
88 * a class loader resource named <code>"simplelogger.properties"</code>, and includes any matching definitions
89 * from this resource (if it exists).</p>
90 *
91 * <p>With no configuration, the default output includes the relative time in milliseconds, thread name, the level,
92 * logger name, and the message followed by the line separator for the host. In log4j terms it amounts to the "%r [%t]
93 * %level %logger - %m%n" pattern. </p>
94 * <p>Sample output follows.</p>
95 * <pre>
96 * 176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
97 * 225 [main] INFO examples.SortAlgo - Entered the sort method.
98 * 304 [main] INFO examples.SortAlgo - Dump of integer array:
99 * 317 [main] INFO examples.SortAlgo - Element [0] = 0
100 * 331 [main] INFO examples.SortAlgo - Element [1] = 1
101 * 343 [main] INFO examples.Sort - The next log statement should be an error message.
102 * 346 [main] ERROR examples.SortAlgo - Tried to dump an uninitialized array.
103 * at org.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
104 * at org.log4j.examples.Sort.main(Sort.java:64)
105 * 467 [main] INFO examples.Sort - Exiting main method.
106 * </pre>
107 *
108 * <p>This implementation is heavily inspired by
109 * <a href="http://commons.apache.org/logging/">Apache Commons Logging</a>'s SimpleLog.</p>
110 *
111 * @author Ceki G&uuml;lc&uuml;
112 * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
113 * @author Rod Waldhoff
114 * @author Robert Burrell Donkin
115 * @author C&eacute;drik LIME
116 */
117 public class SimpleLogger extends MarkerIgnoringBase {
118
119 private static final long serialVersionUID = -632788891211436180L;
120 private static final String CONFIGURATION_FILE = "simplelogger.properties";
121
122 private static long START_TIME = System.currentTimeMillis();
123 private static final Properties SIMPLE_LOGGER_PROPS = new Properties();
124
125 private static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT;
126 private static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT;
127 private static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT;
128 private static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT;
129 private static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT;
130
131 private static boolean INITIALIZED = false;
132
133 private static int DEFAULT_LOG_LEVEL = LOG_LEVEL_INFO;
134 private static boolean SHOW_DATE_TIME = false;
135 private static String DATE_TIME_FORMAT_STR = null;
136 private static DateFormat DATE_FORMATTER = null;
137 private static boolean SHOW_THREAD_NAME = true;
138 private static boolean SHOW_LOG_NAME = true;
139 private static boolean SHOW_SHORT_LOG_NAME = false;
140 private static String LOG_FILE = "System.err";
141 private static PrintStream TARGET_STREAM = null;
142 private static boolean LEVEL_IN_BRACKETS = false;
143 private static String WARN_LEVEL_STRING = "WARN";
144
145 /** All system properties used by <code>SimpleLogger</code> start with this prefix */
146 public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger.";
147
148 public static final String DEFAULT_LOG_LEVEL_KEY = SYSTEM_PREFIX + "defaultLogLevel";
149 public static final String SHOW_DATE_TIME_KEY = SYSTEM_PREFIX + "showDateTime";
150 public static final String DATE_TIME_FORMAT_KEY = SYSTEM_PREFIX + "dateTimeFormat";
151 public static final String SHOW_THREAD_NAME_KEY = SYSTEM_PREFIX + "showThreadName";
152 public static final String SHOW_LOG_NAME_KEY = SYSTEM_PREFIX + "showLogName";
153 public static final String SHOW_SHORT_LOG_NAME_KEY = SYSTEM_PREFIX + "showShortLogName";
154 public static final String LOG_FILE_KEY = SYSTEM_PREFIX + "logFile";
155 public static final String LEVEL_IN_BRACKETS_KEY = SYSTEM_PREFIX + "levelInBrackets";
156 public static final String WARN_LEVEL_STRING_KEY = SYSTEM_PREFIX + "warnLevelString";
157
158 public static final String LOG_KEY_PREFIX = SYSTEM_PREFIX + "log.";
159
160 private static String getStringProperty(String name) {
161 String prop = null;
162 try {
163 prop = System.getProperty(name);
164 } catch (SecurityException e) {
165 ; // Ignore
166 }
167 return (prop == null) ? SIMPLE_LOGGER_PROPS.getProperty(name) : prop;
168 }
169
170 private static String getStringProperty(String name, String defaultValue) {
171 String prop = getStringProperty(name);
172 return (prop == null) ? defaultValue : prop;
173 }
174
175 private static boolean getBooleanProperty(String name, boolean defaultValue) {
176 String prop = getStringProperty(name);
177 return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop);
178 }
179
180 // Initialize class attributes.
181 // Load properties file, if found.
182 // Override with system properties.
183 static void init() {
184 INITIALIZED = true;
185 loadProperties();
186
187 String defaultLogLevelString = getStringProperty(DEFAULT_LOG_LEVEL_KEY, null);
188 if (defaultLogLevelString != null)
189 DEFAULT_LOG_LEVEL = stringToLevel(defaultLogLevelString);
190
191 SHOW_LOG_NAME = getBooleanProperty(SHOW_LOG_NAME_KEY, SHOW_LOG_NAME);
192 SHOW_SHORT_LOG_NAME = getBooleanProperty(SHOW_SHORT_LOG_NAME_KEY, SHOW_SHORT_LOG_NAME);
193 SHOW_DATE_TIME = getBooleanProperty(SHOW_DATE_TIME_KEY, SHOW_DATE_TIME);
194 SHOW_THREAD_NAME = getBooleanProperty(SHOW_THREAD_NAME_KEY, SHOW_THREAD_NAME);
195 DATE_TIME_FORMAT_STR = getStringProperty(DATE_TIME_FORMAT_KEY, DATE_TIME_FORMAT_STR);
196 LEVEL_IN_BRACKETS = getBooleanProperty(LEVEL_IN_BRACKETS_KEY, LEVEL_IN_BRACKETS);
197 WARN_LEVEL_STRING = getStringProperty(WARN_LEVEL_STRING_KEY, WARN_LEVEL_STRING);
198
199 LOG_FILE = getStringProperty(LOG_FILE_KEY, LOG_FILE);
200 TARGET_STREAM = computeTargetStream(LOG_FILE);
201
202 if (DATE_TIME_FORMAT_STR != null) {
203 try {
204 DATE_FORMATTER = new SimpleDateFormat(DATE_TIME_FORMAT_STR);
205 } catch (IllegalArgumentException e) {
206 Util.report("Bad date format in " + CONFIGURATION_FILE + "; will output relative time", e);
207 }
208 }
209 }
210
211 private static PrintStream computeTargetStream(String logFile) {
212 if ("System.err".equalsIgnoreCase(logFile))
213 return System.err;
214 else if ("System.out".equalsIgnoreCase(logFile)) {
215 return System.out;
216 } else {
217 try {
218 FileOutputStream fos = new FileOutputStream(logFile);
219 PrintStream printStream = new PrintStream(fos);
220 return printStream;
221 } catch (FileNotFoundException e) {
222 Util.report("Could not open [" + logFile + "]. Defaulting to System.err", e);
223 return System.err;
224 }
225 }
226 }
227
228 private static void loadProperties() {
229 // Add props from the resource simplelogger.properties
230 InputStream in = AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
231 public InputStream run() {
232 ClassLoader threadCL = Thread.currentThread().getContextClassLoader();
233 if (threadCL != null) {
234 return threadCL.getResourceAsStream(CONFIGURATION_FILE);
235 } else {
236 return ClassLoader.getSystemResourceAsStream(CONFIGURATION_FILE);
237 }
238 }
239 });
240 if (null != in) {
241 try {
242 SIMPLE_LOGGER_PROPS.load(in);
243 in.close();
244 } catch (java.io.IOException e) {
245 // ignored
246 }
247 }
248 }
249
250 /** The current log level */
251 protected int currentLogLevel = LOG_LEVEL_INFO;
252 /** The short name of this simple log instance */
253 private transient String shortLogName = null;
254
255 /**
256 * Package access allows only {@link SimpleLoggerFactory} to instantiate
257 * SimpleLogger instances.
258 */
259 SimpleLogger(String name) {
260 if (!INITIALIZED) {
261 init();
262 }
263 this.name = name;
264
265 String levelString = recursivelyComputeLevelString();
266 if (levelString != null) {
267 this.currentLogLevel = stringToLevel(levelString);
268 } else {
269 this.currentLogLevel = DEFAULT_LOG_LEVEL;
270 }
271 }
272
273 String recursivelyComputeLevelString() {
274 String tempName = name;
275 String levelString = null;
276 int indexOfLastDot = tempName.length();
277 while ((levelString == null) && (indexOfLastDot > -1)) {
278 tempName = tempName.substring(0, indexOfLastDot);
279 levelString = getStringProperty(LOG_KEY_PREFIX + tempName, null);
280 indexOfLastDot = String.valueOf(tempName).lastIndexOf(".");
281 }
282 return levelString;
283 }
284
285 private static int stringToLevel(String levelStr) {
286 if ("trace".equalsIgnoreCase(levelStr)) {
287 return LOG_LEVEL_TRACE;
288 } else if ("debug".equalsIgnoreCase(levelStr)) {
289 return LOG_LEVEL_DEBUG;
290 } else if ("info".equalsIgnoreCase(levelStr)) {
291 return LOG_LEVEL_INFO;
292 } else if ("warn".equalsIgnoreCase(levelStr)) {
293 return LOG_LEVEL_WARN;
294 } else if ("error".equalsIgnoreCase(levelStr)) {
295 return LOG_LEVEL_ERROR;
296 }
297 // assume INFO by default
298 return LOG_LEVEL_INFO;
299 }
300
301 /**
302 * This is our internal implementation for logging regular (non-parameterized)
303 * log messages.
304 *
305 * @param level One of the LOG_LEVEL_XXX constants defining the log level
306 * @param message The message itself
307 * @param t The exception whose stack trace should be logged
308 */
309 private void log(int level, String message, Throwable t) {
310 if (!isLevelEnabled(level)) {
311 return;
312 }
313
314 StringBuilder buf = new StringBuilder(32);
315
316 // Append date-time if so configured
317 if (SHOW_DATE_TIME) {
318 if (DATE_FORMATTER != null) {
319 buf.append(getFormattedDate());
320 buf.append(' ');
321 } else {
322 buf.append(System.currentTimeMillis() - START_TIME);
323 buf.append(' ');
324 }
325 }
326
327 // Append current thread name if so configured
328 if (SHOW_THREAD_NAME) {
329 buf.append('[');
330 buf.append(Thread.currentThread().getName());
331 buf.append("] ");
332 }
333
334 if (LEVEL_IN_BRACKETS)
335 buf.append('[');
336
337 // Append a readable representation of the log level
338 switch (level) {
339 case LOG_LEVEL_TRACE:
340 buf.append("TRACE");
341 break;
342 case LOG_LEVEL_DEBUG:
343 buf.append("DEBUG");
344 break;
345 case LOG_LEVEL_INFO:
346 buf.append("INFO");
347 break;
348 case LOG_LEVEL_WARN:
349 buf.append(WARN_LEVEL_STRING);
350 break;
351 case LOG_LEVEL_ERROR:
352 buf.append("ERROR");
353 break;
354 }
355 if (LEVEL_IN_BRACKETS)
356 buf.append(']');
357 buf.append(' ');
358
359 // Append the name of the log instance if so configured
360 if (SHOW_SHORT_LOG_NAME) {
361 if (shortLogName == null)
362 shortLogName = computeShortName();
363 buf.append(String.valueOf(shortLogName)).append(" - ");
364 } else if (SHOW_LOG_NAME) {
365 buf.append(String.valueOf(name)).append(" - ");
366 }
367
368 // Append the message
369 buf.append(message);
370
371 write(buf, t);
372
373 }
374
375 void write(StringBuilder buf, Throwable t) {
376 TARGET_STREAM.println(buf.toString());
377 if (t != null) {
378 t.printStackTrace(TARGET_STREAM);
379 }
380 TARGET_STREAM.flush();
381 }
382
383 private String getFormattedDate() {
384 Date now = new Date();
385 String dateText;
386 synchronized (DATE_FORMATTER) {
387 dateText = DATE_FORMATTER.format(now);
388 }
389 return dateText;
390 }
391
392 private String computeShortName() {
393 return name.substring(name.lastIndexOf(".") + 1);
394 }
395
396 /**
397 * For formatted messages, first substitute arguments and then log.
398 *
399 * @param level
400 * @param format
401 * @param arg1
402 * @param arg2
403 */
404 private void formatAndLog(int level, String format, Object arg1, Object arg2) {
405 if (!isLevelEnabled(level)) {
406 return;
407 }
408 FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
409 log(level, tp.getMessage(), tp.getThrowable());
410 }
411
412 /**
413 * For formatted messages, first substitute arguments and then log.
414 *
415 * @param level
416 * @param format
417 * @param arguments a list of 3 ore more arguments
418 */
419 private void formatAndLog(int level, String format, Object... arguments) {
420 if (!isLevelEnabled(level)) {
421 return;
422 }
423 FormattingTuple tp = MessageFormatter.arrayFormat(format, arguments);
424 log(level, tp.getMessage(), tp.getThrowable());
425 }
426
427 /**
428 * Is the given log level currently enabled?
429 *
430 * @param logLevel is this level enabled?
431 */
432 protected boolean isLevelEnabled(int logLevel) {
433 // log level are numerically ordered so can use simple numeric
434 // comparison
435 return (logLevel >= currentLogLevel);
436 }
437
438 /** Are {@code trace} messages currently enabled? */
439 public boolean isTraceEnabled() {
440 return isLevelEnabled(LOG_LEVEL_TRACE);
441 }
442
443 /**
444 * A simple implementation which logs messages of level TRACE according
445 * to the format outlined above.
446 */
447 public void trace(String msg) {
448 log(LOG_LEVEL_TRACE, msg, null);
449 }
450
451 /**
452 * Perform single parameter substitution before logging the message of level
453 * TRACE according to the format outlined above.
454 */
455 public void trace(String format, Object param1) {
456 formatAndLog(LOG_LEVEL_TRACE, format, param1, null);
457 }
458
459 /**
460 * Perform double parameter substitution before logging the message of level
461 * TRACE according to the format outlined above.
462 */
463 public void trace(String format, Object param1, Object param2) {
464 formatAndLog(LOG_LEVEL_TRACE, format, param1, param2);
465 }
466
467 /**
468 * Perform double parameter substitution before logging the message of level
469 * TRACE according to the format outlined above.
470 */
471 public void trace(String format, Object... argArray) {
472 formatAndLog(LOG_LEVEL_TRACE, format, argArray);
473 }
474
475 /** Log a message of level TRACE, including an exception. */
476 public void trace(String msg, Throwable t) {
477 log(LOG_LEVEL_TRACE, msg, t);
478 }
479
480 /** Are {@code debug} messages currently enabled? */
481 public boolean isDebugEnabled() {
482 return isLevelEnabled(LOG_LEVEL_DEBUG);
483 }
484
485 /**
486 * A simple implementation which logs messages of level DEBUG according
487 * to the format outlined above.
488 */
489 public void debug(String msg) {
490 log(LOG_LEVEL_DEBUG, msg, null);
491 }
492
493 /**
494 * Perform single parameter substitution before logging the message of level
495 * DEBUG according to the format outlined above.
496 */
497 public void debug(String format, Object param1) {
498 formatAndLog(LOG_LEVEL_DEBUG, format, param1, null);
499 }
500
501 /**
502 * Perform double parameter substitution before logging the message of level
503 * DEBUG according to the format outlined above.
504 */
505 public void debug(String format, Object param1, Object param2) {
506 formatAndLog(LOG_LEVEL_DEBUG, format, param1, param2);
507 }
508
509 /**
510 * Perform double parameter substitution before logging the message of level
511 * DEBUG according to the format outlined above.
512 */
513 public void debug(String format, Object... argArray) {
514 formatAndLog(LOG_LEVEL_DEBUG, format, argArray);
515 }
516
517 /** Log a message of level DEBUG, including an exception. */
518 public void debug(String msg, Throwable t) {
519 log(LOG_LEVEL_DEBUG, msg, t);
520 }
521
522 /** Are {@code info} messages currently enabled? */
523 public boolean isInfoEnabled() {
524 return isLevelEnabled(LOG_LEVEL_INFO);
525 }
526
527 /**
528 * A simple implementation which logs messages of level INFO according
529 * to the format outlined above.
530 */
531 public void info(String msg) {
532 log(LOG_LEVEL_INFO, msg, null);
533 }
534
535 /**
536 * Perform single parameter substitution before logging the message of level
537 * INFO according to the format outlined above.
538 */
539 public void info(String format, Object arg) {
540 formatAndLog(LOG_LEVEL_INFO, format, arg, null);
541 }
542
543 /**
544 * Perform double parameter substitution before logging the message of level
545 * INFO according to the format outlined above.
546 */
547 public void info(String format, Object arg1, Object arg2) {
548 formatAndLog(LOG_LEVEL_INFO, format, arg1, arg2);
549 }
550
551 /**
552 * Perform double parameter substitution before logging the message of level
553 * INFO according to the format outlined above.
554 */
555 public void info(String format, Object... argArray) {
556 formatAndLog(LOG_LEVEL_INFO, format, argArray);
557 }
558
559 /** Log a message of level INFO, including an exception. */
560 public void info(String msg, Throwable t) {
561 log(LOG_LEVEL_INFO, msg, t);
562 }
563
564 /** Are {@code warn} messages currently enabled? */
565 public boolean isWarnEnabled() {
566 return isLevelEnabled(LOG_LEVEL_WARN);
567 }
568
569 /**
570 * A simple implementation which always logs messages of level WARN according
571 * to the format outlined above.
572 */
573 public void warn(String msg) {
574 log(LOG_LEVEL_WARN, msg, null);
575 }
576
577 /**
578 * Perform single parameter substitution before logging the message of level
579 * WARN according to the format outlined above.
580 */
581 public void warn(String format, Object arg) {
582 formatAndLog(LOG_LEVEL_WARN, format, arg, null);
583 }
584
585 /**
586 * Perform double parameter substitution before logging the message of level
587 * WARN according to the format outlined above.
588 */
589 public void warn(String format, Object arg1, Object arg2) {
590 formatAndLog(LOG_LEVEL_WARN, format, arg1, arg2);
591 }
592
593 /**
594 * Perform double parameter substitution before logging the message of level
595 * WARN according to the format outlined above.
596 */
597 public void warn(String format, Object... argArray) {
598 formatAndLog(LOG_LEVEL_WARN, format, argArray);
599 }
600
601 /** Log a message of level WARN, including an exception. */
602 public void warn(String msg, Throwable t) {
603 log(LOG_LEVEL_WARN, msg, t);
604 }
605
606 /** Are {@code error} messages currently enabled? */
607 public boolean isErrorEnabled() {
608 return isLevelEnabled(LOG_LEVEL_ERROR);
609 }
610
611 /**
612 * A simple implementation which always logs messages of level ERROR according
613 * to the format outlined above.
614 */
615 public void error(String msg) {
616 log(LOG_LEVEL_ERROR, msg, null);
617 }
618
619 /**
620 * Perform single parameter substitution before logging the message of level
621 * ERROR according to the format outlined above.
622 */
623 public void error(String format, Object arg) {
624 formatAndLog(LOG_LEVEL_ERROR, format, arg, null);
625 }
626
627 /**
628 * Perform double parameter substitution before logging the message of level
629 * ERROR according to the format outlined above.
630 */
631 public void error(String format, Object arg1, Object arg2) {
632 formatAndLog(LOG_LEVEL_ERROR, format, arg1, arg2);
633 }
634
635 /**
636 * Perform double parameter substitution before logging the message of level
637 * ERROR according to the format outlined above.
638 */
639 public void error(String format, Object... argArray) {
640 formatAndLog(LOG_LEVEL_ERROR, format, argArray);
641 }
642
643 /** Log a message of level ERROR, including an exception. */
644 public void error(String msg, Throwable t) {
645 log(LOG_LEVEL_ERROR, msg, t);
646 }
647 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ConcurrentMap;
28
29 import org.slf4j.Logger;
30 import org.slf4j.ILoggerFactory;
31
32 /**
33 * An implementation of {@link ILoggerFactory} which always returns
34 * {@link SimpleLogger} instances.
35 *
36 * @author Ceki G&uuml;lc&uuml;
37 */
38 public class SimpleLoggerFactory implements ILoggerFactory {
39
40 ConcurrentMap<String, Logger> loggerMap;
41
42 public SimpleLoggerFactory() {
43 loggerMap = new ConcurrentHashMap<String, Logger>();
44 }
45
46 /**
47 * Return an appropriate {@link SimpleLogger} instance by name.
48 */
49 public Logger getLogger(String name) {
50 Logger simpleLogger = loggerMap.get(name);
51 if (simpleLogger != null) {
52 return simpleLogger;
53 } else {
54 Logger newInstance = new SimpleLogger(name);
55 Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
56 return oldInstance == null ? newInstance : oldInstance;
57 }
58 }
59
60 /**
61 * Clear the internal logger cache.
62 *
63 * This method is intended to be called by classes (in the same package) for
64 * testing purposes. This method is internal. It can be modified, renamed or
65 * removed at any time without notice.
66 *
67 * You are strongly discouraged from calling this method in production code.
68 */
69 void reset() {
70 loggerMap.clear();
71 }
72 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.ILoggerFactory;
27 import org.slf4j.LoggerFactory;
28 import org.slf4j.spi.LoggerFactoryBinder;
29
30 /**
31 * The binding of {@link LoggerFactory} class with an actual instance of
32 * {@link ILoggerFactory} is performed using information returned by this class.
33 *
34 *
35 * @author Ceki G&uuml;lc&uuml;
36 */
37 public class StaticLoggerBinder implements LoggerFactoryBinder {
38
39 /**
40 * The unique instance of this class.
41 *
42 */
43 private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
44
45 /**
46 * Return the singleton of this class.
47 *
48 * @return the StaticLoggerBinder singleton
49 */
50 public static final StaticLoggerBinder getSingleton() {
51 return SINGLETON;
52 }
53
54 /**
55 * Declare the version of the SLF4J API this implementation is compiled
56 * against. The value of this field is usually modified with each release.
57 */
58 // to avoid constant folding by the compiler, this field must *not* be final
59 public static String REQUESTED_API_VERSION = "1.6.99"; // !final
60
61 private static final String loggerFactoryClassStr = SimpleLoggerFactory.class.getName();
62
63 /**
64 * The ILoggerFactory instance returned by the {@link #getLoggerFactory}
65 * method should always be the same object
66 */
67 private final ILoggerFactory loggerFactory;
68
69 private StaticLoggerBinder() {
70 loggerFactory = new SimpleLoggerFactory();
71 }
72
73 public ILoggerFactory getLoggerFactory() {
74 return loggerFactory;
75 }
76
77 public String getLoggerFactoryClassStr() {
78 return loggerFactoryClassStr;
79 }
80 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.slf4j.helpers.NOPMDCAdapter;
27 import org.slf4j.spi.MDCAdapter;
28
29 /**
30 * This implementation is bound to {@link NOPMDCAdapter}.
31 *
32 * @author Ceki G&uuml;lc&uuml;
33 */
34 public class StaticMDCBinder {
35
36 /**
37 * The unique instance of this class.
38 */
39 public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
40
41 private StaticMDCBinder() {
42 }
43
44 /**
45 * Currently this method always returns an instance of
46 * {@link StaticMDCBinder}.
47 */
48 public MDCAdapter getMDCA() {
49 return new NOPMDCAdapter();
50 }
51
52 public String getMDCAdapterClassStr() {
53 return NOPMDCAdapter.class.getName();
54 }
55 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24
25 package org.slf4j.impl;
26
27 import org.slf4j.IMarkerFactory;
28 import org.slf4j.MarkerFactory;
29 import org.slf4j.helpers.BasicMarkerFactory;
30 import org.slf4j.spi.MarkerFactoryBinder;
31
32 /**
33 *
34 * The binding of {@link MarkerFactory} class with an actual instance of
35 * {@link IMarkerFactory} is performed using information returned by this class.
36 *
37 * @author Ceki G&uuml;lc&uuml;
38 */
39 public class StaticMarkerBinder implements MarkerFactoryBinder {
40
41 /**
42 * The unique instance of this class.
43 */
44 public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder();
45
46 final IMarkerFactory markerFactory = new BasicMarkerFactory();
47
48 private StaticMarkerBinder() {
49 }
50
51 /**
52 * Currently this method always returns an instance of
53 * {@link BasicMarkerFactory}.
54 */
55 public IMarkerFactory getMarkerFactory() {
56 return markerFactory;
57 }
58
59 /**
60 * Currently, this method returns the class name of
61 * {@link BasicMarkerFactory}.
62 */
63 public String getMarkerFactoryClassStr() {
64 return BasicMarkerFactory.class.getName();
65 }
66
67 }
0 Implementation-Title: slf4j-simple
1 Bundle-ManifestVersion: 2
2 Bundle-SymbolicName: slf4j.simple
3 Bundle-Name: slf4j-simple
4 Bundle-Vendor: SLF4J.ORG
5 Require-Bundle: slf4j.api
6 Bundle-RequiredExecutionEnvironment: J2SE-1.5
7 Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion}
8 Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}
9 Fragment-Host: slf4j.api
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28
29 import java.io.ByteArrayOutputStream;
30 import java.io.PrintStream;
31
32 import org.junit.After;
33 import org.junit.Before;
34 import org.junit.Test;
35
36 /**
37 * Tests that detecting logger name mismatches works and doesn't cause problems
38 * or trigger if disabled.
39 * <p>
40 * This test can't live inside slf4j-api because the NOP Logger doesn't
41 * remember its name.
42 *
43 * @author Alexander Dorokhine
44 * @author Ceki G&uuml;lc&uuml;
45 */
46 public class DetectLoggerNameMismatchTest {
47
48 private static final String MISMATCH_STRING = "Detected logger name mismatch";
49
50 private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
51 private final PrintStream oldErr = System.err;
52
53 @Before
54 public void setUp() {
55 System.setErr(new PrintStream(byteArrayOutputStream));
56 }
57
58 @After
59 public void tearDown() {
60 setTrialEnabled(false);
61 System.setErr(oldErr);
62 }
63
64 /*
65 * Pass in the wrong class to the Logger with the check disabled, and make sure there are no errors.
66 */
67 @Test
68 public void testNoTriggerWithoutProperty() {
69 setTrialEnabled(false);
70 Logger logger = LoggerFactory.getLogger(String.class);
71 assertEquals("java.lang.String", logger.getName());
72 assertMismatchDetected(false);
73 }
74
75 /*
76 * Pass in the wrong class to the Logger with the check enabled, and make sure there ARE errors.
77 */
78 @Test
79 public void testTriggerWithProperty() {
80 setTrialEnabled(true);
81 LoggerFactory.getLogger(String.class);
82 assertMismatchDetected(true);
83 }
84
85 /*
86 * Checks the whole error message to ensure all the names show up correctly.
87 */
88 @Test
89 public void testTriggerWholeMessage() {
90 setTrialEnabled(true);
91 LoggerFactory.getLogger(String.class);
92 assertTrue("Actual value of byteArrayOutputStream: " + String.valueOf(byteArrayOutputStream), String.valueOf(byteArrayOutputStream).contains(
93 "Detected logger name mismatch. Given name: \"java.lang.String\"; " + "computed name: \"org.slf4j.DetectLoggerNameMismatchTest\"."));
94 }
95
96 /*
97 * Checks that there are no errors with the check enabled if the class matches.
98 */
99 @Test
100 public void testPassIfMatch() {
101 setTrialEnabled(true);
102 Logger logger = LoggerFactory.getLogger(DetectLoggerNameMismatchTest.class);
103 assertEquals("org.slf4j.DetectLoggerNameMismatchTest", logger.getName());
104 assertMismatchDetected(false);
105 }
106
107 private void assertMismatchDetected(boolean mismatchDetected) {
108 assertEquals(mismatchDetected, String.valueOf(byteArrayOutputStream).contains(MISMATCH_STRING));
109 }
110
111 @Test
112 public void verifyLoggerDefinedInBaseWithOverridenGetClassMethod() {
113 setTrialEnabled(true);
114 Square square = new Square();
115 assertEquals("org.slf4j.Square", square.logger.getName());
116 assertMismatchDetected(false);
117 }
118
119 private static void setTrialEnabled(boolean enabled) {
120 // The system property is read into a static variable at initialization time
121 // so we cannot just reset the system property to test this feature.
122 // Therefore we set the variable directly.
123 LoggerFactory.DETECT_LOGGER_NAME_MISMATCH = enabled;
124 }
125 }
126
127 // Used for testing that inheritance is ignored by the checker.
128 class ShapeBase {
129 public Logger logger = LoggerFactory.getLogger(getClass());
130 }
131
132 class Square extends ShapeBase {
133 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27
28 import junit.framework.TestCase;
29
30 /**
31 * Test whether invoking the SLF4J API causes problems or not.
32 *
33 * @author Ceki Gulcu
34 *
35 */
36 public class InvocationTest extends TestCase {
37
38 PrintStream old = System.err;
39
40 public InvocationTest(String arg0) {
41 super(arg0);
42 }
43
44 protected void setUp() throws Exception {
45 super.setUp();
46 System.setErr(new SilentPrintStream(old));
47 }
48
49 protected void tearDown() throws Exception {
50 super.tearDown();
51 System.setErr(old);
52 }
53
54 public void test1() {
55 Logger logger = LoggerFactory.getLogger("test1");
56 logger.debug("Hello world.");
57 }
58
59 public void test2() {
60 Integer i1 = new Integer(1);
61 Integer i2 = new Integer(2);
62 Integer i3 = new Integer(3);
63 Exception e = new Exception("This is a test exception.");
64 Logger logger = LoggerFactory.getLogger("test2");
65
66 logger.debug("Hello world 1.");
67 logger.debug("Hello world {}", i1);
68 logger.debug("val={} val={}", i1, i2);
69 logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 });
70
71 logger.debug("Hello world 2", e);
72 logger.info("Hello world 2.");
73
74 logger.warn("Hello world 3.");
75 logger.warn("Hello world 3", e);
76
77 logger.error("Hello world 4.");
78 logger.error("Hello world {}", new Integer(3));
79 logger.error("Hello world 4.", e);
80 }
81
82 // http://bugzilla.slf4j.org/show_bug.cgi?id=78
83 public void testNullParameter_BUG78() {
84 Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78");
85 String[] parameters = null;
86 String msg = "hello {}";
87 logger.info(msg, parameters);
88 }
89
90 public void testNull() {
91 Logger logger = LoggerFactory.getLogger("testNull");
92 logger.debug(null);
93 logger.info(null);
94 logger.warn(null);
95 logger.error(null);
96
97 Exception e = new Exception("This is a test exception.");
98 logger.debug(null, e);
99 logger.info(null, e);
100 logger.warn(null, e);
101 logger.error(null, e);
102 }
103
104 public void testMarker() {
105 Logger logger = LoggerFactory.getLogger("testMarker");
106 Marker blue = MarkerFactory.getMarker("BLUE");
107 logger.debug(blue, "hello");
108 logger.info(blue, "hello");
109 logger.warn(blue, "hello");
110 logger.error(blue, "hello");
111
112 logger.debug(blue, "hello {}", "world");
113 logger.info(blue, "hello {}", "world");
114 logger.warn(blue, "hello {}", "world");
115 logger.error(blue, "hello {}", "world");
116
117 logger.debug(blue, "hello {} and {} ", "world", "universe");
118 logger.info(blue, "hello {} and {} ", "world", "universe");
119 logger.warn(blue, "hello {} and {} ", "world", "universe");
120 logger.error(blue, "hello {} and {} ", "world", "universe");
121 }
122
123 public void testMDC() {
124 MDC.put("k", "v");
125 assertNull(MDC.get("k"));
126 MDC.remove("k");
127 assertNull(MDC.get("k"));
128 MDC.clear();
129 }
130 }
0 /**
1 * Copyright (c) 2004-2011 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j;
25
26 import java.io.PrintStream;
27
28 public class SilentPrintStream extends PrintStream {
29
30 PrintStream other;
31
32 public SilentPrintStream(PrintStream ps) {
33 super(ps);
34 other = ps;
35 }
36
37 public void print(String s) {
38 }
39
40 public void println(String s) {
41 }
42
43 public void println(Object x) {
44 }
45 }
0 /**
1 * Copyright (c) 2004-2012 QOS.ch
2 * All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files (the
6 * "Software"), to deal in the Software without restriction, including
7 * without limitation the rights to use, copy, modify, merge, publish,
8 * distribute, sublicense, and/or sell copies of the Software, and to
9 * permit persons to whom the Software is furnished to do so, subject to
10 * the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 */
24 package org.slf4j.impl;
25
26 import org.junit.After;
27 import org.junit.Before;
28 import org.junit.Test;
29
30 import static junit.framework.Assert.assertEquals;
31 import static junit.framework.Assert.assertNull;
32
33 public class SimpleLoggerTest {
34
35 String A_KEY = SimpleLogger.LOG_KEY_PREFIX + "a";
36
37 @Before
38 public void before() {
39 System.setProperty(A_KEY, "info");
40 }
41
42 @After
43 public void after() {
44 System.clearProperty(A_KEY);
45 }
46
47 @Test
48 public void emptyLoggerName() {
49 SimpleLogger simpleLogger = new SimpleLogger("a");
50 assertEquals("info", simpleLogger.recursivelyComputeLevelString());
51 }
52
53 @Test
54 public void loggerNameWithNoDots_WithLevel() {
55 SimpleLogger simpleLogger = new SimpleLogger("a");
56 assertEquals("info", simpleLogger.recursivelyComputeLevelString());
57 }
58
59 @Test
60 public void loggerNameWithOneDotShouldInheritFromParent() {
61 SimpleLogger simpleLogger = new SimpleLogger("a.b");
62 assertEquals("info", simpleLogger.recursivelyComputeLevelString());
63 }
64
65 @Test
66 public void loggerNameWithNoDots_WithNoSetLevel() {
67 SimpleLogger simpleLogger = new SimpleLogger("x");
68 assertNull(simpleLogger.recursivelyComputeLevelString());
69 }
70
71 @Test
72 public void loggerNameWithOneDot_NoSetLevel() {
73 SimpleLogger simpleLogger = new SimpleLogger("x.y");
74 assertNull(simpleLogger.recursivelyComputeLevelString());
75 }
76
77 }
0 # SLF4J's SimpleLogger configuration file
1 # Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
2
3 # Default logging detail level for all instances of SimpleLogger.
4 # Must be one of ("trace", "debug", "info", "warn", or "error").
5 # If not specified, defaults to "info".
6 #org.slf4j.simpleLogger.defaultLogLevel=info
7
8 # Logging detail level for a SimpleLogger instance named "xxxxx".
9 # Must be one of ("trace", "debug", "info", "warn", or "error").
10 # If not specified, the default logging detail level is used.
11 #org.slf4j.simpleLogger.log.xxxxx=
12
13 # Set to true if you want the current date and time to be included in output messages.
14 # Default is false, and will output the number of milliseconds elapsed since startup.
15 #org.slf4j.simpleLogger.showDateTime=false
16
17 # The date and time format to be used in the output messages.
18 # The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
19 # If the format is not specified or is invalid, the default format is used.
20 # The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
21 #org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
22
23 # Set to true if you want to output the current thread name.
24 # Defaults to true.
25 #org.slf4j.simpleLogger.showThreadName=true
26
27 # Set to true if you want the Logger instance name to be included in output messages.
28 # Defaults to true.
29 #org.slf4j.simpleLogger.showLogName=true
30
31 # Set to true if you want the last component of the name to be included in output messages.
32 # Defaults to false.
33 #org.slf4j.simpleLogger.showShortLogName=false
0 <assembly>
1 <id>dist</id>
2 <formats>
3 <format>zip</format>
4 <format>tar.gz</format>
5 </formats>
6 <fileSets>
7 <!-- Module POMs -->
8 <fileSet>
9 <directory>slf4j-api/</directory>
10 <outputDirectory>slf4j-api/</outputDirectory>
11 <includes>
12 <include>pom.xml</include>
13 </includes>
14 </fileSet>
15
16 <fileSet>
17 <directory>slf4j-jcl/</directory>
18 <outputDirectory>slf4j-jcl/</outputDirectory>
19 <includes>
20 <include>pom.xml</include>
21 </includes>
22 </fileSet>
23
24 <fileSet>
25 <directory>slf4j-jdk14/</directory>
26 <outputDirectory>slf4j-jdk14/</outputDirectory>
27 <includes>
28 <include>pom.xml</include>
29 </includes>
30 </fileSet>
31
32 <fileSet>
33 <directory>slf4j-log4j12/</directory>
34 <outputDirectory>slf4j-log4j12/</outputDirectory>
35 <includes>
36 <include>pom.xml</include>
37 </includes>
38 </fileSet>
39
40 <fileSet>
41 <directory>slf4j-nop/</directory>
42 <outputDirectory>slf4j-nop/</outputDirectory>
43 <includes>
44 <include>pom.xml</include>
45 </includes>
46 </fileSet>
47
48 <fileSet>
49 <directory>slf4j-simple/</directory>
50 <outputDirectory>slf4j-simple/</outputDirectory>
51 <includes>
52 <include>pom.xml</include>
53 </includes>
54 </fileSet>
55
56 <fileSet>
57 <directory>slf4j-android/</directory>
58 <outputDirectory>slf4j-android/</outputDirectory>
59 <includes>
60 <include>pom.xml</include>
61 </includes>
62 </fileSet>
63
64 <fileSet>
65 <directory>slf4j-ext/</directory>
66 <outputDirectory>slf4j-ext/</outputDirectory>
67 <includes>
68 <include>pom.xml</include>
69 </includes>
70 </fileSet>
71
72
73 <fileSet>
74 <directory>jcl104-over-slf4j/</directory>
75 <outputDirectory>jcl104-over-slf4j/</outputDirectory>
76 <includes>
77 <include>pom.xml</include>
78 </includes>
79 </fileSet>
80
81 <fileSet>
82 <directory>jcl-over-slf4j/</directory>
83 <outputDirectory>jcl-over-slf4j/</outputDirectory>
84 <includes>
85 <include>pom.xml</include>
86 </includes>
87 </fileSet>
88
89 <fileSet>
90 <directory>jul-to-slf4j/</directory>
91 <outputDirectory>jul-to-slf4j/</outputDirectory>
92 <includes>
93 <include>pom.xml</include>
94 </includes>
95 </fileSet>
96
97 <fileSet>
98 <directory>log4j-over-slf4j/</directory>
99 <outputDirectory>log4j-over-slf4j/</outputDirectory>
100 <includes><include>pom.xml</include></includes>
101 </fileSet>
102
103 <fileSet>
104 <directory>osgi-over-slf4j/</directory>
105 <outputDirectory>osgi-over-slf4j/</outputDirectory>
106 <includes><include>pom.xml</include></includes>
107 </fileSet>
108
109 <fileSet>
110 <directory>slf4j-site/</directory>
111 <outputDirectory>slf4j-site/</outputDirectory>
112 <includes>
113 <include>pom.xml</include>
114 </includes>
115 </fileSet>
116
117 <fileSet>
118 <directory>slf4j-migrator/</directory>
119 <outputDirectory>slf4j-migrator/</outputDirectory>
120 <includes>
121 <include>pom.xml</include>
122 </includes>
123 </fileSet>
124
125 <fileSet>
126 <directory>integration/</directory>
127 <outputDirectory>integration/</outputDirectory>
128 <includes>
129 <include>pom.xml</include>
130 <include>build.xml</include>
131 <include>osgi-build.xml</include>
132 <include>lib/*</include>
133 </includes>
134 </fileSet>
135
136 <!-- Module Source directories (includes tests) -->
137 <fileSet>
138 <directory>slf4j-api/src/</directory>
139 <outputDirectory>slf4j-api/src/</outputDirectory>
140 <excludes>
141 <exclude>test/output/</exclude>
142 </excludes>
143 </fileSet>
144
145 <fileSet>
146 <directory>slf4j-jcl/src/</directory>
147 <outputDirectory>slf4j-jcl/src/</outputDirectory>
148 </fileSet>
149
150 <fileSet>
151 <directory>slf4j-jdk14/src/</directory>
152 <outputDirectory>slf4j-jdk14/src/</outputDirectory>
153 </fileSet>
154
155 <fileSet>
156 <directory>slf4j-log4j12/src/</directory>
157 <outputDirectory>slf4j-log4j12/src/</outputDirectory>
158 </fileSet>
159 <fileSet>
160 <directory>slf4j-nop/src/</directory>
161 <outputDirectory>slf4j-nop/src/</outputDirectory>
162 </fileSet>
163 <fileSet>
164 <directory>slf4j-simple/src/</directory>
165 <outputDirectory>slf4j-simple/src/</outputDirectory>
166 </fileSet>
167 <fileSet>
168 <directory>slf4j-android/src/</directory>
169 <outputDirectory>slf4j-android/src/</outputDirectory>
170 </fileSet>
171 <fileSet>
172 <directory>slf4j-ext/src/</directory>
173 <outputDirectory>slf4j-ext/src/</outputDirectory>
174 </fileSet>
175 <fileSet>
176 <directory>jcl-over-slf4j/src/</directory>
177 <outputDirectory>jcl-over-slf4j/src/</outputDirectory>
178 </fileSet>
179 <fileSet>
180 <directory>jul-to-slf4j/src/</directory>
181 <outputDirectory>jul-to-slf4j/src/</outputDirectory>
182 </fileSet>
183 <fileSet>
184 <directory>log4j-over-slf4j/src/</directory>
185 <outputDirectory>log4j-over-slf4j/src/</outputDirectory>
186 </fileSet>
187 <fileSet>
188 <directory>osgi-over-slf4j/src/</directory>
189 <outputDirectory>osgi-over-slf4j/src/</outputDirectory>
190 </fileSet>
191 <fileSet>
192 <directory>slf4j-site/src/</directory>
193 <outputDirectory>slf4j-site/src/</outputDirectory>
194 </fileSet>
195 <fileSet>
196 <directory>slf4j-migrator/src/</directory>
197 <outputDirectory>slf4j-migrator/src/</outputDirectory>
198 </fileSet>
199 <fileSet>
200 <directory>integration/src/</directory>
201 <outputDirectory>integration/src/</outputDirectory>
202 </fileSet>
203
204
205 <!-- Module JARs -->
206 <fileSet>
207 <directory>slf4j-api/target/</directory>
208 <outputDirectory>/</outputDirectory>
209 <includes>
210 <include>slf4j-api-${project.version}-sources.jar</include>
211 <include>slf4j-api-${project.version}.jar</include>
212 </includes>
213 </fileSet>
214
215 <fileSet>
216 <directory>slf4j-jcl/target/</directory>
217 <outputDirectory>/</outputDirectory>
218 <includes>
219 <include>slf4j-jcl-${project.version}.jar</include>
220 <include>slf4j-jcl-${project.version}-sources.jar</include>
221 </includes>
222 </fileSet>
223
224 <fileSet>
225 <directory>slf4j-jdk14/target/</directory>
226 <outputDirectory>/</outputDirectory>
227 <includes>
228 <include>slf4j-jdk14-${project.version}-sources.jar</include>
229 <include>slf4j-jdk14-${project.version}.jar</include>
230 </includes>
231 </fileSet>
232
233 <fileSet>
234 <directory>slf4j-log4j12/target/</directory>
235 <outputDirectory>/</outputDirectory>
236 <includes>
237 <include>slf4j-log4j12-${project.version}.jar</include>
238 <include>slf4j-log4j12-${project.version}-sources.jar</include>
239 </includes>
240 </fileSet>
241
242 <fileSet>
243 <directory>slf4j-nop/target/</directory>
244 <outputDirectory>/</outputDirectory>
245 <includes>
246 <include>slf4j-nop-${project.version}.jar</include>
247 <include>slf4j-nop-${project.version}-sources.jar</include>
248 </includes>
249 </fileSet>
250
251 <fileSet>
252 <directory>slf4j-simple/target/</directory>
253 <outputDirectory>/</outputDirectory>
254 <includes>
255 <include>slf4j-simple-${project.version}-sources*.jar</include>
256 <include>slf4j-simple-${project.version}.jar</include>
257 </includes>
258 </fileSet>
259
260 <fileSet>
261 <directory>slf4j-android/target/</directory>
262 <outputDirectory>/</outputDirectory>
263 <includes>
264 <include>slf4j-android-${project.version}-sources*.jar</include>
265 <include>slf4j-android-${project.version}.jar</include>
266 </includes>
267 </fileSet>
268
269
270 <fileSet>
271 <directory>slf4j-ext/target/</directory>
272 <outputDirectory>/</outputDirectory>
273 <includes>
274 <include>slf4j-ext-${project.version}-sources*.jar</include>
275 <include>slf4j-ext-${project.version}.jar</include>
276 </includes>
277 </fileSet>
278
279
280 <fileSet>
281 <directory>jcl-over-slf4j/target/</directory>
282 <outputDirectory>/</outputDirectory>
283 <includes>
284 <include>jcl-over-slf4j-${project.version}-sources.jar</include>
285 <include>jcl-over-slf4j-${project.version}.jar</include>
286 </includes>
287 </fileSet>
288 <fileSet>
289 <directory>jul-to-slf4j/target/</directory>
290 <outputDirectory>/</outputDirectory>
291 <includes>
292 <include>jul-to-slf4j-${project.version}-sources.jar</include>
293 <include>jul-to-slf4j-${project.version}.jar</include>
294 </includes>
295 </fileSet>
296 <fileSet>
297 <directory>log4j-over-slf4j/target/</directory>
298 <outputDirectory>/</outputDirectory>
299 <includes>
300 <include>log4j-over-slf4j-${project.version}.jar</include>
301 <include>log4j-over-slf4j-${project.version}-sources.jar</include>
302 </includes>
303 </fileSet>
304 <fileSet>
305 <directory>osgi-over-slf4j/target/</directory>
306 <outputDirectory>/</outputDirectory>
307 <includes>
308 <include>osgi-over-slf4j-${project.version}.jar</include>
309 <include>osgi-over-slf4j-${project.version}-sources.jar</include>
310 </includes>
311 </fileSet>
312
313 <fileSet>
314 <directory>slf4j-migrator/target/</directory>
315 <outputDirectory>/</outputDirectory>
316 <includes>
317 <include>slf4j-migrator-${project.version}.jar</include>
318 </includes>
319 </fileSet>
320
321 <!-- Website -->
322 <fileSet>
323 <directory>target/site</directory>
324 <outputDirectory>/site</outputDirectory>
325 <excludes>
326 <exclude>dist/*</exclude>
327 </excludes>
328 </fileSet>
329
330 <!-- Parent files -->
331 <fileSet>
332 <includes>
333 <include>src/</include>
334 <include>README*</include>
335 <include>LICENSE*</include>
336 <include>pom.xml</include>
337 </includes>
338 </fileSet>
339 </fileSets>
340
341 </assembly>
0 <additionalHeaders>
1 <javadoc_style>
2 <firstLine>/**</firstLine>
3 <beforeEachLine> * </beforeEachLine>
4 <endLine> */</endLine>
5 <!--<skipLine>packa</skipLine>-->
6 <firstLineDetectionPattern>(\s|\t)*/\*.*$</firstLineDetectionPattern>
7 <lastLineDetectionPattern>.*\*/(\s|\t)*$</lastLineDetectionPattern>
8 </javadoc_style>
9 </additionalHeaders>
0 Copyright (c) 2004-2011 QOS.ch
1 All rights reserved.
2
3 Permission is hereby granted, free of charge, to any person obtaining
4 a copy of this software and associated documentation files (the
5 "Software"), to deal in the Software without restriction, including
6 without limitation the rights to use, copy, modify, merge, publish,
7 distribute, sublicense, and/or sell copies of the Software, and to
8 permit persons to whom the Software is furnished to do so, subject to
9 the following conditions:
10
11 The above copyright notice and this permission notice shall be
12 included in all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21