diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..412eeda --- /dev/null +++ b/.gitattributes @@ -0,0 +1,22 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..23c65dc --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +.settings +target +.classpath +.project +*~ +*.tmproj +*.iml +.idea +.scala_dependencies +integration/bundle/ +integration/felix-cache/ +runner +.DS_Store diff --git a/.idea/codeStyleSettings.xml b/.idea/codeStyleSettings.xml new file mode 100755 index 0000000..31cb322 --- /dev/null +++ b/.idea/codeStyleSettings.xml @@ -0,0 +1,48 @@ + + + + + + \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100755 index 0000000..74f2ed9 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,4 @@ +language: java +notifications: + email: + - notification@qos.ch diff --git a/LICENSE.txt b/LICENSE.txt index 54f5abe..315bd49 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,24 +1,24 @@ -Copyright (c) 2004-2017 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - +Copyright (c) 2004-2017 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/README.md b/README.md index 1cb4a4f..6966353 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ -# About SLF4J -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. -More information can be found on the [SLF4J website](http://www.slf4j.org). -# Build Status -[![Build Status](https://travis-ci.org/qos-ch/slf4j.png)](https://travis-ci.org/qos-ch/slf4j) - -# How to contribute pull requests -If you are interested in improving SLF4J, great! The SLF4J community looks forward to your contribution. Please follow this process: - -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). -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. -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. -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. -5. Submit a pull request to SLF4J from from your commit page on github. +# About SLF4J +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. +More information can be found on the [SLF4J website](http://www.slf4j.org). +# Build Status +[![Build Status](https://travis-ci.org/qos-ch/slf4j.png)](https://travis-ci.org/qos-ch/slf4j) + +# How to contribute pull requests +If you are interested in improving SLF4J, great! The SLF4J community looks forward to your contribution. Please follow this process: + +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). +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. +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. +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. +5. Submit a pull request to SLF4J from from your commit page on github. diff --git a/codeStyle.xml b/codeStyle.xml new file mode 100644 index 0000000..355c4b1 --- /dev/null +++ b/codeStyle.xml @@ -0,0 +1,295 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/integration/build.xml b/integration/build.xml old file mode 100644 new file mode 100755 index 80f3efc..6f7bb03 100755 --- a/integration/build.xml +++ b/integration/build.xml @@ -1,248 +1,248 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - setPathToPolicy_FromTop - - - - - setPathToPolicy_FromInegration - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + setPathToPolicy_FromTop + + + + + setPathToPolicy_FromInegration + + + + + + + + + + + + + + + diff --git a/integration/osgi-build.xml b/integration/osgi-build.xml index 00f59f7..231c2fa 100644 --- a/integration/osgi-build.xml +++ b/integration/osgi-build.xml @@ -1,92 +1,92 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - value of t = @{t} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + value of t = @{t} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/integration/pom.xml b/integration/pom.xml old file mode 100644 new file mode 100755 index 6d33bc5..b612ae6 100755 --- a/integration/pom.xml +++ b/integration/pom.xml @@ -1,119 +1,119 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - integration - jar - SLF4J Integration tests - - http://www.slf4j.org - SLF4J integration tests - - - - org.slf4j - slf4j-api - - - - - junit - junit - 3.8.1 - - - - ant - ant-junit - 1.6.5 - - - - - org.apache.felix - org.apache.felix.main - 5.6.1 - - - - - - - - maven-antrun-plugin - 1.2 - - - junit - junit - 3.8.1 - - - ant - ant-junit - 1.6.5 - - - - - ant-test - package - - - - - - - - - - - - run - - - - ant-osgi-test - package - - - - - - - - - - run - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - once - plain - false - - **/*Test.java - - - - - - - - + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + integration + jar + SLF4J Integration tests + + http://www.slf4j.org + SLF4J integration tests + + + + org.slf4j + slf4j-api + + + + + junit + junit + 3.8.1 + + + + ant + ant-junit + 1.6.5 + + + + + org.apache.felix + org.apache.felix.main + 5.6.1 + + + + + + + + maven-antrun-plugin + 1.2 + + + junit + junit + 3.8.1 + + + ant + ant-junit + 1.6.5 + + + + + ant-test + package + + + + + + + + + + + + run + + + + ant-osgi-test + package + + + + + + + + + + run + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + once + plain + false + + **/*Test.java + + + + + + + + diff --git a/integration/src/IBUNDLE-META-INF/MANIFEST.MF b/integration/src/IBUNDLE-META-INF/MANIFEST.MF index 07492d4..d518a2b 100644 --- a/integration/src/IBUNDLE-META-INF/MANIFEST.MF +++ b/integration/src/IBUNDLE-META-INF/MANIFEST.MF @@ -1,15 +1,15 @@ -Manifest-Version: 1.0 -Archiver-Version: Plexus Archiver -Created-By: Apache Maven -Built-By: ceki -Build-Jdk: 1.6.0_16 -Bundle-Description: iBundle -Bundle-Version: 0.1 -Bundle-Activator: integrator.Activator -Implementation-Title: iBundle -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: iBundle -Bundle-Name: abundle -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: apack +Manifest-Version: 1.0 +Archiver-Version: Plexus Archiver +Created-By: Apache Maven +Built-By: ceki +Build-Jdk: 1.6.0_16 +Bundle-Description: iBundle +Bundle-Version: 0.1 +Bundle-Activator: integrator.Activator +Implementation-Title: iBundle +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: iBundle +Bundle-Name: abundle +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: apack Import-Package: org.osgi.framework, org.slf4j;version=1.5diff --git a/integration/src/policy/java-eclipse.policy b/integration/src/policy/java-eclipse.policy index f196c95..9a42e4d 100644 --- a/integration/src/policy/java-eclipse.policy +++ b/integration/src/policy/java-eclipse.policy @@ -1,10 +1,10 @@ - -grant { - - // note that java.lang.RuntimePermission createSecurityManager is NOT granted - - permission java.util.PropertyPermission "user.dir", "read"; - permission java.util.PropertyPermission "*", "read"; - - permission java.net.SocketPermission "*", "connect,resolve"; + +grant { + + // note that java.lang.RuntimePermission createSecurityManager is NOT granted + + permission java.util.PropertyPermission "user.dir", "read"; + permission java.util.PropertyPermission "*", "read"; + + permission java.net.SocketPermission "*", "connect,resolve"; };diff --git a/integration/src/policy/java-under-ant.policy b/integration/src/policy/java-under-ant.policy index 1077f96..41f7fcf 100644 --- a/integration/src/policy/java-under-ant.policy +++ b/integration/src/policy/java-under-ant.policy @@ -1,13 +1,13 @@ - -grant { - - // note that java.lang.RuntimePermission createSecurityManager is NOT granted - - permission java.util.PropertyPermission "user.dir", "read"; - - // permissions required for Ant's Junit runner - permission java.util.PropertyPermission "*", "read, write"; - permission java.io.FilePermission "./-", "read"; - permission java.io.FilePermission "./-", "write"; - permission java.lang.RuntimePermission "setIO"; + +grant { + + // note that java.lang.RuntimePermission createSecurityManager is NOT granted + + permission java.util.PropertyPermission "user.dir", "read"; + + // permissions required for Ant's Junit runner + permission java.util.PropertyPermission "*", "read, write"; + permission java.io.FilePermission "./-", "read"; + permission java.io.FilePermission "./-", "write"; + permission java.lang.RuntimePermission "setIO"; };diff --git a/integration/src/test/java/integrator/Activator.java b/integration/src/test/java/integrator/Activator.java index 25f7965..f1b5c78 100644 --- a/integration/src/test/java/integrator/Activator.java +++ b/integration/src/test/java/integrator/Activator.java @@ -1,60 +1,60 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package integrator; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A BundleActivator which invokes slf4j loggers - * @author Ceki Gülcü - * - */ -public class Activator implements BundleActivator { - - private BundleContext m_context = null; - - public void start(BundleContext context) { - Logger logger = LoggerFactory.getLogger(this.getClass()); - logger.info("Activator.start()"); - m_context = context; - } - - public void stop(BundleContext context) { - m_context = null; - Logger logger = LoggerFactory.getLogger(this.getClass()); - logger.info("Activator.stop"); - } - - public Bundle[] getBundles() { - if (m_context != null) { - return m_context.getBundles(); - } - return null; - } +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package integrator; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A BundleActivator which invokes slf4j loggers + * @author Ceki Gülcü + * + */ +public class Activator implements BundleActivator { + + private BundleContext m_context = null; + + public void start(BundleContext context) { + Logger logger = LoggerFactory.getLogger(this.getClass()); + logger.info("Activator.start()"); + m_context = context; + } + + public void stop(BundleContext context) { + m_context = null; + Logger logger = LoggerFactory.getLogger(this.getClass()); + logger.info("Activator.stop"); + } + + public Bundle[] getBundles() { + if (m_context != null) { + return m_context.getBundles(); + } + return null; + } }diff --git a/integration/src/test/java/org/slf4j/CompatibilityAssertionTest.java b/integration/src/test/java/org/slf4j/CompatibilityAssertionTest.java index 501a34b..021ef13 100644 --- a/integration/src/test/java/org/slf4j/CompatibilityAssertionTest.java +++ b/integration/src/test/java/org/slf4j/CompatibilityAssertionTest.java @@ -1,61 +1,61 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -package org.slf4j; - -import java.io.PrintStream; -import java.util.Random; - -import junit.framework.TestCase; - -public class CompatibilityAssertionTest extends TestCase { - - StringPrintStream sps = new StringPrintStream(System.err); - PrintStream old = System.err; - int diff = 1024 + new Random().nextInt(10000); - - public CompatibilityAssertionTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } - - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } - - public void test() throws Exception { - Logger logger = LoggerFactory.getLogger(this.getClass()); - String msg = "hello world " + diff; - logger.info(msg); - assertEquals(1, sps.stringList.size()); - String s0 = (String) sps.stringList.get(0); - assertTrue(s0.contains(msg)); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +package org.slf4j; + +import java.io.PrintStream; +import java.util.Random; + +import junit.framework.TestCase; + +public class CompatibilityAssertionTest extends TestCase { + + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); + + public CompatibilityAssertionTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } + + protected void tearDown() throws Exception { + super.tearDown(); + System.setErr(old); + } + + public void test() throws Exception { + Logger logger = LoggerFactory.getLogger(this.getClass()); + String msg = "hello world " + diff; + logger.info(msg); + assertEquals(1, sps.stringList.size()); + String s0 = (String) sps.stringList.get(0); + assertTrue(s0.contains(msg)); + } +} diff --git a/integration/src/test/java/org/slf4j/IncompatibleMultiBindingAssertionTest.java b/integration/src/test/java/org/slf4j/IncompatibleMultiBindingAssertionTest.java index 001ea1b..80c9b00 100644 --- a/integration/src/test/java/org/slf4j/IncompatibleMultiBindingAssertionTest.java +++ b/integration/src/test/java/org/slf4j/IncompatibleMultiBindingAssertionTest.java @@ -1,74 +1,74 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.io.PrintStream; -import java.util.List; -import java.util.Random; - -import junit.framework.TestCase; - -public class IncompatibleMultiBindingAssertionTest extends TestCase { - - StringPrintStream sps = new StringPrintStream(System.err); - PrintStream old = System.err; - int diff = 1024 + new Random().nextInt(10000); - - public IncompatibleMultiBindingAssertionTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } - - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } - - public void test() throws Exception { - try { - Logger logger = LoggerFactory.getLogger(this.getClass()); - String msg = "hello world " + diff; - logger.info(msg); - fail("was expecting NoSuchMethodError"); - } catch (NoSuchMethodError e) { - } - List list = sps.stringList; - assertMsgContains(list, 0, "Class path contains multiple SLF4J bindings."); - assertMsgContains(list, 1, "Found binding in"); - assertMsgContains(list, 2, "Found binding in"); - assertMsgContains(list, 3, "See http://www.slf4j.org/codes.html"); - assertMsgContains(list, 4, "slf4j-api 1.6.x (or later) is incompatible with this binding"); - assertMsgContains(list, 5, "Your binding is version 1.5.5 or earlier."); - - } - - void assertMsgContains(List strList, int index, String msg) { - assertTrue(((String) strList.get(index)).contains(msg)); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.io.PrintStream; +import java.util.List; +import java.util.Random; + +import junit.framework.TestCase; + +public class IncompatibleMultiBindingAssertionTest extends TestCase { + + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); + + public IncompatibleMultiBindingAssertionTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } + + protected void tearDown() throws Exception { + super.tearDown(); + System.setErr(old); + } + + public void test() throws Exception { + try { + Logger logger = LoggerFactory.getLogger(this.getClass()); + String msg = "hello world " + diff; + logger.info(msg); + fail("was expecting NoSuchMethodError"); + } catch (NoSuchMethodError e) { + } + List list = sps.stringList; + assertMsgContains(list, 0, "Class path contains multiple SLF4J bindings."); + assertMsgContains(list, 1, "Found binding in"); + assertMsgContains(list, 2, "Found binding in"); + assertMsgContains(list, 3, "See http://www.slf4j.org/codes.html"); + assertMsgContains(list, 4, "slf4j-api 1.6.x (or later) is incompatible with this binding"); + assertMsgContains(list, 5, "Your binding is version 1.5.5 or earlier."); + + } + + void assertMsgContains(List strList, int index, String msg) { + assertTrue(((String) strList.get(index)).contains(msg)); + } +} diff --git a/integration/src/test/java/org/slf4j/MissingSingletonMethodAssertionTest.java b/integration/src/test/java/org/slf4j/MissingSingletonMethodAssertionTest.java index 08776f8..96c2b41 100644 --- a/integration/src/test/java/org/slf4j/MissingSingletonMethodAssertionTest.java +++ b/integration/src/test/java/org/slf4j/MissingSingletonMethodAssertionTest.java @@ -1,83 +1,83 @@ -/** - * Copyright (c) 2004-2016 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.io.PrintStream; -import java.util.Random; - -import junit.framework.TestCase; - -public class MissingSingletonMethodAssertionTest extends TestCase { - - StringPrintStream sps = new StringPrintStream(System.err); - PrintStream old = System.err; - int diff = 1024 + new Random().nextInt(10000); - - public MissingSingletonMethodAssertionTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } - - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } - - public void test() throws Exception { - try { - Logger logger = LoggerFactory.getLogger(this.getClass()); - String msg = "hello world " + diff; - logger.info(msg); - fail("NoSuchMethodError expected"); - } catch (NoSuchMethodError e) { - } - - int lineCount = sps.stringList.size(); - assertTrue("number of lines should be 3 but was " + lineCount, lineCount == 3); - - // expected output: - // SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding. - // SLF4J: Your binding is version 1.4.x or earlier. - // SLF4J: Upgrade your binding to version 1.6.x. or 2.0.x - - { - String s = (String) sps.stringList.get(0); - assertTrue(s.contains("SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.")); - } - { - String s = (String) sps.stringList.get(1); - assertTrue(s.contains("SLF4J: Your binding is version 1.5.5 or earlier.")); - } - { - String s = (String) sps.stringList.get(2); - assertTrue(s.contains("SLF4J: Upgrade your binding to version 1.6.x.")); - } - - } -} +/** + * Copyright (c) 2004-2016 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.io.PrintStream; +import java.util.Random; + +import junit.framework.TestCase; + +public class MissingSingletonMethodAssertionTest extends TestCase { + + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); + + public MissingSingletonMethodAssertionTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } + + protected void tearDown() throws Exception { + super.tearDown(); + System.setErr(old); + } + + public void test() throws Exception { + try { + Logger logger = LoggerFactory.getLogger(this.getClass()); + String msg = "hello world " + diff; + logger.info(msg); + fail("NoSuchMethodError expected"); + } catch (NoSuchMethodError e) { + } + + int lineCount = sps.stringList.size(); + assertTrue("number of lines should be 3 but was " + lineCount, lineCount == 3); + + // expected output: + // SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding. + // SLF4J: Your binding is version 1.4.x or earlier. + // SLF4J: Upgrade your binding to version 1.6.x. or 2.0.x + + { + String s = (String) sps.stringList.get(0); + assertTrue(s.contains("SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.")); + } + { + String s = (String) sps.stringList.get(1); + assertTrue(s.contains("SLF4J: Your binding is version 1.5.5 or earlier.")); + } + { + String s = (String) sps.stringList.get(2); + assertTrue(s.contains("SLF4J: Upgrade your binding to version 1.6.x.")); + } + + } +} diff --git a/integration/src/test/java/org/slf4j/MultiBindingAssertionTest.java b/integration/src/test/java/org/slf4j/MultiBindingAssertionTest.java index 5cbf131..8d1cb59 100644 --- a/integration/src/test/java/org/slf4j/MultiBindingAssertionTest.java +++ b/integration/src/test/java/org/slf4j/MultiBindingAssertionTest.java @@ -1,68 +1,68 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.io.PrintStream; -import java.util.List; -import java.util.Random; - -import junit.framework.TestCase; - -public class MultiBindingAssertionTest extends TestCase { - - StringPrintStream sps = new StringPrintStream(System.err); - PrintStream old = System.err; - int diff = 1024 + new Random().nextInt(10000); - - public MultiBindingAssertionTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } - - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } - - public void test() throws Exception { - Logger logger = LoggerFactory.getLogger(this.getClass()); - String msg = "hello world " + diff; - logger.info(msg); - List list = sps.stringList; - assertMsgContains(list, 0, "Class path contains multiple SLF4J bindings."); - assertMsgContains(list, 1, "Found binding in"); - assertMsgContains(list, 2, "Found binding in"); - assertMsgContains(list, 3, "See http://www.slf4j.org/codes.html"); - assertMsgContains(list, 4, "Actual binding is of type ["); - } - - void assertMsgContains(List strList, int index, String msg) { - assertTrue(((String) strList.get(index)).contains(msg)); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.io.PrintStream; +import java.util.List; +import java.util.Random; + +import junit.framework.TestCase; + +public class MultiBindingAssertionTest extends TestCase { + + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); + + public MultiBindingAssertionTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } + + protected void tearDown() throws Exception { + super.tearDown(); + System.setErr(old); + } + + public void test() throws Exception { + Logger logger = LoggerFactory.getLogger(this.getClass()); + String msg = "hello world " + diff; + logger.info(msg); + List list = sps.stringList; + assertMsgContains(list, 0, "Class path contains multiple SLF4J bindings."); + assertMsgContains(list, 1, "Found binding in"); + assertMsgContains(list, 2, "Found binding in"); + assertMsgContains(list, 3, "See http://www.slf4j.org/codes.html"); + assertMsgContains(list, 4, "Actual binding is of type ["); + } + + void assertMsgContains(List strList, int index, String msg) { + assertTrue(((String) strList.get(index)).contains(msg)); + } +} diff --git a/integration/src/test/java/org/slf4j/StringPrintStream.java b/integration/src/test/java/org/slf4j/StringPrintStream.java index 82b6852..200b745 100644 --- a/integration/src/test/java/org/slf4j/StringPrintStream.java +++ b/integration/src/test/java/org/slf4j/StringPrintStream.java @@ -1,56 +1,56 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.List; - -public class StringPrintStream extends PrintStream { - - public static final String LINE_SEP = System.getProperty("line.separator"); - PrintStream other; - List stringList = new ArrayList(); - - public StringPrintStream(PrintStream ps) { - super(ps); - other = ps; - } - - public void print(String s) { - other.print(s); - stringList.add(s); - } - - public void println(String s) { - other.println(s); - stringList.add(s); - } - - public void println(Object o) { - other.println(o); - stringList.add(o.toString()); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; + +public class StringPrintStream extends PrintStream { + + public static final String LINE_SEP = System.getProperty("line.separator"); + PrintStream other; + List stringList = new ArrayList(); + + public StringPrintStream(PrintStream ps) { + super(ps); + other = ps; + } + + public void print(String s) { + other.print(s); + stringList.add(s); + } + + public void println(String s) { + other.println(s); + stringList.add(s); + } + + public void println(Object o) { + other.println(o); + stringList.add(o.toString()); + } +} diff --git a/integration/src/test/java/org/slf4j/VersionMismatchAssertionTest.java b/integration/src/test/java/org/slf4j/VersionMismatchAssertionTest.java index 75ff0bd..c6d90e0 100644 --- a/integration/src/test/java/org/slf4j/VersionMismatchAssertionTest.java +++ b/integration/src/test/java/org/slf4j/VersionMismatchAssertionTest.java @@ -1,67 +1,67 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.io.PrintStream; -import java.util.Random; - -import junit.framework.TestCase; - -public class VersionMismatchAssertionTest extends TestCase { - - StringPrintStream sps = new StringPrintStream(System.err); - PrintStream old = System.err; - int diff = 1024 + new Random().nextInt(10000); - - public VersionMismatchAssertionTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } - - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } - - public void test() throws Exception { - Logger logger = LoggerFactory.getLogger(this.getClass()); - String msg = "hello world " + diff; - logger.info(msg); - - String s0 = (String) sps.stringList.get(0); - assertTrue(s0.matches("SLF4J: The requested version .* by your slf4j binding is not compatible with.*")); - - String s1 = (String) sps.stringList.get(1); - assertTrue(s1.contains(LoggerFactory.VERSION_MISMATCH)); - - String s2 = (String) sps.stringList.get(2); - assertTrue(s2.contains(msg)); - - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.io.PrintStream; +import java.util.Random; + +import junit.framework.TestCase; + +public class VersionMismatchAssertionTest extends TestCase { + + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); + + public VersionMismatchAssertionTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } + + protected void tearDown() throws Exception { + super.tearDown(); + System.setErr(old); + } + + public void test() throws Exception { + Logger logger = LoggerFactory.getLogger(this.getClass()); + String msg = "hello world " + diff; + logger.info(msg); + + String s0 = (String) sps.stringList.get(0); + assertTrue(s0.matches("SLF4J: The requested version .* by your slf4j binding is not compatible with.*")); + + String s1 = (String) sps.stringList.get(1); + assertTrue(s1.contains(LoggerFactory.VERSION_MISMATCH)); + + String s2 = (String) sps.stringList.get(2); + assertTrue(s2.contains(msg)); + + } +} diff --git a/integration/src/test/java/org/slf4j/issues/Issue324Test.java b/integration/src/test/java/org/slf4j/issues/Issue324Test.java index 4093f62..a7c2d7e 100644 --- a/integration/src/test/java/org/slf4j/issues/Issue324Test.java +++ b/integration/src/test/java/org/slf4j/issues/Issue324Test.java @@ -1,16 +1,16 @@ -package org.slf4j.issues; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import junit.framework.TestCase; - -public class Issue324Test extends TestCase { - - public void testLoggerCreationInPresenseOfSecurityManager() { - String currentDir = System.getProperty("user.dir"); - System.out.println("currentDir:" + currentDir); - Logger logger = LoggerFactory.getLogger(Issue324Test.class); - logger.debug("hello"); - } -} +package org.slf4j.issues; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import junit.framework.TestCase; + +public class Issue324Test extends TestCase { + + public void testLoggerCreationInPresenseOfSecurityManager() { + String currentDir = System.getProperty("user.dir"); + System.out.println("currentDir:" + currentDir); + Logger logger = LoggerFactory.getLogger(Issue324Test.class); + logger.debug("hello"); + } +} diff --git a/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java b/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java index 9cb70a6..920f228 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java +++ b/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java @@ -1,59 +1,59 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.test_osgi; - -import java.io.File; - -import junit.framework.TestCase; - -public class BundleTest extends TestCase { - - FrameworkErrorListener fel = new FrameworkErrorListener(); - CheckingBundleListener mbl = new CheckingBundleListener(); - - FelixHost felixHost = new FelixHost(fel, mbl); - - protected void setUp() throws Exception { - super.setUp(); - felixHost.doLaunch(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - felixHost.stop(); - } - - public void testSmoke() { - System.out.println("===========" + new File(".").getAbsolutePath()); - mbl.dumpAll(); - // check that the bundle was installed - assertTrue(mbl.exists("iBundle")); - if (fel.errorList.size() != 0) { - fel.dumpAll(); - } - // check that no errors occured - assertEquals(0, fel.errorList.size()); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.test_osgi; + +import java.io.File; + +import junit.framework.TestCase; + +public class BundleTest extends TestCase { + + FrameworkErrorListener fel = new FrameworkErrorListener(); + CheckingBundleListener mbl = new CheckingBundleListener(); + + FelixHost felixHost = new FelixHost(fel, mbl); + + protected void setUp() throws Exception { + super.setUp(); + felixHost.doLaunch(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + felixHost.stop(); + } + + public void testSmoke() { + System.out.println("===========" + new File(".").getAbsolutePath()); + mbl.dumpAll(); + // check that the bundle was installed + assertTrue(mbl.exists("iBundle")); + if (fel.errorList.size() != 0) { + fel.dumpAll(); + } + // check that no errors occured + assertEquals(0, fel.errorList.size()); + } +} diff --git a/integration/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java b/integration/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java index 2d2f573..ef4a034 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java +++ b/integration/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java @@ -1,66 +1,66 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.test_osgi; - -import java.util.ArrayList; -import java.util.List; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleEvent; -import org.osgi.framework.BundleListener; - -public class CheckingBundleListener implements BundleListener { - - List eventList = new ArrayList(); - - public void bundleChanged(BundleEvent be) { - eventList.add(be); - } - - private void dump(BundleEvent be) { - System.out.println("BE:" + ", source " + be.getSource() + ", bundle=" + be.getBundle() + ", type=" + be.getType()); - - } - - public void dumpAll() { - for (int i = 0; i < eventList.size(); i++) { - BundleEvent fe = (BundleEvent) eventList.get(i); - dump(fe); - } - } - - boolean exists(String bundleName) { - for (int i = 0; i < eventList.size(); i++) { - BundleEvent fe = (BundleEvent) eventList.get(i); - Bundle b = fe.getBundle(); - System.out.println("===[" + b + "]"); - if (bundleName.equals(b.getSymbolicName())) { - return true; - } - } - return false; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.test_osgi; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleEvent; +import org.osgi.framework.BundleListener; + +public class CheckingBundleListener implements BundleListener { + + List eventList = new ArrayList(); + + public void bundleChanged(BundleEvent be) { + eventList.add(be); + } + + private void dump(BundleEvent be) { + System.out.println("BE:" + ", source " + be.getSource() + ", bundle=" + be.getBundle() + ", type=" + be.getType()); + + } + + public void dumpAll() { + for (int i = 0; i < eventList.size(); i++) { + BundleEvent fe = (BundleEvent) eventList.get(i); + dump(fe); + } + } + + boolean exists(String bundleName) { + for (int i = 0; i < eventList.size(); i++) { + BundleEvent fe = (BundleEvent) eventList.get(i); + Bundle b = fe.getBundle(); + System.out.println("===[" + b + "]"); + if (bundleName.equals(b.getSymbolicName())) { + return true; + } + } + return false; + } + +} diff --git a/integration/src/test/java/org/slf4j/test_osgi/FelixHost.java b/integration/src/test/java/org/slf4j/test_osgi/FelixHost.java index adcd565..c2a655d 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/FelixHost.java +++ b/integration/src/test/java/org/slf4j/test_osgi/FelixHost.java @@ -1,119 +1,119 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.test_osgi; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.apache.felix.framework.Felix; -import org.apache.felix.framework.util.FelixConstants; -import org.apache.felix.framework.util.StringMap; -import org.apache.felix.main.AutoProcessor; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.Constants; - -/** - * Runs a hosted version of Felix for testing purposes. Any bundle errors are - * reported via the FrameworkListener passed to the constructor. - * - * @author Ceki Gülcü - */ -public class FelixHost { - - private Felix felix = null; - - Properties otherProps = new Properties(); - - final FrameworkErrorListener frameworkErrorListener; - final CheckingBundleListener myBundleListener; - - public FelixHost(FrameworkErrorListener frameworkErrorListener, CheckingBundleListener myBundleListener) { - this.frameworkErrorListener = frameworkErrorListener; - this.myBundleListener = myBundleListener; - } - - public void doLaunch() { - // Create a case-insensitive configuration property map. - StringMap configMap = new StringMap(); - // Configure the Felix instance to be embedded. - // configMap.put(FelixConstants.EMBEDDED_EXECUTION_PROP, "true"); - // Add core OSGi packages to be exported from the class path - // via the system bundle. - configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES, "org.osgi.framework; version=1.3.0," + "org.osgi.service.packageadmin; version=1.2.0," - + "org.osgi.service.startlevel; version=1.0.0," + "org.osgi.service.url; version=1.0.0"); - - configMap.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); - - // Explicitly specify the directory to use for caching bundles. - // configMap.put(BundleCache.CACHE_PROFILE_DIR_PROP, "cache"); - - try { - // Create host activator; - - List list = new ArrayList(); - - // list.add(new HostActivator()); - configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.xml.sax, org.xml.sax.helpers, javax.xml.parsers, javax.naming"); - configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list); - configMap.put("felix.log.level", "4"); - - // Now create an instance of the framework with - // our configuration properties and activator. - felix = new Felix(configMap); - felix.init(); - - // otherProps.put(Constants.FRAMEWORK_STORAGE, "bundles"); - - otherProps.put(AutoProcessor.AUTO_DEPLOY_DIR_PROPERTY, AutoProcessor.AUTO_DEPLOY_DIR_VALUE); - otherProps.put(AutoProcessor.AUTO_DEPLOY_ACTION_PROPERTY, AutoProcessor.AUTO_DEPLOY_START_VALUE + "," + AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE); - - BundleContext felixBudleContext = felix.getBundleContext(); - - AutoProcessor.process(otherProps, felixBudleContext); - // listen to errors - felixBudleContext.addFrameworkListener(frameworkErrorListener); - felixBudleContext.addBundleListener(myBundleListener); - // Now start Felix instance. - felix.start(); - System.out.println("felix started"); - - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public void stop() throws BundleException { - felix.stop(); - } - - public Bundle[] getInstalledBundles() { - // Use the system bundle activator to gain external - // access to the set of installed bundles. - return null;// m_activator.getBundles(); - } +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.test_osgi; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.apache.felix.framework.Felix; +import org.apache.felix.framework.util.FelixConstants; +import org.apache.felix.framework.util.StringMap; +import org.apache.felix.main.AutoProcessor; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.Constants; + +/** + * Runs a hosted version of Felix for testing purposes. Any bundle errors are + * reported via the FrameworkListener passed to the constructor. + * + * @author Ceki Gülcü + */ +public class FelixHost { + + private Felix felix = null; + + Properties otherProps = new Properties(); + + final FrameworkErrorListener frameworkErrorListener; + final CheckingBundleListener myBundleListener; + + public FelixHost(FrameworkErrorListener frameworkErrorListener, CheckingBundleListener myBundleListener) { + this.frameworkErrorListener = frameworkErrorListener; + this.myBundleListener = myBundleListener; + } + + public void doLaunch() { + // Create a case-insensitive configuration property map. + StringMap configMap = new StringMap(); + // Configure the Felix instance to be embedded. + // configMap.put(FelixConstants.EMBEDDED_EXECUTION_PROP, "true"); + // Add core OSGi packages to be exported from the class path + // via the system bundle. + configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES, "org.osgi.framework; version=1.3.0," + "org.osgi.service.packageadmin; version=1.2.0," + + "org.osgi.service.startlevel; version=1.0.0," + "org.osgi.service.url; version=1.0.0"); + + configMap.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); + + // Explicitly specify the directory to use for caching bundles. + // configMap.put(BundleCache.CACHE_PROFILE_DIR_PROP, "cache"); + + try { + // Create host activator; + + List list = new ArrayList(); + + // list.add(new HostActivator()); + configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.xml.sax, org.xml.sax.helpers, javax.xml.parsers, javax.naming"); + configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list); + configMap.put("felix.log.level", "4"); + + // Now create an instance of the framework with + // our configuration properties and activator. + felix = new Felix(configMap); + felix.init(); + + // otherProps.put(Constants.FRAMEWORK_STORAGE, "bundles"); + + otherProps.put(AutoProcessor.AUTO_DEPLOY_DIR_PROPERTY, AutoProcessor.AUTO_DEPLOY_DIR_VALUE); + otherProps.put(AutoProcessor.AUTO_DEPLOY_ACTION_PROPERTY, AutoProcessor.AUTO_DEPLOY_START_VALUE + "," + AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE); + + BundleContext felixBudleContext = felix.getBundleContext(); + + AutoProcessor.process(otherProps, felixBudleContext); + // listen to errors + felixBudleContext.addFrameworkListener(frameworkErrorListener); + felixBudleContext.addBundleListener(myBundleListener); + // Now start Felix instance. + felix.start(); + System.out.println("felix started"); + + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public void stop() throws BundleException { + felix.stop(); + } + + public Bundle[] getInstalledBundles() { + // Use the system bundle activator to gain external + // access to the set of installed bundles. + return null;// m_activator.getBundles(); + } }diff --git a/integration/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java b/integration/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java index 9b66dd4..2f9458d 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java +++ b/integration/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java @@ -1,62 +1,62 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.test_osgi; - -import java.util.ArrayList; -import java.util.List; - -import org.osgi.framework.FrameworkEvent; -import org.osgi.framework.FrameworkListener; - -public class FrameworkErrorListener implements FrameworkListener { - - public List errorList = new ArrayList(); - - public void frameworkEvent(FrameworkEvent fe) { - if (fe.getType() == FrameworkEvent.ERROR) { - errorList.add(fe); - - } - } - - private void dump(FrameworkEvent fe) { - Throwable t = fe.getThrowable(); - String tString = null; - if (t != null) { - tString = t.toString(); - } - System.out.println("Framework ERROR:" + ", source " + fe.getSource() + ", bundle=" + fe.getBundle() + ", ex=" + tString); - if (t != null) { - t.printStackTrace(); - } - } - - public void dumpAll() { - for (int i = 0; i < errorList.size(); i++) { - FrameworkEvent fe = (FrameworkEvent) errorList.get(i); - dump(fe); - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.test_osgi; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.framework.FrameworkEvent; +import org.osgi.framework.FrameworkListener; + +public class FrameworkErrorListener implements FrameworkListener { + + public List errorList = new ArrayList(); + + public void frameworkEvent(FrameworkEvent fe) { + if (fe.getType() == FrameworkEvent.ERROR) { + errorList.add(fe); + + } + } + + private void dump(FrameworkEvent fe) { + Throwable t = fe.getThrowable(); + String tString = null; + if (t != null) { + tString = t.toString(); + } + System.out.println("Framework ERROR:" + ", source " + fe.getSource() + ", bundle=" + fe.getBundle() + ", ex=" + tString); + if (t != null) { + t.printStackTrace(); + } + } + + public void dumpAll() { + for (int i = 0; i < errorList.size(); i++) { + FrameworkEvent fe = (FrameworkEvent) errorList.get(i); + dump(fe); + } + } +} diff --git a/jcl-over-slf4j/LICENSE.txt b/jcl-over-slf4j/LICENSE.txt new file mode 100644 index 0000000..2bb9ad2 --- /dev/null +++ b/jcl-over-slf4j/LICENSE.txt @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/jcl-over-slf4j/pom.xml b/jcl-over-slf4j/pom.xml old file mode 100644 new file mode 100755 index 0c94e46..7173c01 100755 --- a/jcl-over-slf4j/pom.xml +++ b/jcl-over-slf4j/pom.xml @@ -1,31 +1,32 @@ - - - - - org.slf4j - slf4j-parent - 1.7.25 - - - 4.0.0 - - jcl-over-slf4j - jar - JCL 1.2 implemented over SLF4J - JCL 1.2 implemented over SLF4J - http://www.slf4j.org - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-jdk14 - test - - - - \ No newline at end of file + + + + + org.slf4j + slf4j-parent + 1.7.26 + + + 4.0.0 + + jcl-over-slf4j + jar + JCL 1.2 implemented over SLF4J + JCL 1.2 implemented over SLF4J + http://www.slf4j.org + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-jdk14 + test + + + + + diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/Log.java b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/Log.java index 61b738d..779c4d9 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/Log.java +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/Log.java @@ -1,217 +1,217 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging; - -/** - *

A simple logging interface abstracting logging APIs. In order to be - * instantiated successfully by {@link LogFactory}, classes that implement - * this interface must have a constructor that takes a single String - * parameter representing the "name" of this Log.

- * - *

The six logging levels used by Log are (in order): - *

    - *
  1. trace (the least serious)
  2. - *
  3. debug
  4. - *
  5. info
  6. - *
  7. warn
  8. - *
  9. error
  10. - *
  11. fatal (the most serious)
  12. - *
- * The mapping of these log levels to the concepts used by the underlying - * logging system is implementation dependent. - * The implementation should ensure, though, that this ordering behaves - * as expected.

- * - *

Performance is often a logging concern. - * By examining the appropriate property, - * a component can avoid expensive operations (producing information - * to be logged).

- * - *

For example, - *

- *    if (log.isDebugEnabled()) {
- *        ... do something expensive ...
- *        log.debug(theResult);
- *    }
- * 
- *

- * - *

Configuration of the underlying logging system will generally be done - * external to the Logging APIs, through whatever mechanism is supported by - * that system.

- * - *

Please note that this interface is identical to that found in JCL 1.1.1.

- * - * @author Scott Sanders - * @author Rod Waldhoff - * @version $Id: Log.java,v 1.19 2004/06/06 21:16:04 rdonkin Exp $ - */ -public interface Log { - - // ----------------------------------------------------- Logging Properties - - /** - *

Is debug logging currently enabled?

- * - *

Call this method to prevent having to perform expensive operations - * (for example, String concatenation) - * when the log level is more than debug.

- */ - public boolean isDebugEnabled(); - - /** - *

Is error logging currently enabled?

- * - *

Call this method to prevent having to perform expensive operations - * (for example, String concatenation) - * when the log level is more than error.

- */ - public boolean isErrorEnabled(); - - /** - *

Is fatal logging currently enabled?

- * - *

Call this method to prevent having to perform expensive operations - * (for example, String concatenation) - * when the log level is more than fatal.

- */ - public boolean isFatalEnabled(); - - /** - *

Is info logging currently enabled?

- * - *

Call this method to prevent having to perform expensive operations - * (for example, String concatenation) - * when the log level is more than info.

- * - * @return true if info enabled, false otherwise - */ - public boolean isInfoEnabled(); - - /** - *

Is trace logging currently enabled?

- * - *

Call this method to prevent having to perform expensive operations - * (for example, String concatenation) - * when the log level is more than trace.

- * - * @return true if trace enabled, false otherwise - */ - public boolean isTraceEnabled(); - - /** - *

Is warn logging currently enabled?

- * - *

Call this method to prevent having to perform expensive operations - * (for example, String concatenation) - * when the log level is more than warn.

- */ - public boolean isWarnEnabled(); - - // -------------------------------------------------------- Logging Methods - - /** - *

Log a message with trace log level.

- * - * @param message log this message - */ - public void trace(Object message); - - /** - *

Log an error with trace log level.

- * - * @param message log this message - * @param t log this cause - */ - public void trace(Object message, Throwable t); - - /** - *

Log a message with debug log level.

- * - * @param message log this message - */ - public void debug(Object message); - - /** - *

Log an error with debug log level.

- * - * @param message log this message - * @param t log this cause - */ - public void debug(Object message, Throwable t); - - /** - *

Log a message with info log level.

- * - * @param message log this message - */ - public void info(Object message); - - /** - *

Log an error with info log level.

- * - * @param message log this message - * @param t log this cause - */ - public void info(Object message, Throwable t); - - /** - *

Log a message with warn log level.

- * - * @param message log this message - */ - public void warn(Object message); - - /** - *

Log an error with warn log level.

- * - * @param message log this message - * @param t log this cause - */ - public void warn(Object message, Throwable t); - - /** - *

Log a message with error log level.

- * - * @param message log this message - */ - public void error(Object message); - - /** - *

Log an error with error log level.

- * - * @param message log this message - * @param t log this cause - */ - public void error(Object message, Throwable t); - - /** - *

Log a message with fatal log level.

- * - * @param message log this message - */ - public void fatal(Object message); - - /** - *

Log an error with fatal log level.

- * - * @param message log this message - * @param t log this cause - */ - public void fatal(Object message, Throwable t); - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.logging; + +/** + *

A simple logging interface abstracting logging APIs. In order to be + * instantiated successfully by {@link LogFactory}, classes that implement + * this interface must have a constructor that takes a single String + * parameter representing the "name" of this Log.

+ * + *

The six logging levels used by Log are (in order): + *

    + *
  1. trace (the least serious)
  2. + *
  3. debug
  4. + *
  5. info
  6. + *
  7. warn
  8. + *
  9. error
  10. + *
  11. fatal (the most serious)
  12. + *
+ * The mapping of these log levels to the concepts used by the underlying + * logging system is implementation dependent. + * The implementation should ensure, though, that this ordering behaves + * as expected.

+ * + *

Performance is often a logging concern. + * By examining the appropriate property, + * a component can avoid expensive operations (producing information + * to be logged).

+ * + *

For example, + *

+ *    if (log.isDebugEnabled()) {
+ *        ... do something expensive ...
+ *        log.debug(theResult);
+ *    }
+ * 
+ *

+ * + *

Configuration of the underlying logging system will generally be done + * external to the Logging APIs, through whatever mechanism is supported by + * that system.

+ * + *

Please note that this interface is identical to that found in JCL 1.1.1.

+ * + * @author Scott Sanders + * @author Rod Waldhoff + * @version $Id: Log.java,v 1.19 2004/06/06 21:16:04 rdonkin Exp $ + */ +public interface Log { + + // ----------------------------------------------------- Logging Properties + + /** + *

Is debug logging currently enabled?

+ * + *

Call this method to prevent having to perform expensive operations + * (for example, String concatenation) + * when the log level is more than debug.

+ */ + public boolean isDebugEnabled(); + + /** + *

Is error logging currently enabled?

+ * + *

Call this method to prevent having to perform expensive operations + * (for example, String concatenation) + * when the log level is more than error.

+ */ + public boolean isErrorEnabled(); + + /** + *

Is fatal logging currently enabled?

+ * + *

Call this method to prevent having to perform expensive operations + * (for example, String concatenation) + * when the log level is more than fatal.

+ */ + public boolean isFatalEnabled(); + + /** + *

Is info logging currently enabled?

+ * + *

Call this method to prevent having to perform expensive operations + * (for example, String concatenation) + * when the log level is more than info.

+ * + * @return true if info enabled, false otherwise + */ + public boolean isInfoEnabled(); + + /** + *

Is trace logging currently enabled?

+ * + *

Call this method to prevent having to perform expensive operations + * (for example, String concatenation) + * when the log level is more than trace.

+ * + * @return true if trace enabled, false otherwise + */ + public boolean isTraceEnabled(); + + /** + *

Is warn logging currently enabled?

+ * + *

Call this method to prevent having to perform expensive operations + * (for example, String concatenation) + * when the log level is more than warn.

+ */ + public boolean isWarnEnabled(); + + // -------------------------------------------------------- Logging Methods + + /** + *

Log a message with trace log level.

+ * + * @param message log this message + */ + public void trace(Object message); + + /** + *

Log an error with trace log level.

+ * + * @param message log this message + * @param t log this cause + */ + public void trace(Object message, Throwable t); + + /** + *

Log a message with debug log level.

+ * + * @param message log this message + */ + public void debug(Object message); + + /** + *

Log an error with debug log level.

+ * + * @param message log this message + * @param t log this cause + */ + public void debug(Object message, Throwable t); + + /** + *

Log a message with info log level.

+ * + * @param message log this message + */ + public void info(Object message); + + /** + *

Log an error with info log level.

+ * + * @param message log this message + * @param t log this cause + */ + public void info(Object message, Throwable t); + + /** + *

Log a message with warn log level.

+ * + * @param message log this message + */ + public void warn(Object message); + + /** + *

Log an error with warn log level.

+ * + * @param message log this message + * @param t log this cause + */ + public void warn(Object message, Throwable t); + + /** + *

Log a message with error log level.

+ * + * @param message log this message + */ + public void error(Object message); + + /** + *

Log an error with error log level.

+ * + * @param message log this message + * @param t log this cause + */ + public void error(Object message, Throwable t); + + /** + *

Log a message with fatal log level.

+ * + * @param message log this message + */ + public void fatal(Object message); + + /** + *

Log an error with fatal log level.

+ * + * @param message log this message + * @param t log this cause + */ + public void fatal(Object message, Throwable t); + +} diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/LogConfigurationException.java b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/LogConfigurationException.java index c61bf4a..668f413 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/LogConfigurationException.java +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/LogConfigurationException.java @@ -1,93 +1,93 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging; - -/** - *

- * An exception that is thrown only if a suitable LogFactory or - * Log instance cannot be created by the corresponding factory - * methods. - *

- * - *

- * In this version of JCL, this exception will never be thrown in practice. - * However, it is included here to ensure total compile time and run time - * compatibility with the original JCL 1.0.4. - * - * @author Craig R. McClanahan - */ - -public class LogConfigurationException extends RuntimeException { - - private static final long serialVersionUID = 8486587136871052495L; - - /** - * Construct a new exception with null as its detail message. - */ - public LogConfigurationException() { - super(); - } - - /** - * Construct a new exception with the specified detail message. - * - * @param message - * The detail message - */ - public LogConfigurationException(String message) { - super(message); - } - - /** - * Construct a new exception with the specified cause and a derived detail - * message. - * - * @param cause - * The underlying cause - */ - public LogConfigurationException(Throwable cause) { - - this((cause == null) ? null : cause.toString(), cause); - - } - - /** - * Construct a new exception with the specified detail message and cause. - * - * @param message - * The detail message - * @param cause - * The underlying cause - */ - public LogConfigurationException(String message, Throwable cause) { - super(message + " (Caused by " + cause + ")"); - this.cause = cause; // Two-argument version requires JDK 1.4 or later - } - - /** - * The underlying cause of this exception. - */ - protected Throwable cause = null; - - /** - * Return the underlying cause of this exception (if any). - */ - public Throwable getCause() { - return (this.cause); - } - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.logging; + +/** + *

+ * An exception that is thrown only if a suitable LogFactory or + * Log instance cannot be created by the corresponding factory + * methods. + *

+ * + *

+ * In this version of JCL, this exception will never be thrown in practice. + * However, it is included here to ensure total compile time and run time + * compatibility with the original JCL 1.0.4. + * + * @author Craig R. McClanahan + */ + +public class LogConfigurationException extends RuntimeException { + + private static final long serialVersionUID = 8486587136871052495L; + + /** + * Construct a new exception with null as its detail message. + */ + public LogConfigurationException() { + super(); + } + + /** + * Construct a new exception with the specified detail message. + * + * @param message + * The detail message + */ + public LogConfigurationException(String message) { + super(message); + } + + /** + * Construct a new exception with the specified cause and a derived detail + * message. + * + * @param cause + * The underlying cause + */ + public LogConfigurationException(Throwable cause) { + + this((cause == null) ? null : cause.toString(), cause); + + } + + /** + * Construct a new exception with the specified detail message and cause. + * + * @param message + * The detail message + * @param cause + * The underlying cause + */ + public LogConfigurationException(String message, Throwable cause) { + super(message + " (Caused by " + cause + ")"); + this.cause = cause; // Two-argument version requires JDK 1.4 or later + } + + /** + * The underlying cause of this exception. + */ + protected Throwable cause = null; + + /** + * Return the underlying cause of this exception (if any). + */ + public Throwable getCause() { + return (this.cause); + } + +} diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/LogFactory.java b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/LogFactory.java index 5745d3e..313adef 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/LogFactory.java +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/LogFactory.java @@ -1,408 +1,408 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging; - -import java.util.Hashtable; - -import org.apache.commons.logging.impl.SLF4JLogFactory; - -/** - *

- * Factory for creating {@link Log} instances, which always delegates to an - * instance of {@link SLF4JLogFactory}. - * - *

- * - * @author Craig R. McClanahan - * @author Costin Manolache - * @author Richard A. Sitze - * @author Ceki Gülcü - */ - -@SuppressWarnings("rawtypes") -public abstract class LogFactory { - - static String UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J = "http://www.slf4j.org/codes.html#unsupported_operation_in_jcl_over_slf4j"; - - static LogFactory logFactory = new SLF4JLogFactory(); - - /** - * The name (priority) of the key in the config file used to - * specify the priority of that particular config file. The associated value - * is a floating-point number; higher values take priority over lower values. - * - *

- * This property is not used but preserved here for compatibility. - */ - public static final String PRIORITY_KEY = "priority"; - - /** - * The name (use_tccl) of the key in the config file used to - * specify whether logging classes should be loaded via the thread context - * class loader (TCCL), or not. By default, the TCCL is used. - * - *

- * This property is not used but preserved here for compatibility. - */ - public static final String TCCL_KEY = "use_tccl"; - - /** - * The name of the property used to identify the LogFactory implementation - * class name. - *

- * This property is not used but preserved here for compatibility. - */ - public static final String FACTORY_PROPERTY = "org.apache.commons.logging.LogFactory"; - - /** - * The fully qualified class name of the fallback LogFactory - * implementation class to use, if no other can be found. - * - *

- * This property is not used but preserved here for compatibility. - */ - public static final String FACTORY_DEFAULT = "org.apache.commons.logging.impl.SLF4JLogFactory"; - - /** - * The name of the properties file to search for. - *

- * This property is not used but preserved here for compatibility. - */ - public static final String FACTORY_PROPERTIES = "commons-logging.properties"; - - /** - * JDK1.3+ - * 'Service Provider' specification. - *

- * This property is not used but preserved here for compatibility. - */ - protected static final String SERVICE_ID = "META-INF/services/org.apache.commons.logging.LogFactory"; - - /** - * The name (org.apache.commons.logging.diagnostics.dest) of - * the property used to enable internal commons-logging diagnostic output, in - * order to get information on what logging implementations are being - * discovered, what classloaders they are loaded through, etc. - * - *

- * This property is not used but preserved here for compatibility. - */ - public static final String DIAGNOSTICS_DEST_PROPERTY = "org.apache.commons.logging.diagnostics.dest"; - - /** - *

- * Setting this system property value allows the Hashtable used - * to store classloaders to be substituted by an alternative implementation. - *

- * This property is not used but preserved here for compatibility. - */ - public static final String HASHTABLE_IMPLEMENTATION_PROPERTY = "org.apache.commons.logging.LogFactory.HashtableImpl"; - - /** - * The previously constructed LogFactory instances, keyed by - * the ClassLoader with which it was created. - * - *

- * This property is not used but preserved here for compatibility. - */ - protected static Hashtable factories = null; - - /** - *

- * This property is not used but preserved here for compatibility. - */ - protected static LogFactory nullClassLoaderFactory = null; - - /** - * Protected constructor that is not available for public use. - */ - protected LogFactory() { - } - - // --------------------------------------------------------- Public Methods - - /** - * Return the configuration attribute with the specified name (if any), or - * null if there is no such attribute. - * - * @param name Name of the attribute to return - * @return configuration attribute - */ - public abstract Object getAttribute(String name); - - /** - * Return an array containing the names of all currently defined configuration - * attributes. If there are no such attributes, a zero length array is - * returned. - * - * @return names of all currently defined configuration attributes - */ - public abstract String[] getAttributeNames(); - - /** - * Convenience method to derive a name from the specified class and call - * getInstance(String) with it. - * - * @param clazz - * Class for which a suitable Log name will be derived - * - * @exception LogConfigurationException - * if a suitable Log instance cannot be - * returned - */ - public abstract Log getInstance(Class clazz) throws LogConfigurationException; - - /** - *

- * Construct (if necessary) and return a Log instance, using - * the factory's current set of configuration attributes. - *

- * - *

- * NOTE - Depending upon the implementation of the - * LogFactory you are using, the Log instance - * you are returned may or may not be local to the current application, and - * may or may not be returned again on a subsequent call with the same name - * argument. - *

- * - * @param name - * Logical name of the Log instance to be - * returned (the meaning of this name is only known to the - * underlying logging implementation that is being wrapped) - * - * @exception LogConfigurationException - * if a suitable Log instance cannot be - * returned - */ - public abstract Log getInstance(String name) throws LogConfigurationException; - - /** - * Release any internal references to previously created {@link Log}instances - * returned by this factory. This is useful in environments like servlet - * containers, which implement application reloading by throwing away a - * ClassLoader. Dangling references to objects in that class loader would - * prevent garbage collection. - */ - public abstract void release(); - - /** - * Remove any configuration attribute associated with the specified name. If - * there is no such attribute, no action is taken. - * - * @param name - * Name of the attribute to remove - */ - public abstract void removeAttribute(String name); - - /** - * Set the configuration attribute with the specified name. Calling this with - * a null value is equivalent to calling - * removeAttribute(name). - * - * @param name - * Name of the attribute to set - * @param value - * Value of the attribute to set, or null to - * remove any setting for this attribute - */ - public abstract void setAttribute(String name, Object value); - - // --------------------------------------------------------- Static Methods - - /** - *

- * Construct (if necessary) and return a LogFactory instance, - * using the following ordered lookup procedure to determine the name of the - * implementation class to be loaded. - *

- *
    - *
  • The org.apache.commons.logging.LogFactory system - * property.
  • - *
  • The JDK 1.3 Service Discovery mechanism
  • - *
  • Use the properties file commons-logging.properties - * file, if found in the class path of this class. The configuration file is - * in standard java.util.Properties format and contains the - * fully qualified name of the implementation class with the key being the - * system property defined above.
  • - *
  • Fall back to a default implementation class ( - * org.apache.commons.logging.impl.SLF4FLogFactory).
  • - *
- * - *

- * NOTE- If the properties file method of identifying the - * LogFactory implementation class is utilized, all of the - * properties defined in this file will be set as configuration attributes on - * the corresponding LogFactory instance. - *

- * - * @exception LogConfigurationException - * if the implementation class is not available or cannot - * be instantiated. - */ - public static LogFactory getFactory() throws LogConfigurationException { - return logFactory; - } - - /** - * Convenience method to return a named logger, without the application having - * to care about factories. - * - * @param clazz - * Class from which a log name will be derived - * - * @exception LogConfigurationException - * if a suitable Log instance cannot be - * returned - */ - public static Log getLog(Class clazz) throws LogConfigurationException { - return (getFactory().getInstance(clazz)); - } - - /** - * Convenience method to return a named logger, without the application having - * to care about factories. - * - * @param name - * Logical name of the Log instance to be - * returned (the meaning of this name is only known to the - * underlying logging implementation that is being wrapped) - * - * @exception LogConfigurationException - * if a suitable Log instance cannot be - * returned - */ - public static Log getLog(String name) throws LogConfigurationException { - return (getFactory().getInstance(name)); - } - - /** - * Release any internal references to previously created {@link LogFactory} - * instances that have been associated with the specified class loader (if - * any), after calling the instance method release() on each of - * them. - * - * @param classLoader - * ClassLoader for which to release the LogFactory - */ - public static void release(ClassLoader classLoader) { - // since SLF4J based JCL does not make use of classloaders, there is nothing - // to do here - } - - /** - * Release any internal references to previously created {@link LogFactory} - * instances, after calling the instance method release() on - * each of them. This is useful in environments like servlet containers, which - * implement application reloading by throwing away a ClassLoader. Dangling - * references to objects in that class loader would prevent garbage - * collection. - */ - public static void releaseAll() { - // since SLF4J based JCL does not make use of classloaders, there is nothing - // to do here - } - - /** - * Returns a string that uniquely identifies the specified object, including - * its class. - *

- * The returned string is of form "classname@hashcode", i.e. is the same as the - * return value of the Object.toString() method, but works even when the - * specified object's class has overridden the toString method. - * - * @param o - * may be null. - * @return a string of form classname@hashcode, or "null" if param o is null. - * @since 1.1 - */ - public static String objectId(Object o) { - if (o == null) { - return "null"; - } else { - return o.getClass().getName() + "@" + System.identityHashCode(o); - } - } - - // protected methods which were added in JCL 1.1. These are not used - // by SLF4JLogFactory - - /** - * This method exists to ensure signature compatibility. - */ - protected static Object createFactory(String factoryClass, ClassLoader classLoader) { - throw new UnsupportedOperationException("Operation [factoryClass] is not supported in jcl-over-slf4j. See also " - + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); - } - - /** - * This method exists to ensure signature compatibility. - */ - protected static ClassLoader directGetContextClassLoader() { - throw new UnsupportedOperationException("Operation [directGetContextClassLoader] is not supported in jcl-over-slf4j. See also " - + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); - } - - /** - * This method exists to ensure signature compatibility. - */ - protected static ClassLoader getContextClassLoader() throws LogConfigurationException { - throw new UnsupportedOperationException("Operation [getContextClassLoader] is not supported in jcl-over-slf4j. See also " - + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); - } - - /** - * This method exists to ensure signature compatibility. - */ - protected static ClassLoader getClassLoader(Class clazz) { - throw new UnsupportedOperationException("Operation [getClassLoader] is not supported in jcl-over-slf4j. See also " - + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); - } - - /** - * This method exists to ensure signature compatibility. - */ - protected static boolean isDiagnosticsEnabled() { - throw new UnsupportedOperationException("Operation [isDiagnosticsEnabled] is not supported in jcl-over-slf4j. See also " - + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); - } - - /** - * This method exists to ensure signature compatibility. - */ - protected static void logRawDiagnostic(String msg) { - throw new UnsupportedOperationException("Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also " - + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); - } - - /** - * This method exists to ensure signature compatibility. - */ - protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader, final ClassLoader contextClassLoader) { - throw new UnsupportedOperationException("Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also " - + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); - } - - /** - * This method exists to ensure signature compatibility. - */ - protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader) { - throw new UnsupportedOperationException("Operation [newFactory] is not supported in jcl-over-slf4j. See also " - + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); - } - +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.logging; + +import java.util.Hashtable; + +import org.apache.commons.logging.impl.SLF4JLogFactory; + +/** + *

+ * Factory for creating {@link Log} instances, which always delegates to an + * instance of {@link SLF4JLogFactory}. + * + *

+ * + * @author Craig R. McClanahan + * @author Costin Manolache + * @author Richard A. Sitze + * @author Ceki Gülcü + */ + +@SuppressWarnings("rawtypes") +public abstract class LogFactory { + + static String UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J = "http://www.slf4j.org/codes.html#unsupported_operation_in_jcl_over_slf4j"; + + static LogFactory logFactory = new SLF4JLogFactory(); + + /** + * The name (priority) of the key in the config file used to + * specify the priority of that particular config file. The associated value + * is a floating-point number; higher values take priority over lower values. + * + *

+ * This property is not used but preserved here for compatibility. + */ + public static final String PRIORITY_KEY = "priority"; + + /** + * The name (use_tccl) of the key in the config file used to + * specify whether logging classes should be loaded via the thread context + * class loader (TCCL), or not. By default, the TCCL is used. + * + *

+ * This property is not used but preserved here for compatibility. + */ + public static final String TCCL_KEY = "use_tccl"; + + /** + * The name of the property used to identify the LogFactory implementation + * class name. + *

+ * This property is not used but preserved here for compatibility. + */ + public static final String FACTORY_PROPERTY = "org.apache.commons.logging.LogFactory"; + + /** + * The fully qualified class name of the fallback LogFactory + * implementation class to use, if no other can be found. + * + *

+ * This property is not used but preserved here for compatibility. + */ + public static final String FACTORY_DEFAULT = "org.apache.commons.logging.impl.SLF4JLogFactory"; + + /** + * The name of the properties file to search for. + *

+ * This property is not used but preserved here for compatibility. + */ + public static final String FACTORY_PROPERTIES = "commons-logging.properties"; + + /** + * JDK1.3+ + * 'Service Provider' specification. + *

+ * This property is not used but preserved here for compatibility. + */ + protected static final String SERVICE_ID = "META-INF/services/org.apache.commons.logging.LogFactory"; + + /** + * The name (org.apache.commons.logging.diagnostics.dest) of + * the property used to enable internal commons-logging diagnostic output, in + * order to get information on what logging implementations are being + * discovered, what classloaders they are loaded through, etc. + * + *

+ * This property is not used but preserved here for compatibility. + */ + public static final String DIAGNOSTICS_DEST_PROPERTY = "org.apache.commons.logging.diagnostics.dest"; + + /** + *

+ * Setting this system property value allows the Hashtable used + * to store classloaders to be substituted by an alternative implementation. + *

+ * This property is not used but preserved here for compatibility. + */ + public static final String HASHTABLE_IMPLEMENTATION_PROPERTY = "org.apache.commons.logging.LogFactory.HashtableImpl"; + + /** + * The previously constructed LogFactory instances, keyed by + * the ClassLoader with which it was created. + * + *

+ * This property is not used but preserved here for compatibility. + */ + protected static Hashtable factories = null; + + /** + *

+ * This property is not used but preserved here for compatibility. + */ + protected static LogFactory nullClassLoaderFactory = null; + + /** + * Protected constructor that is not available for public use. + */ + protected LogFactory() { + } + + // --------------------------------------------------------- Public Methods + + /** + * Return the configuration attribute with the specified name (if any), or + * null if there is no such attribute. + * + * @param name Name of the attribute to return + * @return configuration attribute + */ + public abstract Object getAttribute(String name); + + /** + * Return an array containing the names of all currently defined configuration + * attributes. If there are no such attributes, a zero length array is + * returned. + * + * @return names of all currently defined configuration attributes + */ + public abstract String[] getAttributeNames(); + + /** + * Convenience method to derive a name from the specified class and call + * getInstance(String) with it. + * + * @param clazz + * Class for which a suitable Log name will be derived + * + * @exception LogConfigurationException + * if a suitable Log instance cannot be + * returned + */ + public abstract Log getInstance(Class clazz) throws LogConfigurationException; + + /** + *

+ * Construct (if necessary) and return a Log instance, using + * the factory's current set of configuration attributes. + *

+ * + *

+ * NOTE - Depending upon the implementation of the + * LogFactory you are using, the Log instance + * you are returned may or may not be local to the current application, and + * may or may not be returned again on a subsequent call with the same name + * argument. + *

+ * + * @param name + * Logical name of the Log instance to be + * returned (the meaning of this name is only known to the + * underlying logging implementation that is being wrapped) + * + * @exception LogConfigurationException + * if a suitable Log instance cannot be + * returned + */ + public abstract Log getInstance(String name) throws LogConfigurationException; + + /** + * Release any internal references to previously created {@link Log}instances + * returned by this factory. This is useful in environments like servlet + * containers, which implement application reloading by throwing away a + * ClassLoader. Dangling references to objects in that class loader would + * prevent garbage collection. + */ + public abstract void release(); + + /** + * Remove any configuration attribute associated with the specified name. If + * there is no such attribute, no action is taken. + * + * @param name + * Name of the attribute to remove + */ + public abstract void removeAttribute(String name); + + /** + * Set the configuration attribute with the specified name. Calling this with + * a null value is equivalent to calling + * removeAttribute(name). + * + * @param name + * Name of the attribute to set + * @param value + * Value of the attribute to set, or null to + * remove any setting for this attribute + */ + public abstract void setAttribute(String name, Object value); + + // --------------------------------------------------------- Static Methods + + /** + *

+ * Construct (if necessary) and return a LogFactory instance, + * using the following ordered lookup procedure to determine the name of the + * implementation class to be loaded. + *

+ *
    + *
  • The org.apache.commons.logging.LogFactory system + * property.
  • + *
  • The JDK 1.3 Service Discovery mechanism
  • + *
  • Use the properties file commons-logging.properties + * file, if found in the class path of this class. The configuration file is + * in standard java.util.Properties format and contains the + * fully qualified name of the implementation class with the key being the + * system property defined above.
  • + *
  • Fall back to a default implementation class ( + * org.apache.commons.logging.impl.SLF4FLogFactory).
  • + *
+ * + *

+ * NOTE- If the properties file method of identifying the + * LogFactory implementation class is utilized, all of the + * properties defined in this file will be set as configuration attributes on + * the corresponding LogFactory instance. + *

+ * + * @exception LogConfigurationException + * if the implementation class is not available or cannot + * be instantiated. + */ + public static LogFactory getFactory() throws LogConfigurationException { + return logFactory; + } + + /** + * Convenience method to return a named logger, without the application having + * to care about factories. + * + * @param clazz + * Class from which a log name will be derived + * + * @exception LogConfigurationException + * if a suitable Log instance cannot be + * returned + */ + public static Log getLog(Class clazz) throws LogConfigurationException { + return (getFactory().getInstance(clazz)); + } + + /** + * Convenience method to return a named logger, without the application having + * to care about factories. + * + * @param name + * Logical name of the Log instance to be + * returned (the meaning of this name is only known to the + * underlying logging implementation that is being wrapped) + * + * @exception LogConfigurationException + * if a suitable Log instance cannot be + * returned + */ + public static Log getLog(String name) throws LogConfigurationException { + return (getFactory().getInstance(name)); + } + + /** + * Release any internal references to previously created {@link LogFactory} + * instances that have been associated with the specified class loader (if + * any), after calling the instance method release() on each of + * them. + * + * @param classLoader + * ClassLoader for which to release the LogFactory + */ + public static void release(ClassLoader classLoader) { + // since SLF4J based JCL does not make use of classloaders, there is nothing + // to do here + } + + /** + * Release any internal references to previously created {@link LogFactory} + * instances, after calling the instance method release() on + * each of them. This is useful in environments like servlet containers, which + * implement application reloading by throwing away a ClassLoader. Dangling + * references to objects in that class loader would prevent garbage + * collection. + */ + public static void releaseAll() { + // since SLF4J based JCL does not make use of classloaders, there is nothing + // to do here + } + + /** + * Returns a string that uniquely identifies the specified object, including + * its class. + *

+ * The returned string is of form "classname@hashcode", i.e. is the same as the + * return value of the Object.toString() method, but works even when the + * specified object's class has overridden the toString method. + * + * @param o + * may be null. + * @return a string of form classname@hashcode, or "null" if param o is null. + * @since 1.1 + */ + public static String objectId(Object o) { + if (o == null) { + return "null"; + } else { + return o.getClass().getName() + "@" + System.identityHashCode(o); + } + } + + // protected methods which were added in JCL 1.1. These are not used + // by SLF4JLogFactory + + /** + * This method exists to ensure signature compatibility. + */ + protected static Object createFactory(String factoryClass, ClassLoader classLoader) { + throw new UnsupportedOperationException("Operation [factoryClass] is not supported in jcl-over-slf4j. See also " + + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); + } + + /** + * This method exists to ensure signature compatibility. + */ + protected static ClassLoader directGetContextClassLoader() { + throw new UnsupportedOperationException("Operation [directGetContextClassLoader] is not supported in jcl-over-slf4j. See also " + + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); + } + + /** + * This method exists to ensure signature compatibility. + */ + protected static ClassLoader getContextClassLoader() throws LogConfigurationException { + throw new UnsupportedOperationException("Operation [getContextClassLoader] is not supported in jcl-over-slf4j. See also " + + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); + } + + /** + * This method exists to ensure signature compatibility. + */ + protected static ClassLoader getClassLoader(Class clazz) { + throw new UnsupportedOperationException("Operation [getClassLoader] is not supported in jcl-over-slf4j. See also " + + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); + } + + /** + * This method exists to ensure signature compatibility. + */ + protected static boolean isDiagnosticsEnabled() { + throw new UnsupportedOperationException("Operation [isDiagnosticsEnabled] is not supported in jcl-over-slf4j. See also " + + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); + } + + /** + * This method exists to ensure signature compatibility. + */ + protected static void logRawDiagnostic(String msg) { + throw new UnsupportedOperationException("Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also " + + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); + } + + /** + * This method exists to ensure signature compatibility. + */ + protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader, final ClassLoader contextClassLoader) { + throw new UnsupportedOperationException("Operation [logRawDiagnostic] is not supported in jcl-over-slf4j. See also " + + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); + } + + /** + * This method exists to ensure signature compatibility. + */ + protected static LogFactory newFactory(final String factoryClass, final ClassLoader classLoader) { + throw new UnsupportedOperationException("Operation [newFactory] is not supported in jcl-over-slf4j. See also " + + UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J); + } + }diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/NoOpLog.java b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/NoOpLog.java index c5881b2..45e99a4 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/NoOpLog.java +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/NoOpLog.java @@ -1,145 +1,145 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging.impl; - -import java.io.Serializable; -import org.apache.commons.logging.Log; - -/** - *

- * Trivial implementation of Log that throws away all messages. No configurable - * system properties are supported. - *

- * - * @author Scott Sanders - * @author Rod Waldhoff - * @version $Id: NoOpLog.java,v 1.8 2004/06/06 21:13:12 rdonkin Exp $ - */ -public class NoOpLog implements Log, Serializable { - private static final long serialVersionUID = 561423906191706148L; - - /** Convenience constructor */ - public NoOpLog() { - } - - /** Base constructor */ - public NoOpLog(String name) { - } - - /** Do nothing */ - public void trace(Object message) { - } - - /** Do nothing */ - public void trace(Object message, Throwable t) { - } - - /** Do nothing */ - public void debug(Object message) { - } - - /** Do nothing */ - public void debug(Object message, Throwable t) { - } - - /** Do nothing */ - public void info(Object message) { - } - - /** Do nothing */ - public void info(Object message, Throwable t) { - } - - /** Do nothing */ - public void warn(Object message) { - } - - /** Do nothing */ - public void warn(Object message, Throwable t) { - } - - /** Do nothing */ - public void error(Object message) { - } - - /** Do nothing */ - public void error(Object message, Throwable t) { - } - - /** Do nothing */ - public void fatal(Object message) { - } - - /** Do nothing */ - public void fatal(Object message, Throwable t) { - } - - /** - * Debug is never enabled. - * - * @return false - */ - public final boolean isDebugEnabled() { - return false; - } - - /** - * Error is never enabled. - * - * @return false - */ - public final boolean isErrorEnabled() { - return false; - } - - /** - * Fatal is never enabled. - * - * @return false - */ - public final boolean isFatalEnabled() { - return false; - } - - /** - * Info is never enabled. - * - * @return false - */ - public final boolean isInfoEnabled() { - return false; - } - - /** - * Trace is never enabled. - * - * @return false - */ - public final boolean isTraceEnabled() { - return false; - } - - /** - * Warn is never enabled. - * - * @return false - */ - public final boolean isWarnEnabled() { - return false; - } - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.logging.impl; + +import java.io.Serializable; +import org.apache.commons.logging.Log; + +/** + *

+ * Trivial implementation of Log that throws away all messages. No configurable + * system properties are supported. + *

+ * + * @author Scott Sanders + * @author Rod Waldhoff + * @version $Id: NoOpLog.java,v 1.8 2004/06/06 21:13:12 rdonkin Exp $ + */ +public class NoOpLog implements Log, Serializable { + private static final long serialVersionUID = 561423906191706148L; + + /** Convenience constructor */ + public NoOpLog() { + } + + /** Base constructor */ + public NoOpLog(String name) { + } + + /** Do nothing */ + public void trace(Object message) { + } + + /** Do nothing */ + public void trace(Object message, Throwable t) { + } + + /** Do nothing */ + public void debug(Object message) { + } + + /** Do nothing */ + public void debug(Object message, Throwable t) { + } + + /** Do nothing */ + public void info(Object message) { + } + + /** Do nothing */ + public void info(Object message, Throwable t) { + } + + /** Do nothing */ + public void warn(Object message) { + } + + /** Do nothing */ + public void warn(Object message, Throwable t) { + } + + /** Do nothing */ + public void error(Object message) { + } + + /** Do nothing */ + public void error(Object message, Throwable t) { + } + + /** Do nothing */ + public void fatal(Object message) { + } + + /** Do nothing */ + public void fatal(Object message, Throwable t) { + } + + /** + * Debug is never enabled. + * + * @return false + */ + public final boolean isDebugEnabled() { + return false; + } + + /** + * Error is never enabled. + * + * @return false + */ + public final boolean isErrorEnabled() { + return false; + } + + /** + * Fatal is never enabled. + * + * @return false + */ + public final boolean isFatalEnabled() { + return false; + } + + /** + * Info is never enabled. + * + * @return false + */ + public final boolean isInfoEnabled() { + return false; + } + + /** + * Trace is never enabled. + * + * @return false + */ + public final boolean isTraceEnabled() { + return false; + } + + /** + * Warn is never enabled. + * + * @return false + */ + public final boolean isWarnEnabled() { + return false; + } + +} diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLocationAwareLog.java b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLocationAwareLog.java index 6c712b8..ef48be6 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLocationAwareLog.java +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLocationAwareLog.java @@ -1,254 +1,254 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging.impl; - -import java.io.ObjectStreamException; -import java.io.Serializable; - -import org.apache.commons.logging.Log; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LocationAwareLogger; - -/** - * Implementation of {@link Log org.apache.commons.logging.Log} interface which - * delegates all processing to a wrapped {@link Logger org.slf4j.Logger} - * instance. - * - *

- * JCL's FATAL level is mapped to ERROR. All other levels map one to one. - * - * @author Ceki Gülcü - */ -public class SLF4JLocationAwareLog implements Log, Serializable { - - private static final long serialVersionUID = -2379157579039314822L; - - // used to store this logger's name to recreate it after serialization - protected String name; - - // in both Log4jLogger and Jdk14Logger classes in the original JCL, the - // logger instance is transient - private transient LocationAwareLogger logger; - - private static final String FQCN = SLF4JLocationAwareLog.class.getName(); - - SLF4JLocationAwareLog(LocationAwareLogger logger) { - this.logger = logger; - this.name = logger.getName(); - } - - /** - * Delegates to the isTraceEnabled method of the wrapped - * org.slf4j.Logger instance. - */ - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - /** - * Directly delegates to the wrapped org.slf4j.Logger instance. - */ - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - /** - * Directly delegates to the wrapped org.slf4j.Logger instance. - */ - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - /** - * Directly delegates to the wrapped org.slf4j.Logger instance. - */ - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - /** - * Directly delegates to the wrapped org.slf4j.Logger instance. - */ - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } - - /** - * Delegates to the isErrorEnabled method of the wrapped - * org.slf4j.Logger instance. - */ - public boolean isFatalEnabled() { - return logger.isErrorEnabled(); - } - - /** - * Converts the input parameter to String and then delegates to the debug - * method of the wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void trace(Object message) { - logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, null); - } - - /** - * Converts the first input parameter to String and then delegates to the - * debug method of the wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void trace(Object message, Throwable t) { - logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, t); - } - - /** - * Converts the input parameter to String and then delegates to the wrapped - * org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void debug(Object message) { - logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, null); - } - - /** - * Converts the first input parameter to String and then delegates to the - * wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void debug(Object message, Throwable t) { - logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, t); - } - - /** - * Converts the input parameter to String and then delegates to the wrapped - * org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void info(Object message) { - logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, null); - } - - /** - * Converts the first input parameter to String and then delegates to the - * wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void info(Object message, Throwable t) { - logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, t); - } - - /** - * Converts the input parameter to String and then delegates to the wrapped - * org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void warn(Object message) { - logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, null); - } - - /** - * Converts the first input parameter to String and then delegates to the - * wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void warn(Object message, Throwable t) { - logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, t); - } - - /** - * Converts the input parameter to String and then delegates to the wrapped - * org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void error(Object message) { - logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null); - } - - /** - * Converts the first input parameter to String and then delegates to the - * wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void error(Object message, Throwable t) { - logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t); - } - - /** - * Converts the input parameter to String and then delegates to the error - * method of the wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void fatal(Object message) { - logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null); - } - - /** - * Converts the first input parameter to String and then delegates to the - * error method of the wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void fatal(Object message, Throwable t) { - logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t); - } - - /** - * Replace this instance with a homonymous (same name) logger returned by - * LoggerFactory. Note that this method is only called during deserialization. - * - * @return logger with same name as returned by LoggerFactory - * @throws ObjectStreamException - */ - protected Object readResolve() throws ObjectStreamException { - Logger logger = LoggerFactory.getLogger(this.name); - return new SLF4JLocationAwareLog((LocationAwareLogger) logger); - } +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.logging.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import org.apache.commons.logging.Log; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LocationAwareLogger; + +/** + * Implementation of {@link Log org.apache.commons.logging.Log} interface which + * delegates all processing to a wrapped {@link Logger org.slf4j.Logger} + * instance. + * + *

+ * JCL's FATAL level is mapped to ERROR. All other levels map one to one. + * + * @author Ceki Gülcü + */ +public class SLF4JLocationAwareLog implements Log, Serializable { + + private static final long serialVersionUID = -2379157579039314822L; + + // used to store this logger's name to recreate it after serialization + protected String name; + + // in both Log4jLogger and Jdk14Logger classes in the original JCL, the + // logger instance is transient + private transient LocationAwareLogger logger; + + private static final String FQCN = SLF4JLocationAwareLog.class.getName(); + + SLF4JLocationAwareLog(LocationAwareLogger logger) { + this.logger = logger; + this.name = logger.getName(); + } + + /** + * Delegates to the isTraceEnabled method of the wrapped + * org.slf4j.Logger instance. + */ + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + /** + * Delegates to the isErrorEnabled method of the wrapped + * org.slf4j.Logger instance. + */ + public boolean isFatalEnabled() { + return logger.isErrorEnabled(); + } + + /** + * Converts the input parameter to String and then delegates to the debug + * method of the wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void trace(Object message) { + logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, null); + } + + /** + * Converts the first input parameter to String and then delegates to the + * debug method of the wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void trace(Object message, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.TRACE_INT, String.valueOf(message), null, t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void debug(Object message) { + logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, null); + } + + /** + * Converts the first input parameter to String and then delegates to the + * wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void debug(Object message, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.DEBUG_INT, String.valueOf(message), null, t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void info(Object message) { + logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, null); + } + + /** + * Converts the first input parameter to String and then delegates to the + * wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void info(Object message, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.INFO_INT, String.valueOf(message), null, t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void warn(Object message) { + logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, null); + } + + /** + * Converts the first input parameter to String and then delegates to the + * wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void warn(Object message, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.WARN_INT, String.valueOf(message), null, t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void error(Object message) { + logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null); + } + + /** + * Converts the first input parameter to String and then delegates to the + * wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void error(Object message, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t); + } + + /** + * Converts the input parameter to String and then delegates to the error + * method of the wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void fatal(Object message) { + logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, null); + } + + /** + * Converts the first input parameter to String and then delegates to the + * error method of the wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void fatal(Object message, Throwable t) { + logger.log(null, FQCN, LocationAwareLogger.ERROR_INT, String.valueOf(message), null, t); + } + + /** + * Replace this instance with a homonymous (same name) logger returned by + * LoggerFactory. Note that this method is only called during deserialization. + * + * @return logger with same name as returned by LoggerFactory + * @throws ObjectStreamException + */ + protected Object readResolve() throws ObjectStreamException { + Logger logger = LoggerFactory.getLogger(this.name); + return new SLF4JLocationAwareLog((LocationAwareLogger) logger); + } }diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLog.java b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLog.java index 5a14285..5ee59f7 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLog.java +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLog.java @@ -1,251 +1,251 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging.impl; - -import java.io.ObjectStreamException; -import java.io.Serializable; - -import org.apache.commons.logging.Log; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Implementation of {@link Log org.apache.commons.logging.Log} interface which - * delegates all processing to a wrapped {@link Logger org.slf4j.Logger} - * instance. - * - *

- * JCL's FATAL level is mapped to ERROR. All other levels map one to one. - * - * @author Ceki Gülcü - */ -public class SLF4JLog implements Log, Serializable { - - private static final long serialVersionUID = 680728617011167209L; - - // used to store this logger's name to recreate it after serialization - protected String name; - - // in both Log4jLogger and Jdk14Logger classes in the original JCL, the - // logger instance is transient - private transient Logger logger; - - SLF4JLog(Logger logger) { - this.logger = logger; - this.name = logger.getName(); - } - - /** - * Directly delegates to the wrapped org.slf4j.Logger instance. - */ - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - /** - * Directly delegates to the wrapped org.slf4j.Logger instance. - */ - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } - - /** - * Delegates to the isErrorEnabled method of the wrapped - * org.slf4j.Logger instance. - */ - public boolean isFatalEnabled() { - return logger.isErrorEnabled(); - } - - /** - * Directly delegates to the wrapped org.slf4j.Logger instance. - */ - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - /** - * Delegates to the isDebugEnabled method of the wrapped - * org.slf4j.Logger instance. - */ - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - /** - * Directly delegates to the wrapped org.slf4j.Logger instance. - */ - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - /** - * Converts the input parameter to String and then delegates to the debug - * method of the wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void trace(Object message) { - logger.trace(String.valueOf(message)); - } - - /** - * Converts the first input parameter to String and then delegates to the - * debug method of the wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void trace(Object message, Throwable t) { - logger.trace(String.valueOf(message), t); - } - - /** - * Converts the input parameter to String and then delegates to the wrapped - * org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void debug(Object message) { - logger.debug(String.valueOf(message)); - } - - /** - * Converts the first input parameter to String and then delegates to the - * wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void debug(Object message, Throwable t) { - logger.debug(String.valueOf(message), t); - } - - /** - * Converts the input parameter to String and then delegates to the wrapped - * org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void info(Object message) { - logger.info(String.valueOf(message)); - } - - /** - * Converts the first input parameter to String and then delegates to the - * wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void info(Object message, Throwable t) { - logger.info(String.valueOf(message), t); - } - - /** - * Converts the input parameter to String and then delegates to the wrapped - * org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void warn(Object message) { - logger.warn(String.valueOf(message)); - } - - /** - * Converts the first input parameter to String and then delegates to the - * wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void warn(Object message, Throwable t) { - logger.warn(String.valueOf(message), t); - } - - /** - * Converts the input parameter to String and then delegates to the wrapped - * org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void error(Object message) { - logger.error(String.valueOf(message)); - } - - /** - * Converts the first input parameter to String and then delegates to the - * wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void error(Object message, Throwable t) { - logger.error(String.valueOf(message), t); - } - - /** - * Converts the input parameter to String and then delegates to the error - * method of the wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - */ - public void fatal(Object message) { - logger.error(String.valueOf(message)); - } - - /** - * Converts the first input parameter to String and then delegates to the - * error method of the wrapped org.slf4j.Logger instance. - * - * @param message - * the message to log. Converted to {@link String} - * @param t - * the exception to log - */ - public void fatal(Object message, Throwable t) { - logger.error(String.valueOf(message), t); - } - - /** - * Replace this instance with a homonymous (same name) logger returned by - * LoggerFactory. Note that this method is only called during deserialization. - * - * @return logger with same name as returned by LoggerFactory - * @throws ObjectStreamException - */ - protected Object readResolve() throws ObjectStreamException { - Logger logger = LoggerFactory.getLogger(this.name); - return new SLF4JLog(logger); - } +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.logging.impl; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import org.apache.commons.logging.Log; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Implementation of {@link Log org.apache.commons.logging.Log} interface which + * delegates all processing to a wrapped {@link Logger org.slf4j.Logger} + * instance. + * + *

+ * JCL's FATAL level is mapped to ERROR. All other levels map one to one. + * + * @author Ceki Gülcü + */ +public class SLF4JLog implements Log, Serializable { + + private static final long serialVersionUID = 680728617011167209L; + + // used to store this logger's name to recreate it after serialization + protected String name; + + // in both Log4jLogger and Jdk14Logger classes in the original JCL, the + // logger instance is transient + private transient Logger logger; + + SLF4JLog(Logger logger) { + this.logger = logger; + this.name = logger.getName(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + /** + * Delegates to the isErrorEnabled method of the wrapped + * org.slf4j.Logger instance. + */ + public boolean isFatalEnabled() { + return logger.isErrorEnabled(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + /** + * Delegates to the isDebugEnabled method of the wrapped + * org.slf4j.Logger instance. + */ + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + /** + * Converts the input parameter to String and then delegates to the debug + * method of the wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void trace(Object message) { + logger.trace(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to the + * debug method of the wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void trace(Object message, Throwable t) { + logger.trace(String.valueOf(message), t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void debug(Object message) { + logger.debug(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to the + * wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void debug(Object message, Throwable t) { + logger.debug(String.valueOf(message), t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void info(Object message) { + logger.info(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to the + * wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void info(Object message, Throwable t) { + logger.info(String.valueOf(message), t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void warn(Object message) { + logger.warn(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to the + * wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void warn(Object message, Throwable t) { + logger.warn(String.valueOf(message), t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void error(Object message) { + logger.error(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to the + * wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void error(Object message, Throwable t) { + logger.error(String.valueOf(message), t); + } + + /** + * Converts the input parameter to String and then delegates to the error + * method of the wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + */ + public void fatal(Object message) { + logger.error(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to the + * error method of the wrapped org.slf4j.Logger instance. + * + * @param message + * the message to log. Converted to {@link String} + * @param t + * the exception to log + */ + public void fatal(Object message, Throwable t) { + logger.error(String.valueOf(message), t); + } + + /** + * Replace this instance with a homonymous (same name) logger returned by + * LoggerFactory. Note that this method is only called during deserialization. + * + * @return logger with same name as returned by LoggerFactory + * @throws ObjectStreamException + */ + protected Object readResolve() throws ObjectStreamException { + Logger logger = LoggerFactory.getLogger(this.name); + return new SLF4JLog(logger); + } }diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLogFactory.java b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLogFactory.java index b40b034..d715c59 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLogFactory.java +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLogFactory.java @@ -1,219 +1,219 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogConfigurationException; -import org.apache.commons.logging.LogFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LocationAwareLogger; - -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - *

- * Concrete subclass of {@link LogFactory} which always delegates to the - * {@link LoggerFactory org.slf4j.LoggerFactory} class. - * - *

- * This factory generates instances of {@link SLF4JLog}. It will remember - * previously created instances for the same name, and will return them on - * repeated requests to the getInstance() method. - * - *

- * This implementation ignores any configured attributes. - *

- * - * @author Rod Waldhoff - * @author Craig R. McClanahan - * @author Richard A. Sitze - * @author Ceki Gülcü - */ -@SuppressWarnings("rawtypes") -public class SLF4JLogFactory extends LogFactory { - - // ----------------------------------------------------------- Constructors - - /** - * The {@link org.apache.commons.logging.Log}instances that have already been - * created, keyed by logger name. - */ - ConcurrentMap loggerMap; - - /** - * Public no-arguments constructor required by the lookup mechanism. - */ - public SLF4JLogFactory() { - loggerMap = new ConcurrentHashMap(); - } - - // ----------------------------------------------------- Manifest Constants - - /** - * The name of the system property identifying our {@link Log}implementation - * class. - */ - public static final String LOG_PROPERTY = "org.apache.commons.logging.Log"; - - // ----------------------------------------------------- Instance Variables - - /** - * Configuration attributes. - */ - protected Hashtable attributes = new Hashtable(); - - // --------------------------------------------------------- Public Methods - - /** - * Return the configuration attribute with the specified name (if any), or - * null if there is no such attribute. - * - * @param name - * Name of the attribute to return - */ - public Object getAttribute(String name) { - - return (attributes.get(name)); - - } - - /** - * Return an array containing the names of all currently defined configuration - * attributes. If there are no such attributes, a zero length array is - * returned. - */ - @SuppressWarnings("unchecked") - public String[] getAttributeNames() { - - List names = new ArrayList(); - Enumeration keys = attributes.keys(); - while (keys.hasMoreElements()) { - names.add((String) keys.nextElement()); - } - String results[] = new String[names.size()]; - for (int i = 0; i < results.length; i++) { - results[i] = (String) names.get(i); - } - return (results); - - } - - /** - * Convenience method to derive a name from the specified class and call - * getInstance(String) with it. - * - * @param clazz - * Class for which a suitable Log name will be derived - * - * @exception LogConfigurationException - * if a suitable Log instance cannot be returned - */ - public Log getInstance(Class clazz) throws LogConfigurationException { - return (getInstance(clazz.getName())); - } - - /** - *

- * Construct (if necessary) and return a Log instance, using - * the factory's current set of configuration attributes. - *

- * - * @param name - * Logical name of the Log instance to be returned - * (the meaning of this name is only known to the underlying logging - * implementation that is being wrapped) - * - * @exception LogConfigurationException - * if a suitable Log instance cannot be returned - */ - public Log getInstance(String name) throws LogConfigurationException { - Log instance = loggerMap.get(name); - if (instance != null) { - return instance; - } else { - Log newInstance; - Logger slf4jLogger = LoggerFactory.getLogger(name); - if (slf4jLogger instanceof LocationAwareLogger) { - newInstance = new SLF4JLocationAwareLog((LocationAwareLogger) slf4jLogger); - } else { - newInstance = new SLF4JLog(slf4jLogger); - } - Log oldInstance = loggerMap.putIfAbsent(name, newInstance); - return oldInstance == null ? newInstance : oldInstance; - } - } - - /** - * Release any internal references to previously created - * {@link org.apache.commons.logging.Log}instances returned by this factory. - * This is useful in environments like servlet containers, which implement - * application reloading by throwing away a ClassLoader. Dangling references - * to objects in that class loader would prevent garbage collection. - */ - public void release() { - // This method is never called by jcl-over-slf4j classes. However, - // in certain deployment scenarios, in particular if jcl-over-slf4j.jar - // is - // in the the web-app class loader and the official commons-logging.jar is - // deployed in some parent class loader (e.g. commons/lib), then it is - // possible - // for the parent class loader to mask the classes shipping in - // jcl-over-slf4j.jar. - System.out.println("WARN: The method " + SLF4JLogFactory.class + "#release() was invoked."); - System.out.println("WARN: Please see http://www.slf4j.org/codes.html#release for an explanation."); - System.out.flush(); - } - - /** - * Remove any configuration attribute associated with the specified name. If - * there is no such attribute, no action is taken. - * - * @param name - * Name of the attribute to remove - */ - public void removeAttribute(String name) { - attributes.remove(name); - } - - /** - * Set the configuration attribute with the specified name. Calling this with - * a null value is equivalent to calling - * removeAttribute(name). - * - * @param name - * Name of the attribute to set - * @param value - * Value of the attribute to set, or null to remove - * any setting for this attribute - */ - @SuppressWarnings("unchecked") - public void setAttribute(String name, Object value) { - - if (value == null) { - attributes.remove(name); - } else { - attributes.put(name, value); - } - - } +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.logging.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogConfigurationException; +import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LocationAwareLogger; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + *

+ * Concrete subclass of {@link LogFactory} which always delegates to the + * {@link LoggerFactory org.slf4j.LoggerFactory} class. + * + *

+ * This factory generates instances of {@link SLF4JLog}. It will remember + * previously created instances for the same name, and will return them on + * repeated requests to the getInstance() method. + * + *

+ * This implementation ignores any configured attributes. + *

+ * + * @author Rod Waldhoff + * @author Craig R. McClanahan + * @author Richard A. Sitze + * @author Ceki Gülcü + */ +@SuppressWarnings("rawtypes") +public class SLF4JLogFactory extends LogFactory { + + // ----------------------------------------------------------- Constructors + + /** + * The {@link org.apache.commons.logging.Log}instances that have already been + * created, keyed by logger name. + */ + ConcurrentMap loggerMap; + + /** + * Public no-arguments constructor required by the lookup mechanism. + */ + public SLF4JLogFactory() { + loggerMap = new ConcurrentHashMap(); + } + + // ----------------------------------------------------- Manifest Constants + + /** + * The name of the system property identifying our {@link Log}implementation + * class. + */ + public static final String LOG_PROPERTY = "org.apache.commons.logging.Log"; + + // ----------------------------------------------------- Instance Variables + + /** + * Configuration attributes. + */ + protected Hashtable attributes = new Hashtable(); + + // --------------------------------------------------------- Public Methods + + /** + * Return the configuration attribute with the specified name (if any), or + * null if there is no such attribute. + * + * @param name + * Name of the attribute to return + */ + public Object getAttribute(String name) { + + return (attributes.get(name)); + + } + + /** + * Return an array containing the names of all currently defined configuration + * attributes. If there are no such attributes, a zero length array is + * returned. + */ + @SuppressWarnings("unchecked") + public String[] getAttributeNames() { + + List names = new ArrayList(); + Enumeration keys = attributes.keys(); + while (keys.hasMoreElements()) { + names.add((String) keys.nextElement()); + } + String results[] = new String[names.size()]; + for (int i = 0; i < results.length; i++) { + results[i] = (String) names.get(i); + } + return (results); + + } + + /** + * Convenience method to derive a name from the specified class and call + * getInstance(String) with it. + * + * @param clazz + * Class for which a suitable Log name will be derived + * + * @exception LogConfigurationException + * if a suitable Log instance cannot be returned + */ + public Log getInstance(Class clazz) throws LogConfigurationException { + return (getInstance(clazz.getName())); + } + + /** + *

+ * Construct (if necessary) and return a Log instance, using + * the factory's current set of configuration attributes. + *

+ * + * @param name + * Logical name of the Log instance to be returned + * (the meaning of this name is only known to the underlying logging + * implementation that is being wrapped) + * + * @exception LogConfigurationException + * if a suitable Log instance cannot be returned + */ + public Log getInstance(String name) throws LogConfigurationException { + Log instance = loggerMap.get(name); + if (instance != null) { + return instance; + } else { + Log newInstance; + Logger slf4jLogger = LoggerFactory.getLogger(name); + if (slf4jLogger instanceof LocationAwareLogger) { + newInstance = new SLF4JLocationAwareLog((LocationAwareLogger) slf4jLogger); + } else { + newInstance = new SLF4JLog(slf4jLogger); + } + Log oldInstance = loggerMap.putIfAbsent(name, newInstance); + return oldInstance == null ? newInstance : oldInstance; + } + } + + /** + * Release any internal references to previously created + * {@link org.apache.commons.logging.Log}instances returned by this factory. + * This is useful in environments like servlet containers, which implement + * application reloading by throwing away a ClassLoader. Dangling references + * to objects in that class loader would prevent garbage collection. + */ + public void release() { + // This method is never called by jcl-over-slf4j classes. However, + // in certain deployment scenarios, in particular if jcl-over-slf4j.jar + // is + // in the the web-app class loader and the official commons-logging.jar is + // deployed in some parent class loader (e.g. commons/lib), then it is + // possible + // for the parent class loader to mask the classes shipping in + // jcl-over-slf4j.jar. + System.out.println("WARN: The method " + SLF4JLogFactory.class + "#release() was invoked."); + System.out.println("WARN: Please see http://www.slf4j.org/codes.html#release for an explanation."); + System.out.flush(); + } + + /** + * Remove any configuration attribute associated with the specified name. If + * there is no such attribute, no action is taken. + * + * @param name + * Name of the attribute to remove + */ + public void removeAttribute(String name) { + attributes.remove(name); + } + + /** + * Set the configuration attribute with the specified name. Calling this with + * a null value is equivalent to calling + * removeAttribute(name). + * + * @param name + * Name of the attribute to set + * @param value + * Value of the attribute to set, or null to remove + * any setting for this attribute + */ + @SuppressWarnings("unchecked") + public void setAttribute(String name, Object value) { + + if (value == null) { + attributes.remove(name); + } else { + attributes.put(name, value); + } + + } }diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SimpleLog.java b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SimpleLog.java index 4a9bd0d..96b6422 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SimpleLog.java +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SimpleLog.java @@ -1,688 +1,688 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging.impl; - -import java.io.InputStream; -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogConfigurationException; - -/** - *

- * Simple implementation of Log that sends all enabled log messages, for all - * defined loggers, to System.err. The following system properties are supported - * to configure the behavior of this logger: - *

- *
    - *
  • org.apache.commons.logging.simplelog.defaultlog - Default - * logging detail level for all instances of SimpleLog. Must be one of ("trace", - * "debug", "info", "warn", "error", or "fatal"). If not specified, defaults to - * "info".
  • - *
  • org.apache.commons.logging.simplelog.log.xxxxx - Logging - * detail level for a SimpleLog instance named "xxxxx". Must be one of ("trace", - * "debug", "info", "warn", "error", or "fatal"). If not specified, the default - * logging detail level is used.
  • - *
  • org.apache.commons.logging.simplelog.showlogname - Set to - * true if you want the Log instance name to be included in output - * messages. Defaults to false.
  • - *
  • org.apache.commons.logging.simplelog.showShortLogname - Set - * to true if you want the last component of the name to be - * included in output messages. Defaults to true.
  • - *
  • org.apache.commons.logging.simplelog.showdatetime - Set to - * true if you want the current date and time to be included in - * output messages. Default is false.
  • - *
  • org.apache.commons.logging.simplelog.dateTimeFormat - The - * date and time format to be used in the output messages. The pattern - * describing the date and time format is the same that is used in - * java.text.SimpleDateFormat. If the format is not specified or is - * invalid, the default format is used. The default format is - * yyyy/MM/dd HH:mm:ss:SSS zzz.
  • - *
- * - *

- * In addition to looking for system properties with the names specified above, - * this implementation also checks for a class loader resource named - * "simplelog.properties", and includes any matching definitions - * from this resource (if it exists). - *

- * - * @author Scott Sanders - * @author Rod Waldhoff - * @author Robert Burrell Donkin - * - * @version $Id: SimpleLog.java,v 1.21 2004/06/06 20:47:56 rdonkin Exp $ - */ -public class SimpleLog implements Log, Serializable { - - private static final long serialVersionUID = 136942970684951178L; - - // ------------------------------------------------------- Class Attributes - - /** All system properties used by SimpleLog start with this */ - static protected final String systemPrefix = "org.apache.commons.logging.simplelog."; - - /** Properties loaded from simplelog.properties */ - static protected final Properties simpleLogProps = new Properties(); - - /** The default format to use when formatting dates */ - static protected final String DEFAULT_DATE_TIME_FORMAT = "yyyy/MM/dd HH:mm:ss:SSS zzz"; - - /** Include the instance name in the log message? */ - static protected boolean showLogName = false; - /** - * Include the short name ( last component ) of the logger in the log message. - * Defaults to true - otherwise we'll be lost in a flood of messages without - * knowing who sends them. - */ - static protected boolean showShortName = true; - /** Include the current time in the log message */ - static protected boolean showDateTime = false; - /** The date and time format to use in the log message */ - static protected String dateTimeFormat = DEFAULT_DATE_TIME_FORMAT; - /** Used to format times */ - static protected DateFormat dateFormatter = null; - - // ---------------------------------------------------- Log Level Constants - - /** "Trace" level logging. */ - public static final int LOG_LEVEL_TRACE = 1; - /** "Debug" level logging. */ - public static final int LOG_LEVEL_DEBUG = 2; - /** "Info" level logging. */ - public static final int LOG_LEVEL_INFO = 3; - /** "Warn" level logging. */ - public static final int LOG_LEVEL_WARN = 4; - /** "Error" level logging. */ - public static final int LOG_LEVEL_ERROR = 5; - /** "Fatal" level logging. */ - public static final int LOG_LEVEL_FATAL = 6; - - /** Enable all logging levels */ - public static final int LOG_LEVEL_ALL = (LOG_LEVEL_TRACE - 1); - - /** Enable no logging levels */ - public static final int LOG_LEVEL_OFF = (LOG_LEVEL_FATAL + 1); - - // ------------------------------------------------------------ Initializer - - private static String getStringProperty(String name) { - String prop = null; - try { - prop = System.getProperty(name); - } catch (SecurityException e) { - ; // Ignore - } - return (prop == null) ? simpleLogProps.getProperty(name) : prop; - } - - private static String getStringProperty(String name, String dephault) { - String prop = getStringProperty(name); - return (prop == null) ? dephault : prop; - } - - private static boolean getBooleanProperty(String name, boolean dephault) { - String prop = getStringProperty(name); - return (prop == null) ? dephault : "true".equalsIgnoreCase(prop); - } - - // Initialize class attributes. - // Load properties file, if found. - // Override with system properties. - static { - // Add props from the resource simplelog.properties - InputStream in = getResourceAsStream("simplelog.properties"); - if (null != in) { - try { - simpleLogProps.load(in); - } catch (java.io.IOException e) { - // ignored - } finally { - try { - in.close(); - } catch (java.io.IOException e) { - // ignored - } - } - } - - showLogName = getBooleanProperty(systemPrefix + "showlogname", showLogName); - showShortName = getBooleanProperty(systemPrefix + "showShortLogname", showShortName); - showDateTime = getBooleanProperty(systemPrefix + "showdatetime", showDateTime); - - if (showDateTime) { - dateTimeFormat = getStringProperty(systemPrefix + "dateTimeFormat", dateTimeFormat); - try { - dateFormatter = new SimpleDateFormat(dateTimeFormat); - } catch (IllegalArgumentException e) { - // If the format pattern is invalid - use the default format - dateTimeFormat = DEFAULT_DATE_TIME_FORMAT; - dateFormatter = new SimpleDateFormat(dateTimeFormat); - } - } - } - - // ------------------------------------------------------------- Attributes - - /** The name of this simple log instance */ - protected String logName = null; - /** The current log level */ - protected int currentLogLevel; - /** The short name of this simple log instance */ - private String shortLogName = null; - - // ------------------------------------------------------------ Constructor - - /** - * Construct a simple log with given name. - * - * @param name - * log name - */ - public SimpleLog(String name) { - - logName = name; - - // Set initial log level - // Used to be: set default log level to ERROR - // IMHO it should be lower, but at least info ( costin ). - setLevel(SimpleLog.LOG_LEVEL_INFO); - - // Set log level from properties - String lvl = getStringProperty(systemPrefix + "log." + logName); - int i = String.valueOf(name).lastIndexOf("."); - while (null == lvl && i > -1) { - name = name.substring(0, i); - lvl = getStringProperty(systemPrefix + "log." + name); - i = String.valueOf(name).lastIndexOf("."); - } - - if (null == lvl) { - lvl = getStringProperty(systemPrefix + "defaultlog"); - } - - if ("all".equalsIgnoreCase(lvl)) { - setLevel(SimpleLog.LOG_LEVEL_ALL); - } else if ("trace".equalsIgnoreCase(lvl)) { - setLevel(SimpleLog.LOG_LEVEL_TRACE); - } else if ("debug".equalsIgnoreCase(lvl)) { - setLevel(SimpleLog.LOG_LEVEL_DEBUG); - } else if ("info".equalsIgnoreCase(lvl)) { - setLevel(SimpleLog.LOG_LEVEL_INFO); - } else if ("warn".equalsIgnoreCase(lvl)) { - setLevel(SimpleLog.LOG_LEVEL_WARN); - } else if ("error".equalsIgnoreCase(lvl)) { - setLevel(SimpleLog.LOG_LEVEL_ERROR); - } else if ("fatal".equalsIgnoreCase(lvl)) { - setLevel(SimpleLog.LOG_LEVEL_FATAL); - } else if ("off".equalsIgnoreCase(lvl)) { - setLevel(SimpleLog.LOG_LEVEL_OFF); - } - - } - - // -------------------------------------------------------- Properties - - /** - *

- * Set logging level. - *

- * - * @param currentLogLevel - * new logging level - */ - public void setLevel(int currentLogLevel) { - - this.currentLogLevel = currentLogLevel; - - } - - /** - *

- * Get logging level. - *

- */ - public int getLevel() { - - return currentLogLevel; - } - - // -------------------------------------------------------- Logging Methods - - /** - *

- * Do the actual logging. This method assembles the message and then calls - * write() to cause it to be written. - *

- * - * @param type - * One of the LOG_LEVEL_XXX constants defining the log level - * @param message - * The message itself (typically a String) - * @param t - * The exception whose stack trace should be logged - */ - protected void log(int type, Object message, Throwable t) { - // Use a string buffer for better performance - StringBuffer buf = new StringBuffer(); - - // Append date-time if so configured - if (showDateTime) { - buf.append(dateFormatter.format(new Date())); - buf.append(" "); - } - - // Append a readable representation of the log level - switch (type) { - case SimpleLog.LOG_LEVEL_TRACE: - buf.append("[TRACE] "); - break; - case SimpleLog.LOG_LEVEL_DEBUG: - buf.append("[DEBUG] "); - break; - case SimpleLog.LOG_LEVEL_INFO: - buf.append("[INFO] "); - break; - case SimpleLog.LOG_LEVEL_WARN: - buf.append("[WARN] "); - break; - case SimpleLog.LOG_LEVEL_ERROR: - buf.append("[ERROR] "); - break; - case SimpleLog.LOG_LEVEL_FATAL: - buf.append("[FATAL] "); - break; - } - - // Append the name of the log instance if so configured - if (showShortName) { - if (shortLogName == null) { - // Cut all but the last component of the name for both styles - shortLogName = logName.substring(logName.lastIndexOf(".") + 1); - shortLogName = shortLogName.substring(shortLogName.lastIndexOf("/") + 1); - } - buf.append(String.valueOf(shortLogName)).append(" - "); - } else if (showLogName) { - buf.append(String.valueOf(logName)).append(" - "); - } - - // Append the message - buf.append(String.valueOf(message)); - - // Append stack trace if not null - if (t != null) { - buf.append(" <"); - buf.append(t.toString()); - buf.append(">"); - - java.io.StringWriter sw = new java.io.StringWriter(1024); - java.io.PrintWriter pw = new java.io.PrintWriter(sw); - t.printStackTrace(pw); - pw.close(); - buf.append(sw.toString()); - } - - // Print to the appropriate destination - write(buf); - - } - - /** - *

- * Write the content of the message accumulated in the specified - * StringBuffer to the appropriate output destination. The - * default implementation writes to System.err. - *

- * - * @param buffer - * A StringBuffer containing the accumulated text to be - * logged - */ - protected void write(StringBuffer buffer) { - - System.err.println(buffer.toString()); - - } - - /** - * Is the given log level currently enabled? - * - * @param logLevel - * is this level enabled? - */ - protected boolean isLevelEnabled(int logLevel) { - // log level are numerically ordered so can use simple numeric - // comparison - return (logLevel >= currentLogLevel); - } - - // -------------------------------------------------------- Log Implementation - - /** - *

- * Log a message with debug log level. - *

- */ - public final void debug(Object message) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) { - log(SimpleLog.LOG_LEVEL_DEBUG, message, null); - } - } - - /** - *

- * Log an error with debug log level. - *

- */ - public final void debug(Object message, Throwable t) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) { - log(SimpleLog.LOG_LEVEL_DEBUG, message, t); - } - } - - /** - *

- * Log a message with trace log level. - *

- */ - public final void trace(Object message) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) { - log(SimpleLog.LOG_LEVEL_TRACE, message, null); - } - } - - /** - *

- * Log an error with trace log level. - *

- */ - public final void trace(Object message, Throwable t) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) { - log(SimpleLog.LOG_LEVEL_TRACE, message, t); - } - } - - /** - *

- * Log a message with info log level. - *

- */ - public final void info(Object message) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) { - log(SimpleLog.LOG_LEVEL_INFO, message, null); - } - } - - /** - *

- * Log an error with info log level. - *

- */ - public final void info(Object message, Throwable t) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) { - log(SimpleLog.LOG_LEVEL_INFO, message, t); - } - } - - /** - *

- * Log a message with warn log level. - *

- */ - public final void warn(Object message) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) { - log(SimpleLog.LOG_LEVEL_WARN, message, null); - } - } - - /** - *

- * Log an error with warn log level. - *

- */ - public final void warn(Object message, Throwable t) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) { - log(SimpleLog.LOG_LEVEL_WARN, message, t); - } - } - - /** - *

- * Log a message with error log level. - *

- */ - public final void error(Object message) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) { - log(SimpleLog.LOG_LEVEL_ERROR, message, null); - } - } - - /** - *

- * Log an error with error log level. - *

- */ - public final void error(Object message, Throwable t) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) { - log(SimpleLog.LOG_LEVEL_ERROR, message, t); - } - } - - /** - *

- * Log a message with fatal log level. - *

- */ - public final void fatal(Object message) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) { - log(SimpleLog.LOG_LEVEL_FATAL, message, null); - } - } - - /** - *

- * Log an error with fatal log level. - *

- */ - public final void fatal(Object message, Throwable t) { - - if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) { - log(SimpleLog.LOG_LEVEL_FATAL, message, t); - } - } - - /** - *

- * Are debug messages currently enabled? - *

- * - *

- * This allows expensive operations such as String concatenation - * to be avoided when the message will be ignored by the logger. - *

- */ - public final boolean isDebugEnabled() { - - return isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG); - } - - /** - *

- * Are error messages currently enabled? - *

- * - *

- * This allows expensive operations such as String concatenation - * to be avoided when the message will be ignored by the logger. - *

- */ - public final boolean isErrorEnabled() { - - return isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR); - } - - /** - *

- * Are fatal messages currently enabled? - *

- * - *

- * This allows expensive operations such as String concatenation - * to be avoided when the message will be ignored by the logger. - *

- */ - public final boolean isFatalEnabled() { - - return isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL); - } - - /** - *

- * Are info messages currently enabled? - *

- * - *

- * This allows expensive operations such as String concatenation - * to be avoided when the message will be ignored by the logger. - *

- */ - public final boolean isInfoEnabled() { - - return isLevelEnabled(SimpleLog.LOG_LEVEL_INFO); - } - - /** - *

- * Are trace messages currently enabled? - *

- * - *

- * This allows expensive operations such as String concatenation - * to be avoided when the message will be ignored by the logger. - *

- */ - public final boolean isTraceEnabled() { - - return isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE); - } - - /** - *

- * Are warn messages currently enabled? - *

- * - *

- * This allows expensive operations such as String concatenation - * to be avoided when the message will be ignored by the logger. - *

- */ - public final boolean isWarnEnabled() { - - return isLevelEnabled(SimpleLog.LOG_LEVEL_WARN); - } - - /** - * Return the thread context class loader if available. Otherwise return null. - * - * The thread context class loader is available for JDK 1.2 or later, if - * certain security conditions are met. - * - * @exception LogConfigurationException - * if a suitable class loader cannot be identified. - */ - private static ClassLoader getContextClassLoader() { - ClassLoader classLoader = null; - - if (classLoader == null) { - try { - // Are we running on a JDK 1.2 or later system? - Method method = Thread.class.getMethod("getContextClassLoader"); - - // Get the thread context class loader (if there is one) - try { - classLoader = (ClassLoader) method.invoke(Thread.currentThread()); - } catch (IllegalAccessException e) { - ; // ignore - } catch (InvocationTargetException e) { - /** - * InvocationTargetException is thrown by 'invoke' when the method - * being invoked (getContextClassLoader) throws an exception. - * - * getContextClassLoader() throws SecurityException when the context - * class loader isn't an ancestor of the calling class's class loader, - * or if security permissions are restricted. - * - * In the first case (not related), we want to ignore and keep going. - * We cannot help but also ignore the second with the logic below, but - * other calls elsewhere (to obtain a class loader) will trigger this - * exception where we can make a distinction. - */ - if (e.getTargetException() instanceof SecurityException) { - ; // ignore - } else { - // Capture 'e.getTargetException()' exception for details - // alternate: log 'e.getTargetException()', and pass back 'e'. - throw new LogConfigurationException("Unexpected InvocationTargetException", e.getTargetException()); - } - } - } catch (NoSuchMethodException e) { - // Assume we are running on JDK 1.1 - ; // ignore - } - } - - if (classLoader == null) { - classLoader = SimpleLog.class.getClassLoader(); - } - - // Return the selected class loader - return classLoader; - } - - private static InputStream getResourceAsStream(final String name) { - return AccessController.doPrivileged(new PrivilegedAction() { - public InputStream run() { - ClassLoader threadCL = getContextClassLoader(); - - if (threadCL != null) { - return threadCL.getResourceAsStream(name); - } else { - return ClassLoader.getSystemResourceAsStream(name); - } - } - }); - } -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.logging.impl; + +import java.io.InputStream; +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogConfigurationException; + +/** + *

+ * Simple implementation of Log that sends all enabled log messages, for all + * defined loggers, to System.err. The following system properties are supported + * to configure the behavior of this logger: + *

+ *
    + *
  • org.apache.commons.logging.simplelog.defaultlog - Default + * logging detail level for all instances of SimpleLog. Must be one of ("trace", + * "debug", "info", "warn", "error", or "fatal"). If not specified, defaults to + * "info".
  • + *
  • org.apache.commons.logging.simplelog.log.xxxxx - Logging + * detail level for a SimpleLog instance named "xxxxx". Must be one of ("trace", + * "debug", "info", "warn", "error", or "fatal"). If not specified, the default + * logging detail level is used.
  • + *
  • org.apache.commons.logging.simplelog.showlogname - Set to + * true if you want the Log instance name to be included in output + * messages. Defaults to false.
  • + *
  • org.apache.commons.logging.simplelog.showShortLogname - Set + * to true if you want the last component of the name to be + * included in output messages. Defaults to true.
  • + *
  • org.apache.commons.logging.simplelog.showdatetime - Set to + * true if you want the current date and time to be included in + * output messages. Default is false.
  • + *
  • org.apache.commons.logging.simplelog.dateTimeFormat - The + * date and time format to be used in the output messages. The pattern + * describing the date and time format is the same that is used in + * java.text.SimpleDateFormat. If the format is not specified or is + * invalid, the default format is used. The default format is + * yyyy/MM/dd HH:mm:ss:SSS zzz.
  • + *
+ * + *

+ * In addition to looking for system properties with the names specified above, + * this implementation also checks for a class loader resource named + * "simplelog.properties", and includes any matching definitions + * from this resource (if it exists). + *

+ * + * @author Scott Sanders + * @author Rod Waldhoff + * @author Robert Burrell Donkin + * + * @version $Id: SimpleLog.java,v 1.21 2004/06/06 20:47:56 rdonkin Exp $ + */ +public class SimpleLog implements Log, Serializable { + + private static final long serialVersionUID = 136942970684951178L; + + // ------------------------------------------------------- Class Attributes + + /** All system properties used by SimpleLog start with this */ + static protected final String systemPrefix = "org.apache.commons.logging.simplelog."; + + /** Properties loaded from simplelog.properties */ + static protected final Properties simpleLogProps = new Properties(); + + /** The default format to use when formatting dates */ + static protected final String DEFAULT_DATE_TIME_FORMAT = "yyyy/MM/dd HH:mm:ss:SSS zzz"; + + /** Include the instance name in the log message? */ + static protected boolean showLogName = false; + /** + * Include the short name ( last component ) of the logger in the log message. + * Defaults to true - otherwise we'll be lost in a flood of messages without + * knowing who sends them. + */ + static protected boolean showShortName = true; + /** Include the current time in the log message */ + static protected boolean showDateTime = false; + /** The date and time format to use in the log message */ + static protected String dateTimeFormat = DEFAULT_DATE_TIME_FORMAT; + /** Used to format times */ + static protected DateFormat dateFormatter = null; + + // ---------------------------------------------------- Log Level Constants + + /** "Trace" level logging. */ + public static final int LOG_LEVEL_TRACE = 1; + /** "Debug" level logging. */ + public static final int LOG_LEVEL_DEBUG = 2; + /** "Info" level logging. */ + public static final int LOG_LEVEL_INFO = 3; + /** "Warn" level logging. */ + public static final int LOG_LEVEL_WARN = 4; + /** "Error" level logging. */ + public static final int LOG_LEVEL_ERROR = 5; + /** "Fatal" level logging. */ + public static final int LOG_LEVEL_FATAL = 6; + + /** Enable all logging levels */ + public static final int LOG_LEVEL_ALL = (LOG_LEVEL_TRACE - 1); + + /** Enable no logging levels */ + public static final int LOG_LEVEL_OFF = (LOG_LEVEL_FATAL + 1); + + // ------------------------------------------------------------ Initializer + + private static String getStringProperty(String name) { + String prop = null; + try { + prop = System.getProperty(name); + } catch (SecurityException e) { + ; // Ignore + } + return (prop == null) ? simpleLogProps.getProperty(name) : prop; + } + + private static String getStringProperty(String name, String dephault) { + String prop = getStringProperty(name); + return (prop == null) ? dephault : prop; + } + + private static boolean getBooleanProperty(String name, boolean dephault) { + String prop = getStringProperty(name); + return (prop == null) ? dephault : "true".equalsIgnoreCase(prop); + } + + // Initialize class attributes. + // Load properties file, if found. + // Override with system properties. + static { + // Add props from the resource simplelog.properties + InputStream in = getResourceAsStream("simplelog.properties"); + if (null != in) { + try { + simpleLogProps.load(in); + } catch (java.io.IOException e) { + // ignored + } finally { + try { + in.close(); + } catch (java.io.IOException e) { + // ignored + } + } + } + + showLogName = getBooleanProperty(systemPrefix + "showlogname", showLogName); + showShortName = getBooleanProperty(systemPrefix + "showShortLogname", showShortName); + showDateTime = getBooleanProperty(systemPrefix + "showdatetime", showDateTime); + + if (showDateTime) { + dateTimeFormat = getStringProperty(systemPrefix + "dateTimeFormat", dateTimeFormat); + try { + dateFormatter = new SimpleDateFormat(dateTimeFormat); + } catch (IllegalArgumentException e) { + // If the format pattern is invalid - use the default format + dateTimeFormat = DEFAULT_DATE_TIME_FORMAT; + dateFormatter = new SimpleDateFormat(dateTimeFormat); + } + } + } + + // ------------------------------------------------------------- Attributes + + /** The name of this simple log instance */ + protected String logName = null; + /** The current log level */ + protected int currentLogLevel; + /** The short name of this simple log instance */ + private String shortLogName = null; + + // ------------------------------------------------------------ Constructor + + /** + * Construct a simple log with given name. + * + * @param name + * log name + */ + public SimpleLog(String name) { + + logName = name; + + // Set initial log level + // Used to be: set default log level to ERROR + // IMHO it should be lower, but at least info ( costin ). + setLevel(SimpleLog.LOG_LEVEL_INFO); + + // Set log level from properties + String lvl = getStringProperty(systemPrefix + "log." + logName); + int i = String.valueOf(name).lastIndexOf("."); + while (null == lvl && i > -1) { + name = name.substring(0, i); + lvl = getStringProperty(systemPrefix + "log." + name); + i = String.valueOf(name).lastIndexOf("."); + } + + if (null == lvl) { + lvl = getStringProperty(systemPrefix + "defaultlog"); + } + + if ("all".equalsIgnoreCase(lvl)) { + setLevel(SimpleLog.LOG_LEVEL_ALL); + } else if ("trace".equalsIgnoreCase(lvl)) { + setLevel(SimpleLog.LOG_LEVEL_TRACE); + } else if ("debug".equalsIgnoreCase(lvl)) { + setLevel(SimpleLog.LOG_LEVEL_DEBUG); + } else if ("info".equalsIgnoreCase(lvl)) { + setLevel(SimpleLog.LOG_LEVEL_INFO); + } else if ("warn".equalsIgnoreCase(lvl)) { + setLevel(SimpleLog.LOG_LEVEL_WARN); + } else if ("error".equalsIgnoreCase(lvl)) { + setLevel(SimpleLog.LOG_LEVEL_ERROR); + } else if ("fatal".equalsIgnoreCase(lvl)) { + setLevel(SimpleLog.LOG_LEVEL_FATAL); + } else if ("off".equalsIgnoreCase(lvl)) { + setLevel(SimpleLog.LOG_LEVEL_OFF); + } + + } + + // -------------------------------------------------------- Properties + + /** + *

+ * Set logging level. + *

+ * + * @param currentLogLevel + * new logging level + */ + public void setLevel(int currentLogLevel) { + + this.currentLogLevel = currentLogLevel; + + } + + /** + *

+ * Get logging level. + *

+ */ + public int getLevel() { + + return currentLogLevel; + } + + // -------------------------------------------------------- Logging Methods + + /** + *

+ * Do the actual logging. This method assembles the message and then calls + * write() to cause it to be written. + *

+ * + * @param type + * One of the LOG_LEVEL_XXX constants defining the log level + * @param message + * The message itself (typically a String) + * @param t + * The exception whose stack trace should be logged + */ + protected void log(int type, Object message, Throwable t) { + // Use a string buffer for better performance + StringBuffer buf = new StringBuffer(); + + // Append date-time if so configured + if (showDateTime) { + buf.append(dateFormatter.format(new Date())); + buf.append(" "); + } + + // Append a readable representation of the log level + switch (type) { + case SimpleLog.LOG_LEVEL_TRACE: + buf.append("[TRACE] "); + break; + case SimpleLog.LOG_LEVEL_DEBUG: + buf.append("[DEBUG] "); + break; + case SimpleLog.LOG_LEVEL_INFO: + buf.append("[INFO] "); + break; + case SimpleLog.LOG_LEVEL_WARN: + buf.append("[WARN] "); + break; + case SimpleLog.LOG_LEVEL_ERROR: + buf.append("[ERROR] "); + break; + case SimpleLog.LOG_LEVEL_FATAL: + buf.append("[FATAL] "); + break; + } + + // Append the name of the log instance if so configured + if (showShortName) { + if (shortLogName == null) { + // Cut all but the last component of the name for both styles + shortLogName = logName.substring(logName.lastIndexOf(".") + 1); + shortLogName = shortLogName.substring(shortLogName.lastIndexOf("/") + 1); + } + buf.append(String.valueOf(shortLogName)).append(" - "); + } else if (showLogName) { + buf.append(String.valueOf(logName)).append(" - "); + } + + // Append the message + buf.append(String.valueOf(message)); + + // Append stack trace if not null + if (t != null) { + buf.append(" <"); + buf.append(t.toString()); + buf.append(">"); + + java.io.StringWriter sw = new java.io.StringWriter(1024); + java.io.PrintWriter pw = new java.io.PrintWriter(sw); + t.printStackTrace(pw); + pw.close(); + buf.append(sw.toString()); + } + + // Print to the appropriate destination + write(buf); + + } + + /** + *

+ * Write the content of the message accumulated in the specified + * StringBuffer to the appropriate output destination. The + * default implementation writes to System.err. + *

+ * + * @param buffer + * A StringBuffer containing the accumulated text to be + * logged + */ + protected void write(StringBuffer buffer) { + + System.err.println(buffer.toString()); + + } + + /** + * Is the given log level currently enabled? + * + * @param logLevel + * is this level enabled? + */ + protected boolean isLevelEnabled(int logLevel) { + // log level are numerically ordered so can use simple numeric + // comparison + return (logLevel >= currentLogLevel); + } + + // -------------------------------------------------------- Log Implementation + + /** + *

+ * Log a message with debug log level. + *

+ */ + public final void debug(Object message) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) { + log(SimpleLog.LOG_LEVEL_DEBUG, message, null); + } + } + + /** + *

+ * Log an error with debug log level. + *

+ */ + public final void debug(Object message, Throwable t) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) { + log(SimpleLog.LOG_LEVEL_DEBUG, message, t); + } + } + + /** + *

+ * Log a message with trace log level. + *

+ */ + public final void trace(Object message) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) { + log(SimpleLog.LOG_LEVEL_TRACE, message, null); + } + } + + /** + *

+ * Log an error with trace log level. + *

+ */ + public final void trace(Object message, Throwable t) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) { + log(SimpleLog.LOG_LEVEL_TRACE, message, t); + } + } + + /** + *

+ * Log a message with info log level. + *

+ */ + public final void info(Object message) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) { + log(SimpleLog.LOG_LEVEL_INFO, message, null); + } + } + + /** + *

+ * Log an error with info log level. + *

+ */ + public final void info(Object message, Throwable t) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) { + log(SimpleLog.LOG_LEVEL_INFO, message, t); + } + } + + /** + *

+ * Log a message with warn log level. + *

+ */ + public final void warn(Object message) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) { + log(SimpleLog.LOG_LEVEL_WARN, message, null); + } + } + + /** + *

+ * Log an error with warn log level. + *

+ */ + public final void warn(Object message, Throwable t) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) { + log(SimpleLog.LOG_LEVEL_WARN, message, t); + } + } + + /** + *

+ * Log a message with error log level. + *

+ */ + public final void error(Object message) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) { + log(SimpleLog.LOG_LEVEL_ERROR, message, null); + } + } + + /** + *

+ * Log an error with error log level. + *

+ */ + public final void error(Object message, Throwable t) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) { + log(SimpleLog.LOG_LEVEL_ERROR, message, t); + } + } + + /** + *

+ * Log a message with fatal log level. + *

+ */ + public final void fatal(Object message) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) { + log(SimpleLog.LOG_LEVEL_FATAL, message, null); + } + } + + /** + *

+ * Log an error with fatal log level. + *

+ */ + public final void fatal(Object message, Throwable t) { + + if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) { + log(SimpleLog.LOG_LEVEL_FATAL, message, t); + } + } + + /** + *

+ * Are debug messages currently enabled? + *

+ * + *

+ * This allows expensive operations such as String concatenation + * to be avoided when the message will be ignored by the logger. + *

+ */ + public final boolean isDebugEnabled() { + + return isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG); + } + + /** + *

+ * Are error messages currently enabled? + *

+ * + *

+ * This allows expensive operations such as String concatenation + * to be avoided when the message will be ignored by the logger. + *

+ */ + public final boolean isErrorEnabled() { + + return isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR); + } + + /** + *

+ * Are fatal messages currently enabled? + *

+ * + *

+ * This allows expensive operations such as String concatenation + * to be avoided when the message will be ignored by the logger. + *

+ */ + public final boolean isFatalEnabled() { + + return isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL); + } + + /** + *

+ * Are info messages currently enabled? + *

+ * + *

+ * This allows expensive operations such as String concatenation + * to be avoided when the message will be ignored by the logger. + *

+ */ + public final boolean isInfoEnabled() { + + return isLevelEnabled(SimpleLog.LOG_LEVEL_INFO); + } + + /** + *

+ * Are trace messages currently enabled? + *

+ * + *

+ * This allows expensive operations such as String concatenation + * to be avoided when the message will be ignored by the logger. + *

+ */ + public final boolean isTraceEnabled() { + + return isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE); + } + + /** + *

+ * Are warn messages currently enabled? + *

+ * + *

+ * This allows expensive operations such as String concatenation + * to be avoided when the message will be ignored by the logger. + *

+ */ + public final boolean isWarnEnabled() { + + return isLevelEnabled(SimpleLog.LOG_LEVEL_WARN); + } + + /** + * Return the thread context class loader if available. Otherwise return null. + * + * The thread context class loader is available for JDK 1.2 or later, if + * certain security conditions are met. + * + * @exception LogConfigurationException + * if a suitable class loader cannot be identified. + */ + private static ClassLoader getContextClassLoader() { + ClassLoader classLoader = null; + + if (classLoader == null) { + try { + // Are we running on a JDK 1.2 or later system? + Method method = Thread.class.getMethod("getContextClassLoader"); + + // Get the thread context class loader (if there is one) + try { + classLoader = (ClassLoader) method.invoke(Thread.currentThread()); + } catch (IllegalAccessException e) { + ; // ignore + } catch (InvocationTargetException e) { + /** + * InvocationTargetException is thrown by 'invoke' when the method + * being invoked (getContextClassLoader) throws an exception. + * + * getContextClassLoader() throws SecurityException when the context + * class loader isn't an ancestor of the calling class's class loader, + * or if security permissions are restricted. + * + * In the first case (not related), we want to ignore and keep going. + * We cannot help but also ignore the second with the logic below, but + * other calls elsewhere (to obtain a class loader) will trigger this + * exception where we can make a distinction. + */ + if (e.getTargetException() instanceof SecurityException) { + ; // ignore + } else { + // Capture 'e.getTargetException()' exception for details + // alternate: log 'e.getTargetException()', and pass back 'e'. + throw new LogConfigurationException("Unexpected InvocationTargetException", e.getTargetException()); + } + } + } catch (NoSuchMethodException e) { + // Assume we are running on JDK 1.1 + ; // ignore + } + } + + if (classLoader == null) { + classLoader = SimpleLog.class.getClassLoader(); + } + + // Return the selected class loader + return classLoader; + } + + private static InputStream getResourceAsStream(final String name) { + return AccessController.doPrivileged(new PrivilegedAction() { + public InputStream run() { + ClassLoader threadCL = getContextClassLoader(); + + if (threadCL != null) { + return threadCL.getResourceAsStream(name); + } else { + return ClassLoader.getSystemResourceAsStream(name); + } + } + }); + } +} diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/package.html b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/package.html index 128d15f..ec177dd 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/package.html +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/package.html @@ -1,5 +1,5 @@ - - -

SLF4J based implementation of commons-logging wrapper APIs.

- - + + +

SLF4J based implementation of commons-logging wrapper APIs.

+ + diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/package.html b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/package.html old file mode 100644 new file mode 100755 index 735d6cf..014e85a 100755 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/package.html +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/package.html @@ -1,169 +1,169 @@ - - - -

Jakarta Commons Logging implemented over SLF4J.

- - -

Overview

- -

This package contains the same public user interface as Jakarta Commons -Logging (JCL). It is intended as a 100% compatible drop-in -replacement for the original JCL version 1.0.4. -

- -

As the original JCL version 1.0.4, the present version supports -various logging APIs. It differs from the original in implementation -but not the public API. This implementation uses SLF4J under the -covers. As as such, all the logging systems that SLF4J supports, -e.g. NOP, Simple, JDK14, nlog4j are supported by this version of JCL. -

- -

Quick Start Guide

- -

For those impatient to just get on with it, the following example -illustrates the typical declaration and use of a logger that is named (by -convention) after the calling class: - -

-    import org.apache.commons.logging.Log;
-    import org.apache.commons.logging.LogFactory;
-
-    public class Foo {
-
-        static Log log = LogFactory.getLog(Foo.class);
-
-        public void foo() {
-            ...
-            try {
-                if (log.isDebugEnabled()) {
-                    log.debug("About to do something to object " + name);
-                }
-                name.bar();
-            } catch (IllegalStateException e) {
-                log.error("Something bad happened to " + name, e);
-            }
-            ...
-        }
-
- -

Configuring the Commons Logging Package

- -

In this version of JCL, the selection of the logging system to use -is chosen by the underlying SLF4J API. Consequently, all JCL-specific -configuration parameters are ignored. -

- -

Choosing a LogFactory Implementation

- -

From an application perspective, the first requirement is to -retrieve an object reference to the LogFactory instance -that will be used to create Log -instances for this application. This is normally accomplished by -calling the static getFactory() method. This method -always returns the same factory, i.e. a unique instance of the SLF4FLogFactory class. -

- - - -

Configuring the Underlying Logging System

- -

The basic principle is that the user is totally responsible for the -configuration of the underlying logging system. -Commons-logging should not change the existing configuration.

- -

Each individual Log implementation may -support its own configuration properties. These will be documented in the -class descriptions for the corresponding implementation class.

- -

Finally, some Log implementations (such as the one for Log4J) -require an external configuration file for the entire logging environment. -This file should be prepared in a manner that is specific to the actual logging -technology being used.

- - -

Using the Logging Package APIs

- -

Use of the Logging Package APIs, from the perspective of an application -component, consists of the following steps:

-
    -
  1. Acquire a reference to an instance of - org.apache.commons.logging.Log, by calling the - factory method - - LogFactory.getInstance(String name). Your application can contain - references to multiple loggers that are used for different - purposes. A typical scenario for a server application is to have each - major component of the server use its own Log instance.
  2. -
  3. Cause messages to be logged (if the corresponding detail level is enabled) - by calling appropriate methods (trace(), debug(), - info(), warn(), error, and - fatal()).
  4. -
- -

For convenience, LogFactory also offers a static method -getLog() that combines the typical two-step pattern:

-
-  Log log = LogFactory.getFactory().getInstance(Foo.class);
-
-

into a single method call:

-
-  Log log = LogFactory.getLog(Foo.class);
-
- -

For example, you might use the following technique to initialize and -use a Log instance in an application component:

-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class MyComponent {
-
-  protected static Log log =
-    LogFactory.getLog(MyComponent.class);
-
-  // Called once at startup time
-  public void start() {
-    ...
-    log.info("MyComponent started");
-    ...
-  }
-
-  // Called once at shutdown time
-  public void stop() {
-    ...
-    log.info("MyComponent stopped");
-    ...
-  }
-
-  // Called repeatedly to process a particular argument value
-  // which you want logged if debugging is enabled
-  public void process(String value) {
-    ...
-    // Do the string concatenation only if logging is enabled
-    if (log.isDebugEnabled())
-      log.debug("MyComponent processing " + value);
-    ...
-  }
-
-}
-
- - + + + +

Jakarta Commons Logging implemented over SLF4J.

+ + +

Overview

+ +

This package contains the same public user interface as Jakarta Commons +Logging (JCL). It is intended as a 100% compatible drop-in +replacement for the original JCL version 1.0.4. +

+ +

As the original JCL version 1.0.4, the present version supports +various logging APIs. It differs from the original in implementation +but not the public API. This implementation uses SLF4J under the +covers. As as such, all the logging systems that SLF4J supports, +e.g. NOP, Simple, JDK14, nlog4j are supported by this version of JCL. +

+ +

Quick Start Guide

+ +

For those impatient to just get on with it, the following example +illustrates the typical declaration and use of a logger that is named (by +convention) after the calling class: + +

+    import org.apache.commons.logging.Log;
+    import org.apache.commons.logging.LogFactory;
+
+    public class Foo {
+
+        static Log log = LogFactory.getLog(Foo.class);
+
+        public void foo() {
+            ...
+            try {
+                if (log.isDebugEnabled()) {
+                    log.debug("About to do something to object " + name);
+                }
+                name.bar();
+            } catch (IllegalStateException e) {
+                log.error("Something bad happened to " + name, e);
+            }
+            ...
+        }
+
+ +

Configuring the Commons Logging Package

+ +

In this version of JCL, the selection of the logging system to use +is chosen by the underlying SLF4J API. Consequently, all JCL-specific +configuration parameters are ignored. +

+ +

Choosing a LogFactory Implementation

+ +

From an application perspective, the first requirement is to +retrieve an object reference to the LogFactory instance +that will be used to create Log +instances for this application. This is normally accomplished by +calling the static getFactory() method. This method +always returns the same factory, i.e. a unique instance of the SLF4FLogFactory class. +

+ + + +

Configuring the Underlying Logging System

+ +

The basic principle is that the user is totally responsible for the +configuration of the underlying logging system. +Commons-logging should not change the existing configuration.

+ +

Each individual Log implementation may +support its own configuration properties. These will be documented in the +class descriptions for the corresponding implementation class.

+ +

Finally, some Log implementations (such as the one for Log4J) +require an external configuration file for the entire logging environment. +This file should be prepared in a manner that is specific to the actual logging +technology being used.

+ + +

Using the Logging Package APIs

+ +

Use of the Logging Package APIs, from the perspective of an application +component, consists of the following steps:

+
    +
  1. Acquire a reference to an instance of + org.apache.commons.logging.Log, by calling the + factory method + + LogFactory.getInstance(String name). Your application can contain + references to multiple loggers that are used for different + purposes. A typical scenario for a server application is to have each + major component of the server use its own Log instance.
  2. +
  3. Cause messages to be logged (if the corresponding detail level is enabled) + by calling appropriate methods (trace(), debug(), + info(), warn(), error, and + fatal()).
  4. +
+ +

For convenience, LogFactory also offers a static method +getLog() that combines the typical two-step pattern:

+
+  Log log = LogFactory.getFactory().getInstance(Foo.class);
+
+

into a single method call:

+
+  Log log = LogFactory.getLog(Foo.class);
+
+ +

For example, you might use the following technique to initialize and +use a Log instance in an application component:

+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class MyComponent {
+
+  protected static Log log =
+    LogFactory.getLog(MyComponent.class);
+
+  // Called once at startup time
+  public void start() {
+    ...
+    log.info("MyComponent started");
+    ...
+  }
+
+  // Called once at shutdown time
+  public void stop() {
+    ...
+    log.info("MyComponent stopped");
+    ...
+  }
+
+  // Called repeatedly to process a particular argument value
+  // which you want logged if debugging is enabled
+  public void process(String value) {
+    ...
+    // Do the string concatenation only if logging is enabled
+    if (log.isDebugEnabled())
+      log.debug("MyComponent processing " + value);
+    ...
+  }
+
+}
+
+ + diff --git a/jcl-over-slf4j/src/main/resources/META-INF/MANIFEST.MF b/jcl-over-slf4j/src/main/resources/META-INF/MANIFEST.MF old file mode 100644 new file mode 100755 index ae8f969..bb1d43e 100755 --- a/jcl-over-slf4j/src/main/resources/META-INF/MANIFEST.MF +++ b/jcl-over-slf4j/src/main/resources/META-INF/MANIFEST.MF @@ -1,9 +1,9 @@ -Implementation-Title: jcl-over-slf4j -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: jcl.over.slf4j -Bundle-Name: jcl-over-slf4j -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.apache.commons.logging;version=1.2, - org.apache.commons.logging.impl;version=1.2 -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion} +Implementation-Title: jcl-over-slf4j +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: jcl.over.slf4j +Bundle-Name: jcl-over-slf4j +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.apache.commons.logging;version=1.2, + org.apache.commons.logging.impl;version=1.2 +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion} diff --git a/jcl-over-slf4j/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory b/jcl-over-slf4j/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory index 50a7c3b..8cece6f 100644 --- a/jcl-over-slf4j/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory +++ b/jcl-over-slf4j/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory @@ -1,5 +1,5 @@ -org.apache.commons.logging.impl.SLF4JLogFactory - -# Axis gets at JCL through its own mechanism as defined by Commons Discovery, which -# in turn follows the instructions found at: -# http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service Provider +org.apache.commons.logging.impl.SLF4JLogFactory + +# Axis gets at JCL through its own mechanism as defined by Commons Discovery, which +# in turn follows the instructions found at: +# http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service Provider diff --git a/jcl-over-slf4j/src/test/java/org/apache/commons/logging/InvokeJCLTest.java b/jcl-over-slf4j/src/test/java/org/apache/commons/logging/InvokeJCLTest.java index f75240a..1cef216 100644 --- a/jcl-over-slf4j/src/test/java/org/apache/commons/logging/InvokeJCLTest.java +++ b/jcl-over-slf4j/src/test/java/org/apache/commons/logging/InvokeJCLTest.java @@ -1,88 +1,88 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -package org.apache.commons.logging; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class InvokeJCLTest { - - @Test - public void testIsEnabledAPI() { - // assume that we are running over slf4j-jdk14 - Log log = LogFactory.getLog(InvokeJCLTest.class); - assertFalse(log.isTraceEnabled()); - assertFalse(log.isDebugEnabled()); - assertTrue(log.isInfoEnabled()); - assertTrue(log.isWarnEnabled()); - assertTrue(log.isErrorEnabled()); - assertTrue(log.isFatalEnabled()); - } - - @Test - public void testPrintAPI() { - Log log = LogFactory.getLog(InvokeJCLTest.class); - Exception e = new Exception("just testing"); - - log.trace(null); - log.trace("trace message"); - - log.debug(null); - log.debug("debug message"); - - log.info(null); - log.info("info message"); - - log.warn(null); - log.warn("warn message"); - - log.error(null); - log.error("error message"); - - log.fatal(null); - log.fatal("fatal message"); - - log.trace(null, e); - log.trace("trace message", e); - - log.debug(null, e); - log.debug("debug message", e); - - log.info(null, e); - log.info("info message", e); - - log.warn(null, e); - log.warn("warn message", e); - - log.error(null, e); - log.error("error message", e); - - log.fatal(null, e); - log.fatal("fatal message", e); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +package org.apache.commons.logging; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class InvokeJCLTest { + + @Test + public void testIsEnabledAPI() { + // assume that we are running over slf4j-jdk14 + Log log = LogFactory.getLog(InvokeJCLTest.class); + assertFalse(log.isTraceEnabled()); + assertFalse(log.isDebugEnabled()); + assertTrue(log.isInfoEnabled()); + assertTrue(log.isWarnEnabled()); + assertTrue(log.isErrorEnabled()); + assertTrue(log.isFatalEnabled()); + } + + @Test + public void testPrintAPI() { + Log log = LogFactory.getLog(InvokeJCLTest.class); + Exception e = new Exception("just testing"); + + log.trace(null); + log.trace("trace message"); + + log.debug(null); + log.debug("debug message"); + + log.info(null); + log.info("info message"); + + log.warn(null); + log.warn("warn message"); + + log.error(null); + log.error("error message"); + + log.fatal(null); + log.fatal("fatal message"); + + log.trace(null, e); + log.trace("trace message", e); + + log.debug(null, e); + log.debug("debug message", e); + + log.info(null, e); + log.info("info message", e); + + log.warn(null, e); + log.warn("warn message", e); + + log.error(null, e); + log.error("error message", e); + + log.fatal(null, e); + log.fatal("fatal message", e); + } +} diff --git a/jcl-over-slf4j/src/test/java/org/apache/commons/logging/impl/SerializationTest.java b/jcl-over-slf4j/src/test/java/org/apache/commons/logging/impl/SerializationTest.java index d0e6a20..4b67861 100644 --- a/jcl-over-slf4j/src/test/java/org/apache/commons/logging/impl/SerializationTest.java +++ b/jcl-over-slf4j/src/test/java/org/apache/commons/logging/impl/SerializationTest.java @@ -1,89 +1,89 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.apache.commons.logging.impl; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.impl.JDK14LoggerFactory; -import org.slf4j.spi.LocationAwareLogger; - -public class SerializationTest { - - ObjectInputStream ois; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos; - - @Before - public void setUp() throws Exception { - oos = new ObjectOutputStream(baos); - } - - @After - public void tearDown() throws Exception { - oos.close(); - } - - public void verify() throws IOException, ClassNotFoundException { - ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray()); - ois = new ObjectInputStream(bis); - - Log resuscitatedLog = (Log) ois.readObject(); - // tests that the "private transient Logger logger" field is non-null - resuscitatedLog.debug(""); - resuscitatedLog.isDebugEnabled(); - } - - @Test - public void testSLF4JLog() throws Exception { - JDK14LoggerFactory factory = new JDK14LoggerFactory(); - SLF4JLog log = new SLF4JLog(factory.getLogger("x")); - oos.writeObject(log); - verify(); - } - - @Test - public void testSmoke() throws Exception { - Log log = LogFactory.getLog("testing"); - oos.writeObject(log); - verify(); - } - - @Test - public void testLocationAware() throws Exception { - JDK14LoggerFactory factory = new JDK14LoggerFactory(); - SLF4JLocationAwareLog log = new SLF4JLocationAwareLog((LocationAwareLogger) factory.getLogger("x")); - oos.writeObject(log); - verify(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.apache.commons.logging.impl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.impl.JDK14LoggerFactory; +import org.slf4j.spi.LocationAwareLogger; + +public class SerializationTest { + + ObjectInputStream ois; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos; + + @Before + public void setUp() throws Exception { + oos = new ObjectOutputStream(baos); + } + + @After + public void tearDown() throws Exception { + oos.close(); + } + + public void verify() throws IOException, ClassNotFoundException { + ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray()); + ois = new ObjectInputStream(bis); + + Log resuscitatedLog = (Log) ois.readObject(); + // tests that the "private transient Logger logger" field is non-null + resuscitatedLog.debug(""); + resuscitatedLog.isDebugEnabled(); + } + + @Test + public void testSLF4JLog() throws Exception { + JDK14LoggerFactory factory = new JDK14LoggerFactory(); + SLF4JLog log = new SLF4JLog(factory.getLogger("x")); + oos.writeObject(log); + verify(); + } + + @Test + public void testSmoke() throws Exception { + Log log = LogFactory.getLog("testing"); + oos.writeObject(log); + verify(); + } + + @Test + public void testLocationAware() throws Exception { + JDK14LoggerFactory factory = new JDK14LoggerFactory(); + SLF4JLocationAwareLog log = new SLF4JLocationAwareLog((LocationAwareLogger) factory.getLogger("x")); + oos.writeObject(log); + verify(); + } +} diff --git a/jul-to-slf4j/pom.xml b/jul-to-slf4j/pom.xml old file mode 100644 new file mode 100755 index d9ed8c5..9f1c8b2 100755 --- a/jul-to-slf4j/pom.xml +++ b/jul-to-slf4j/pom.xml @@ -1,34 +1,34 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - jul-to-slf4j - - jar - JUL to SLF4J bridge - JUL to SLF4J bridge - - http://www.slf4j.org - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - ${project.version} - test - - - - \ No newline at end of file + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + jul-to-slf4j + + jar + JUL to SLF4J bridge + JUL to SLF4J bridge + + http://www.slf4j.org + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + ${project.version} + test + + + + diff --git a/jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java b/jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java old file mode 100644 new file mode 100755 index fe62f19..8e125cf 100755 --- a/jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java +++ b/jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java @@ -1,309 +1,309 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.bridge; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.LogRecord; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LocationAwareLogger; - -// Based on http://jira.qos.ch/browse/SLF4J-30 - -/** - *

Bridge/route all JUL log records to the SLF4J API.

- *

Essentially, the idea is to install on the root logger an instance of - * SLF4JBridgeHandler as the sole JUL handler in the system. Subsequently, the - * SLF4JBridgeHandler instance will redirect all JUL log records are redirected - * to the SLF4J API based on the following mapping of levels: - *

- *
- * FINEST  -> TRACE
- * FINER   -> DEBUG
- * FINE    -> DEBUG
- * INFO    -> INFO
- * WARNING -> WARN
- * SEVERE  -> ERROR
- *

Programmatic installation:

- *
- * // Optionally remove existing handlers attached to j.u.l root logger
- * SLF4JBridgeHandler.removeHandlersForRootLogger();  // (since SLF4J 1.6.5)
-
- * // add SLF4JBridgeHandler to j.u.l's root logger, should be done once during
- * // the initialization phase of your application
- * SLF4JBridgeHandler.install();
- *

Installation via logging.properties configuration file:

- *
- * // register SLF4JBridgeHandler as handler for the j.u.l. root logger
- * handlers = org.slf4j.bridge.SLF4JBridgeHandler
- *

Once SLF4JBridgeHandler is installed, logging by j.u.l. loggers will be directed to - * SLF4J. Example:

- *
- * import  java.util.logging.Logger;
- * ...
- * // usual pattern: get a Logger and then log a message
- * Logger julLogger = Logger.getLogger("org.wombat");
- * julLogger.fine("hello world"); // this will get redirected to SLF4J
- * - *

Please note that translating a java.util.logging event into SLF4J incurs the - * cost of constructing {@link LogRecord} instance regardless of whether the - * SLF4J logger is disabled for the given level. Consequently, j.u.l. to - * SLF4J translation can seriously increase the cost of disabled logging - * statements (60 fold or 6000% increase) and measurably impact the performance of enabled log - * statements (20% overall increase). Please note that as of logback-version 0.9.25, - * it is possible to completely eliminate the 60 fold translation overhead for disabled - * log statements with the help of LevelChangePropagator. - *

- * - *

If you are concerned about application performance, then use of SLF4JBridgeHandler - * is appropriate only if any one the following two conditions is true:

- *
    - *
  1. few j.u.l. logging statements are in play
  2. - *
  3. LevelChangePropagator has been installed
  4. - *
- * - * @author Christian Stein - * @author Joern Huxhorn - * @author Ceki Gülcü - * @author Darryl Smith - * @since 1.5.1 - */ -public class SLF4JBridgeHandler extends Handler { - - // The caller is java.util.logging.Logger - private static final String FQCN = java.util.logging.Logger.class.getName(); - private static final String UNKNOWN_LOGGER_NAME = "unknown.jul.logger"; - - private static final int TRACE_LEVEL_THRESHOLD = Level.FINEST.intValue(); - private static final int DEBUG_LEVEL_THRESHOLD = Level.FINE.intValue(); - private static final int INFO_LEVEL_THRESHOLD = Level.INFO.intValue(); - private static final int WARN_LEVEL_THRESHOLD = Level.WARNING.intValue(); - - /** - * Adds a SLF4JBridgeHandler instance to jul's root logger. - *

- *

- * This handler will redirect j.u.l. logging to SLF4J. However, only logs enabled - * in j.u.l. will be redirected. For example, if a log statement invoking a - * j.u.l. logger is disabled, then the corresponding non-event will not - * reach SLF4JBridgeHandler and cannot be redirected. - */ - public static void install() { - LogManager.getLogManager().getLogger("").addHandler(new SLF4JBridgeHandler()); - } - - private static java.util.logging.Logger getRootLogger() { - return LogManager.getLogManager().getLogger(""); - } - - /** - * Removes previously installed SLF4JBridgeHandler instances. See also - * {@link #install()}. - * - * @throws SecurityException A SecurityException is thrown, if a security manager - * exists and if the caller does not have - * LoggingPermission("control"). - */ - public static void uninstall() throws SecurityException { - java.util.logging.Logger rootLogger = getRootLogger(); - Handler[] handlers = rootLogger.getHandlers(); - for (int i = 0; i < handlers.length; i++) { - if (handlers[i] instanceof SLF4JBridgeHandler) { - rootLogger.removeHandler(handlers[i]); - } - } - } - - /** - * Returns true if SLF4JBridgeHandler has been previously installed, returns false otherwise. - * - * @return true if SLF4JBridgeHandler is already installed, false other wise - * @throws SecurityException - */ - public static boolean isInstalled() throws SecurityException { - java.util.logging.Logger rootLogger = getRootLogger(); - Handler[] handlers = rootLogger.getHandlers(); - for (int i = 0; i < handlers.length; i++) { - if (handlers[i] instanceof SLF4JBridgeHandler) { - return true; - } - } - return false; - } - - /** - * Invoking this method removes/unregisters/detaches all handlers currently attached to the root logger - * @since 1.6.5 - */ - public static void removeHandlersForRootLogger() { - java.util.logging.Logger rootLogger = getRootLogger(); - java.util.logging.Handler[] handlers = rootLogger.getHandlers(); - for (int i = 0; i < handlers.length; i++) { - rootLogger.removeHandler(handlers[i]); - } - } - - /** - * Initialize this handler. - */ - public SLF4JBridgeHandler() { - } - - /** - * No-op implementation. - */ - public void close() { - // empty - } - - /** - * No-op implementation. - */ - public void flush() { - // empty - } - - /** - * Return the Logger instance that will be used for logging. - */ - protected Logger getSLF4JLogger(LogRecord record) { - String name = record.getLoggerName(); - if (name == null) { - name = UNKNOWN_LOGGER_NAME; - } - return LoggerFactory.getLogger(name); - } - - protected void callLocationAwareLogger(LocationAwareLogger lal, LogRecord record) { - int julLevelValue = record.getLevel().intValue(); - int slf4jLevel; - - if (julLevelValue <= TRACE_LEVEL_THRESHOLD) { - slf4jLevel = LocationAwareLogger.TRACE_INT; - } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) { - slf4jLevel = LocationAwareLogger.DEBUG_INT; - } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) { - slf4jLevel = LocationAwareLogger.INFO_INT; - } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) { - slf4jLevel = LocationAwareLogger.WARN_INT; - } else { - slf4jLevel = LocationAwareLogger.ERROR_INT; - } - String i18nMessage = getMessageI18N(record); - lal.log(null, FQCN, slf4jLevel, i18nMessage, null, record.getThrown()); - } - - protected void callPlainSLF4JLogger(Logger slf4jLogger, LogRecord record) { - String i18nMessage = getMessageI18N(record); - int julLevelValue = record.getLevel().intValue(); - if (julLevelValue <= TRACE_LEVEL_THRESHOLD) { - slf4jLogger.trace(i18nMessage, record.getThrown()); - } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) { - slf4jLogger.debug(i18nMessage, record.getThrown()); - } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) { - slf4jLogger.info(i18nMessage, record.getThrown()); - } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) { - slf4jLogger.warn(i18nMessage, record.getThrown()); - } else { - slf4jLogger.error(i18nMessage, record.getThrown()); - } - } - - /** - * Get the record's message, possibly via a resource bundle. - * - * @param record - * @return - */ - private String getMessageI18N(LogRecord record) { - String message = record.getMessage(); - - if (message == null) { - return null; - } - - ResourceBundle bundle = record.getResourceBundle(); - if (bundle != null) { - try { - message = bundle.getString(message); - } catch (MissingResourceException e) { - } - } - Object[] params = record.getParameters(); - // avoid formatting when there are no or 0 parameters. see also - // http://jira.qos.ch/browse/SLF4J-203 - if (params != null && params.length > 0) { - try { - message = MessageFormat.format(message, params); - } catch (IllegalArgumentException e) { - // default to the same behavior as in java.util.logging.Formatter.formatMessage(LogRecord) - // see also http://jira.qos.ch/browse/SLF4J-337 - return message; - } - } - return message; - } - - /** - * Publish a LogRecord. - *

- * The logging request was made initially to a Logger object, which - * initialized the LogRecord and forwarded it here. - *

- * This handler ignores the Level attached to the LogRecord, as SLF4J cares - * about discarding log statements. - * - * @param record Description of the log event. A null record is silently ignored - * and is not published. - */ - public void publish(LogRecord record) { - // Silently ignore null records. - if (record == null) { - return; - } - - Logger slf4jLogger = getSLF4JLogger(record); - String message = record.getMessage(); // can be null! - // this is a check to avoid calling the underlying logging system - // with a null message. While it is legitimate to invoke j.u.l. with - // a null message, other logging frameworks do not support this. - // see also http://jira.qos.ch/browse/SLF4J-99 - if (message == null) { - message = ""; - } - if (slf4jLogger instanceof LocationAwareLogger) { - callLocationAwareLogger((LocationAwareLogger) slf4jLogger, record); - } else { - callPlainSLF4JLogger(slf4jLogger, record); - } - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.bridge; + +import java.text.MessageFormat; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogManager; +import java.util.logging.LogRecord; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LocationAwareLogger; + +// Based on http://jira.qos.ch/browse/SLF4J-30 + +/** + *

Bridge/route all JUL log records to the SLF4J API.

+ *

Essentially, the idea is to install on the root logger an instance of + * SLF4JBridgeHandler as the sole JUL handler in the system. Subsequently, the + * SLF4JBridgeHandler instance will redirect all JUL log records are redirected + * to the SLF4J API based on the following mapping of levels: + *

+ *
+ * FINEST  -> TRACE
+ * FINER   -> DEBUG
+ * FINE    -> DEBUG
+ * INFO    -> INFO
+ * WARNING -> WARN
+ * SEVERE  -> ERROR
+ *

Programmatic installation:

+ *
+ * // Optionally remove existing handlers attached to j.u.l root logger
+ * SLF4JBridgeHandler.removeHandlersForRootLogger();  // (since SLF4J 1.6.5)
+
+ * // add SLF4JBridgeHandler to j.u.l's root logger, should be done once during
+ * // the initialization phase of your application
+ * SLF4JBridgeHandler.install();
+ *

Installation via logging.properties configuration file:

+ *
+ * // register SLF4JBridgeHandler as handler for the j.u.l. root logger
+ * handlers = org.slf4j.bridge.SLF4JBridgeHandler
+ *

Once SLF4JBridgeHandler is installed, logging by j.u.l. loggers will be directed to + * SLF4J. Example:

+ *
+ * import  java.util.logging.Logger;
+ * ...
+ * // usual pattern: get a Logger and then log a message
+ * Logger julLogger = Logger.getLogger("org.wombat");
+ * julLogger.fine("hello world"); // this will get redirected to SLF4J
+ * + *

Please note that translating a java.util.logging event into SLF4J incurs the + * cost of constructing {@link LogRecord} instance regardless of whether the + * SLF4J logger is disabled for the given level. Consequently, j.u.l. to + * SLF4J translation can seriously increase the cost of disabled logging + * statements (60 fold or 6000% increase) and measurably impact the performance of enabled log + * statements (20% overall increase). Please note that as of logback-version 0.9.25, + * it is possible to completely eliminate the 60 fold translation overhead for disabled + * log statements with the help of LevelChangePropagator. + *

+ * + *

If you are concerned about application performance, then use of SLF4JBridgeHandler + * is appropriate only if any one the following two conditions is true:

+ *
    + *
  1. few j.u.l. logging statements are in play
  2. + *
  3. LevelChangePropagator has been installed
  4. + *
+ * + * @author Christian Stein + * @author Joern Huxhorn + * @author Ceki Gülcü + * @author Darryl Smith + * @since 1.5.1 + */ +public class SLF4JBridgeHandler extends Handler { + + // The caller is java.util.logging.Logger + private static final String FQCN = java.util.logging.Logger.class.getName(); + private static final String UNKNOWN_LOGGER_NAME = "unknown.jul.logger"; + + private static final int TRACE_LEVEL_THRESHOLD = Level.FINEST.intValue(); + private static final int DEBUG_LEVEL_THRESHOLD = Level.FINE.intValue(); + private static final int INFO_LEVEL_THRESHOLD = Level.INFO.intValue(); + private static final int WARN_LEVEL_THRESHOLD = Level.WARNING.intValue(); + + /** + * Adds a SLF4JBridgeHandler instance to jul's root logger. + *

+ *

+ * This handler will redirect j.u.l. logging to SLF4J. However, only logs enabled + * in j.u.l. will be redirected. For example, if a log statement invoking a + * j.u.l. logger is disabled, then the corresponding non-event will not + * reach SLF4JBridgeHandler and cannot be redirected. + */ + public static void install() { + LogManager.getLogManager().getLogger("").addHandler(new SLF4JBridgeHandler()); + } + + private static java.util.logging.Logger getRootLogger() { + return LogManager.getLogManager().getLogger(""); + } + + /** + * Removes previously installed SLF4JBridgeHandler instances. See also + * {@link #install()}. + * + * @throws SecurityException A SecurityException is thrown, if a security manager + * exists and if the caller does not have + * LoggingPermission("control"). + */ + public static void uninstall() throws SecurityException { + java.util.logging.Logger rootLogger = getRootLogger(); + Handler[] handlers = rootLogger.getHandlers(); + for (int i = 0; i < handlers.length; i++) { + if (handlers[i] instanceof SLF4JBridgeHandler) { + rootLogger.removeHandler(handlers[i]); + } + } + } + + /** + * Returns true if SLF4JBridgeHandler has been previously installed, returns false otherwise. + * + * @return true if SLF4JBridgeHandler is already installed, false other wise + * @throws SecurityException + */ + public static boolean isInstalled() throws SecurityException { + java.util.logging.Logger rootLogger = getRootLogger(); + Handler[] handlers = rootLogger.getHandlers(); + for (int i = 0; i < handlers.length; i++) { + if (handlers[i] instanceof SLF4JBridgeHandler) { + return true; + } + } + return false; + } + + /** + * Invoking this method removes/unregisters/detaches all handlers currently attached to the root logger + * @since 1.6.5 + */ + public static void removeHandlersForRootLogger() { + java.util.logging.Logger rootLogger = getRootLogger(); + java.util.logging.Handler[] handlers = rootLogger.getHandlers(); + for (int i = 0; i < handlers.length; i++) { + rootLogger.removeHandler(handlers[i]); + } + } + + /** + * Initialize this handler. + */ + public SLF4JBridgeHandler() { + } + + /** + * No-op implementation. + */ + public void close() { + // empty + } + + /** + * No-op implementation. + */ + public void flush() { + // empty + } + + /** + * Return the Logger instance that will be used for logging. + */ + protected Logger getSLF4JLogger(LogRecord record) { + String name = record.getLoggerName(); + if (name == null) { + name = UNKNOWN_LOGGER_NAME; + } + return LoggerFactory.getLogger(name); + } + + protected void callLocationAwareLogger(LocationAwareLogger lal, LogRecord record) { + int julLevelValue = record.getLevel().intValue(); + int slf4jLevel; + + if (julLevelValue <= TRACE_LEVEL_THRESHOLD) { + slf4jLevel = LocationAwareLogger.TRACE_INT; + } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) { + slf4jLevel = LocationAwareLogger.DEBUG_INT; + } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) { + slf4jLevel = LocationAwareLogger.INFO_INT; + } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) { + slf4jLevel = LocationAwareLogger.WARN_INT; + } else { + slf4jLevel = LocationAwareLogger.ERROR_INT; + } + String i18nMessage = getMessageI18N(record); + lal.log(null, FQCN, slf4jLevel, i18nMessage, null, record.getThrown()); + } + + protected void callPlainSLF4JLogger(Logger slf4jLogger, LogRecord record) { + String i18nMessage = getMessageI18N(record); + int julLevelValue = record.getLevel().intValue(); + if (julLevelValue <= TRACE_LEVEL_THRESHOLD) { + slf4jLogger.trace(i18nMessage, record.getThrown()); + } else if (julLevelValue <= DEBUG_LEVEL_THRESHOLD) { + slf4jLogger.debug(i18nMessage, record.getThrown()); + } else if (julLevelValue <= INFO_LEVEL_THRESHOLD) { + slf4jLogger.info(i18nMessage, record.getThrown()); + } else if (julLevelValue <= WARN_LEVEL_THRESHOLD) { + slf4jLogger.warn(i18nMessage, record.getThrown()); + } else { + slf4jLogger.error(i18nMessage, record.getThrown()); + } + } + + /** + * Get the record's message, possibly via a resource bundle. + * + * @param record + * @return + */ + private String getMessageI18N(LogRecord record) { + String message = record.getMessage(); + + if (message == null) { + return null; + } + + ResourceBundle bundle = record.getResourceBundle(); + if (bundle != null) { + try { + message = bundle.getString(message); + } catch (MissingResourceException e) { + } + } + Object[] params = record.getParameters(); + // avoid formatting when there are no or 0 parameters. see also + // http://jira.qos.ch/browse/SLF4J-203 + if (params != null && params.length > 0) { + try { + message = MessageFormat.format(message, params); + } catch (IllegalArgumentException e) { + // default to the same behavior as in java.util.logging.Formatter.formatMessage(LogRecord) + // see also http://jira.qos.ch/browse/SLF4J-337 + return message; + } + } + return message; + } + + /** + * Publish a LogRecord. + *

+ * The logging request was made initially to a Logger object, which + * initialized the LogRecord and forwarded it here. + *

+ * This handler ignores the Level attached to the LogRecord, as SLF4J cares + * about discarding log statements. + * + * @param record Description of the log event. A null record is silently ignored + * and is not published. + */ + public void publish(LogRecord record) { + // Silently ignore null records. + if (record == null) { + return; + } + + Logger slf4jLogger = getSLF4JLogger(record); + String message = record.getMessage(); // can be null! + // this is a check to avoid calling the underlying logging system + // with a null message. While it is legitimate to invoke j.u.l. with + // a null message, other logging frameworks do not support this. + // see also http://jira.qos.ch/browse/SLF4J-99 + if (message == null) { + message = ""; + } + if (slf4jLogger instanceof LocationAwareLogger) { + callLocationAwareLogger((LocationAwareLogger) slf4jLogger, record); + } else { + callPlainSLF4JLogger(slf4jLogger, record); + } + } + +} diff --git a/jul-to-slf4j/src/main/java/org/slf4j/bridge/package.html b/jul-to-slf4j/src/main/java/org/slf4j/bridge/package.html index 37927ff..2b643c3 100644 --- a/jul-to-slf4j/src/main/java/org/slf4j/bridge/package.html +++ b/jul-to-slf4j/src/main/java/org/slf4j/bridge/package.html @@ -1,15 +1,15 @@ - - - - - - - - - - -

Bridge/route all JUL log records to the SLF4J API.

- -
- - + + + + + + + + + + +

Bridge/route all JUL log records to the SLF4J API.

+ +
+ + diff --git a/jul-to-slf4j/src/main/resources/META-INF/MANIFEST.MF b/jul-to-slf4j/src/main/resources/META-INF/MANIFEST.MF index 3cca8c6..e1ab4c0 100644 --- a/jul-to-slf4j/src/main/resources/META-INF/MANIFEST.MF +++ b/jul-to-slf4j/src/main/resources/META-INF/MANIFEST.MF @@ -1,7 +1,7 @@ -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: jul.to.slf4j -Bundle-Name: jul-to-slf4j -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.slf4j.bridge;version=${parsedVersion.osgiVersion};uses:="org.slf4j,org.slf4j.spi" -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},org.slf4j.spi;version=${parsedVersion.osgiVersion} +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: jul.to.slf4j +Bundle-Name: jul-to-slf4j +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.slf4j.bridge;version=${parsedVersion.osgiVersion};uses:="org.slf4j,org.slf4j.spi" +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion},org.slf4j.spi;version=${parsedVersion.osgiVersion} diff --git a/jul-to-slf4j/src/test/java/org/slf4j/bridge/ListAppender.java b/jul-to-slf4j/src/test/java/org/slf4j/bridge/ListAppender.java index 07f3786..e5fb5f3 100644 --- a/jul-to-slf4j/src/test/java/org/slf4j/bridge/ListAppender.java +++ b/jul-to-slf4j/src/test/java/org/slf4j/bridge/ListAppender.java @@ -1,53 +1,53 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.bridge; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.spi.LoggingEvent; - -public class ListAppender extends AppenderSkeleton { - - public List list = new ArrayList(); - - public boolean extractLocationInfo = false; - - protected void append(LoggingEvent event) { - list.add(event); - if (extractLocationInfo) { - event.getLocationInformation(); - } - } - - public void close() { - } - - public boolean requiresLayout() { - return false; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.bridge; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class ListAppender extends AppenderSkeleton { + + public List list = new ArrayList(); + + public boolean extractLocationInfo = false; + + protected void append(LoggingEvent event) { + list.add(event); + if (extractLocationInfo) { + event.getLocationInformation(); + } + } + + public void close() { + } + + public boolean requiresLayout() { + return false; + } + +} diff --git a/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerPerfTest.java b/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerPerfTest.java index fa20411..604ec1d 100644 --- a/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerPerfTest.java +++ b/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerPerfTest.java @@ -1,110 +1,110 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.bridge; - -import java.util.logging.Handler; -import java.util.logging.LogManager; - -import org.apache.log4j.FileAppender; -import org.apache.log4j.PatternLayout; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.LoggerFactory; - -public class SLF4JBridgeHandlerPerfTest { - - static String LOGGER_NAME = "yay"; - static int RUN_LENGTH = 100 * 1000; - - // set to false to test enabled logging performance - boolean disabledLogger = true; - - FileAppender fileAppender; - org.apache.log4j.Logger log4jRoot; - java.util.logging.Logger julRootLogger = LogManager.getLogManager().getLogger(""); - - java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(LOGGER_NAME); - org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(LOGGER_NAME); - - Handler[] existingHandlers; - - @Before - public void setUp() throws Exception { - fileAppender = new FileAppender(new PatternLayout("%r [%t] %p %c %x - %m%n"), "target/test-output/toto.log"); - - existingHandlers = julRootLogger.getHandlers(); - for (int i = 0; i < existingHandlers.length; i++) { - julRootLogger.removeHandler(existingHandlers[i]); - } - log4jRoot = org.apache.log4j.Logger.getRootLogger(); - log4jRoot.addAppender(fileAppender); - } - - @After - public void tearDown() throws Exception { - SLF4JBridgeHandler.uninstall(); - fileAppender.close(); - log4jRoot.getLoggerRepository().resetConfiguration(); - for (int i = 0; i < existingHandlers.length; i++) { - julRootLogger.addHandler(existingHandlers[i]); - } - } - - double julLoggerLoop() { - long start = System.nanoTime(); - for (int i = 0; i < RUN_LENGTH; i++) { - julLogger.info("jul"); - } - long end = System.nanoTime(); - return (end - start) * 1.0 / RUN_LENGTH; - } - - double slf4jLoggerLoop() { - long start = System.nanoTime(); - for (int i = 0; i < RUN_LENGTH; i++) { - slf4jLogger.info("slf4j"); - } - long end = System.nanoTime(); - return (end - start) * 1.0 / RUN_LENGTH; - } - - @Test - public void testPerf() { - SLF4JBridgeHandler.install(); - - if (disabledLogger) { - log4jRoot.setLevel(org.apache.log4j.Level.ERROR); - } - julLoggerLoop(); - double julAvg = julLoggerLoop(); - System.out.println("Average cost per call (JUL->SLF4J->log4j): " + julAvg + " nanos"); - - slf4jLoggerLoop(); - double slf4jAvg = slf4jLoggerLoop(); - System.out.println("Average cost per call (SLF4J->log4j): " + slf4jAvg + " nanos"); - System.out.println("Ratio " + (julAvg / slf4jAvg)); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.bridge; + +import java.util.logging.Handler; +import java.util.logging.LogManager; + +import org.apache.log4j.FileAppender; +import org.apache.log4j.PatternLayout; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +public class SLF4JBridgeHandlerPerfTest { + + static String LOGGER_NAME = "yay"; + static int RUN_LENGTH = 100 * 1000; + + // set to false to test enabled logging performance + boolean disabledLogger = true; + + FileAppender fileAppender; + org.apache.log4j.Logger log4jRoot; + java.util.logging.Logger julRootLogger = LogManager.getLogManager().getLogger(""); + + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(LOGGER_NAME); + org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(LOGGER_NAME); + + Handler[] existingHandlers; + + @Before + public void setUp() throws Exception { + fileAppender = new FileAppender(new PatternLayout("%r [%t] %p %c %x - %m%n"), "target/test-output/toto.log"); + + existingHandlers = julRootLogger.getHandlers(); + for (int i = 0; i < existingHandlers.length; i++) { + julRootLogger.removeHandler(existingHandlers[i]); + } + log4jRoot = org.apache.log4j.Logger.getRootLogger(); + log4jRoot.addAppender(fileAppender); + } + + @After + public void tearDown() throws Exception { + SLF4JBridgeHandler.uninstall(); + fileAppender.close(); + log4jRoot.getLoggerRepository().resetConfiguration(); + for (int i = 0; i < existingHandlers.length; i++) { + julRootLogger.addHandler(existingHandlers[i]); + } + } + + double julLoggerLoop() { + long start = System.nanoTime(); + for (int i = 0; i < RUN_LENGTH; i++) { + julLogger.info("jul"); + } + long end = System.nanoTime(); + return (end - start) * 1.0 / RUN_LENGTH; + } + + double slf4jLoggerLoop() { + long start = System.nanoTime(); + for (int i = 0; i < RUN_LENGTH; i++) { + slf4jLogger.info("slf4j"); + } + long end = System.nanoTime(); + return (end - start) * 1.0 / RUN_LENGTH; + } + + @Test + public void testPerf() { + SLF4JBridgeHandler.install(); + + if (disabledLogger) { + log4jRoot.setLevel(org.apache.log4j.Level.ERROR); + } + julLoggerLoop(); + double julAvg = julLoggerLoop(); + System.out.println("Average cost per call (JUL->SLF4J->log4j): " + julAvg + " nanos"); + + slf4jLoggerLoop(); + double slf4jAvg = slf4jLoggerLoop(); + System.out.println("Average cost per call (SLF4J->log4j): " + slf4jAvg + " nanos"); + System.out.println("Ratio " + (julAvg / slf4jAvg)); + } +} diff --git a/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerTest.java b/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerTest.java old file mode 100644 new file mode 100755 index d78fbdf..71e4bc5 100755 --- a/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerTest.java +++ b/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerTest.java @@ -1,198 +1,198 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.bridge; - -import static org.junit.Assert.assertEquals; - -import java.text.MessageFormat; -import java.util.ResourceBundle; -import java.util.logging.Level; - -import org.apache.log4j.spi.LocationInfo; -import org.apache.log4j.spi.LoggingEvent; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SLF4JBridgeHandlerTest { - - static String LOGGER_NAME = "yay"; - - ListAppender listAppender = new ListAppender(); - org.apache.log4j.Logger log4jRoot; - java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger("yay"); - - @Before - public void setUp() throws Exception { - listAppender.extractLocationInfo = true; - log4jRoot = org.apache.log4j.Logger.getRootLogger(); - log4jRoot.addAppender(listAppender); - log4jRoot.setLevel(org.apache.log4j.Level.TRACE); - } - - @After - public void tearDown() throws Exception { - SLF4JBridgeHandler.uninstall(); - log4jRoot.getLoggerRepository().resetConfiguration(); - } - - @Test - public void testSmoke() { - SLF4JBridgeHandler.install(); - String msg = "msg"; - julLogger.info(msg); - assertEquals(1, listAppender.list.size()); - LoggingEvent le = (LoggingEvent) listAppender.list.get(0); - assertEquals(LOGGER_NAME, le.getLoggerName()); - assertEquals(msg, le.getMessage()); - - // get the location info in the event. - // Note that this must have been computed previously - // within an appender for the following assertion to - // work properly - LocationInfo li = le.getLocationInformation(); - System.out.println(li.fullInfo); - assertEquals("SLF4JBridgeHandlerTest.java", li.getFileName()); - assertEquals("testSmoke", li.getMethodName()); - } - - @Test - public void testLevels() { - SLF4JBridgeHandler.install(); - String msg = "msg"; - julLogger.setLevel(Level.ALL); - - julLogger.finest(msg); - julLogger.finer(msg); - julLogger.fine(msg); - julLogger.info(msg); - julLogger.warning(msg); - julLogger.severe(msg); - - assertEquals(6, listAppender.list.size()); - int i = 0; - assertLevel(i++, org.apache.log4j.Level.TRACE); - assertLevel(i++, org.apache.log4j.Level.DEBUG); - assertLevel(i++, org.apache.log4j.Level.DEBUG); - assertLevel(i++, org.apache.log4j.Level.INFO); - assertLevel(i++, org.apache.log4j.Level.WARN); - assertLevel(i++, org.apache.log4j.Level.ERROR); - } - - @Test - public void testLogWithResourceBundle() { - SLF4JBridgeHandler.install(); - - String resourceBundleName = "org.slf4j.bridge.testLogStrings"; - ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); - String resourceKey = "resource_key"; - String expectedMsg = bundle.getString(resourceKey); - String msg = resourceKey; - - java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("yay", resourceBundleName); - - julResourceBundleLogger.info(msg); - assertEquals(1, listAppender.list.size()); - LoggingEvent le = (LoggingEvent) listAppender.list.get(0); - assertEquals(LOGGER_NAME, le.getLoggerName()); - assertEquals(expectedMsg, le.getMessage()); - } - - @Test - public void testLogWithResourceBundleWithParameters() { - SLF4JBridgeHandler.install(); - - String resourceBundleName = "org.slf4j.bridge.testLogStrings"; - ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); - - java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("foo", resourceBundleName); - - String resourceKey1 = "resource_key_1"; - String expectedMsg1 = bundle.getString(resourceKey1); - julResourceBundleLogger.info(resourceKey1); // 1st log - - String resourceKey2 = "resource_key_2"; - Object[] params2 = new Object[] { "foo", "bar" }; - String expectedMsg2 = MessageFormat.format(bundle.getString(resourceKey2), params2); - julResourceBundleLogger.log(Level.INFO, resourceKey2, params2); // 2nd log - - String resourceKey3 = "invalidKey {0}"; - Object[] params3 = new Object[] { "John" }; - String expectedMsg3 = MessageFormat.format(resourceKey3, params3); - julResourceBundleLogger.log(Level.INFO, resourceKey3, params3); // 3rd log - - julLogger.log(Level.INFO, resourceKey3, params3); // 4th log - - assertEquals(4, listAppender.list.size()); - - LoggingEvent le = null; - - le = (LoggingEvent) listAppender.list.get(0); - assertEquals("foo", le.getLoggerName()); - assertEquals(expectedMsg1, le.getMessage()); - - le = (LoggingEvent) listAppender.list.get(1); - assertEquals("foo", le.getLoggerName()); - assertEquals(expectedMsg2, le.getMessage()); - - le = (LoggingEvent) listAppender.list.get(2); - assertEquals("foo", le.getLoggerName()); - assertEquals(expectedMsg3, le.getMessage()); - - le = (LoggingEvent) listAppender.list.get(3); - assertEquals("yay", le.getLoggerName()); - assertEquals(expectedMsg3, le.getMessage()); - } - - @Test - public void testLogWithPlaceholderNoParameters() { - SLF4JBridgeHandler.install(); - String msg = "msg {non-number-string}"; - julLogger.logp(Level.INFO, "SLF4JBridgeHandlerTest", "testLogWithPlaceholderNoParameters", msg, new Object[0]); - - assertEquals(1, listAppender.list.size()); - LoggingEvent le = (LoggingEvent) listAppender.list.get(0); - assertEquals(LOGGER_NAME, le.getLoggerName()); - assertEquals(msg, le.getMessage()); - } - - // See http://jira.qos.ch/browse/SLF4J-337 - - @Test - public void illFormattedInputShouldBeReturnedAsIs() { - SLF4JBridgeHandler.install(); - String msg = "foo {18=bad} {0}"; - - julLogger.log(Level.INFO, msg, "ignored parameter due to IllegalArgumentException"); - assertEquals(1, listAppender.list.size()); - LoggingEvent le = (LoggingEvent) listAppender.list.get(0); - assertEquals(msg, le.getMessage()); - } - - void assertLevel(int index, org.apache.log4j.Level expectedLevel) { - LoggingEvent le = (LoggingEvent) listAppender.list.get(index); - assertEquals(expectedLevel, le.getLevel()); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.bridge; + +import static org.junit.Assert.assertEquals; + +import java.text.MessageFormat; +import java.util.ResourceBundle; +import java.util.logging.Level; + +import org.apache.log4j.spi.LocationInfo; +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SLF4JBridgeHandlerTest { + + static String LOGGER_NAME = "yay"; + + ListAppender listAppender = new ListAppender(); + org.apache.log4j.Logger log4jRoot; + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger("yay"); + + @Before + public void setUp() throws Exception { + listAppender.extractLocationInfo = true; + log4jRoot = org.apache.log4j.Logger.getRootLogger(); + log4jRoot.addAppender(listAppender); + log4jRoot.setLevel(org.apache.log4j.Level.TRACE); + } + + @After + public void tearDown() throws Exception { + SLF4JBridgeHandler.uninstall(); + log4jRoot.getLoggerRepository().resetConfiguration(); + } + + @Test + public void testSmoke() { + SLF4JBridgeHandler.install(); + String msg = "msg"; + julLogger.info(msg); + assertEquals(1, listAppender.list.size()); + LoggingEvent le = (LoggingEvent) listAppender.list.get(0); + assertEquals(LOGGER_NAME, le.getLoggerName()); + assertEquals(msg, le.getMessage()); + + // get the location info in the event. + // Note that this must have been computed previously + // within an appender for the following assertion to + // work properly + LocationInfo li = le.getLocationInformation(); + System.out.println(li.fullInfo); + assertEquals("SLF4JBridgeHandlerTest.java", li.getFileName()); + assertEquals("testSmoke", li.getMethodName()); + } + + @Test + public void testLevels() { + SLF4JBridgeHandler.install(); + String msg = "msg"; + julLogger.setLevel(Level.ALL); + + julLogger.finest(msg); + julLogger.finer(msg); + julLogger.fine(msg); + julLogger.info(msg); + julLogger.warning(msg); + julLogger.severe(msg); + + assertEquals(6, listAppender.list.size()); + int i = 0; + assertLevel(i++, org.apache.log4j.Level.TRACE); + assertLevel(i++, org.apache.log4j.Level.DEBUG); + assertLevel(i++, org.apache.log4j.Level.DEBUG); + assertLevel(i++, org.apache.log4j.Level.INFO); + assertLevel(i++, org.apache.log4j.Level.WARN); + assertLevel(i++, org.apache.log4j.Level.ERROR); + } + + @Test + public void testLogWithResourceBundle() { + SLF4JBridgeHandler.install(); + + String resourceBundleName = "org.slf4j.bridge.testLogStrings"; + ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); + String resourceKey = "resource_key"; + String expectedMsg = bundle.getString(resourceKey); + String msg = resourceKey; + + java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("yay", resourceBundleName); + + julResourceBundleLogger.info(msg); + assertEquals(1, listAppender.list.size()); + LoggingEvent le = (LoggingEvent) listAppender.list.get(0); + assertEquals(LOGGER_NAME, le.getLoggerName()); + assertEquals(expectedMsg, le.getMessage()); + } + + @Test + public void testLogWithResourceBundleWithParameters() { + SLF4JBridgeHandler.install(); + + String resourceBundleName = "org.slf4j.bridge.testLogStrings"; + ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); + + java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("foo", resourceBundleName); + + String resourceKey1 = "resource_key_1"; + String expectedMsg1 = bundle.getString(resourceKey1); + julResourceBundleLogger.info(resourceKey1); // 1st log + + String resourceKey2 = "resource_key_2"; + Object[] params2 = new Object[] { "foo", "bar" }; + String expectedMsg2 = MessageFormat.format(bundle.getString(resourceKey2), params2); + julResourceBundleLogger.log(Level.INFO, resourceKey2, params2); // 2nd log + + String resourceKey3 = "invalidKey {0}"; + Object[] params3 = new Object[] { "John" }; + String expectedMsg3 = MessageFormat.format(resourceKey3, params3); + julResourceBundleLogger.log(Level.INFO, resourceKey3, params3); // 3rd log + + julLogger.log(Level.INFO, resourceKey3, params3); // 4th log + + assertEquals(4, listAppender.list.size()); + + LoggingEvent le = null; + + le = (LoggingEvent) listAppender.list.get(0); + assertEquals("foo", le.getLoggerName()); + assertEquals(expectedMsg1, le.getMessage()); + + le = (LoggingEvent) listAppender.list.get(1); + assertEquals("foo", le.getLoggerName()); + assertEquals(expectedMsg2, le.getMessage()); + + le = (LoggingEvent) listAppender.list.get(2); + assertEquals("foo", le.getLoggerName()); + assertEquals(expectedMsg3, le.getMessage()); + + le = (LoggingEvent) listAppender.list.get(3); + assertEquals("yay", le.getLoggerName()); + assertEquals(expectedMsg3, le.getMessage()); + } + + @Test + public void testLogWithPlaceholderNoParameters() { + SLF4JBridgeHandler.install(); + String msg = "msg {non-number-string}"; + julLogger.logp(Level.INFO, "SLF4JBridgeHandlerTest", "testLogWithPlaceholderNoParameters", msg, new Object[0]); + + assertEquals(1, listAppender.list.size()); + LoggingEvent le = (LoggingEvent) listAppender.list.get(0); + assertEquals(LOGGER_NAME, le.getLoggerName()); + assertEquals(msg, le.getMessage()); + } + + // See http://jira.qos.ch/browse/SLF4J-337 + + @Test + public void illFormattedInputShouldBeReturnedAsIs() { + SLF4JBridgeHandler.install(); + String msg = "foo {18=bad} {0}"; + + julLogger.log(Level.INFO, msg, "ignored parameter due to IllegalArgumentException"); + assertEquals(1, listAppender.list.size()); + LoggingEvent le = (LoggingEvent) listAppender.list.get(0); + assertEquals(msg, le.getMessage()); + } + + void assertLevel(int index, org.apache.log4j.Level expectedLevel) { + LoggingEvent le = (LoggingEvent) listAppender.list.get(index); + assertEquals(expectedLevel, le.getLevel()); + } +} diff --git a/jul-to-slf4j/src/test/resources/org/slf4j/bridge/testLogStrings.properties b/jul-to-slf4j/src/test/resources/org/slf4j/bridge/testLogStrings.properties index 2b0d143..e0deb62 100644 --- a/jul-to-slf4j/src/test/resources/org/slf4j/bridge/testLogStrings.properties +++ b/jul-to-slf4j/src/test/resources/org/slf4j/bridge/testLogStrings.properties @@ -1,3 +1,3 @@ -resource_key=msg -resource_key_1=msg -resource_key_2=msg {0} {1} +resource_key=msg +resource_key_1=msg +resource_key_2=msg {0} {1} diff --git a/log4j-over-slf4j/compatibility/build.xml b/log4j-over-slf4j/compatibility/build.xml new file mode 100644 index 0000000..5115a42 --- /dev/null +++ b/log4j-over-slf4j/compatibility/build.xml @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + These are some of the targets supported by this ANT build scpript: + + all - run all available tests + refresh - copy required jar files to the lib directory + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/log4j-over-slf4j/compatibility/readme.txt b/log4j-over-slf4j/compatibility/readme.txt new file mode 100644 index 0000000..6554cc6 --- /dev/null +++ b/log4j-over-slf4j/compatibility/readme.txt @@ -0,0 +1,17 @@ + +This directory is used to test the module against various log4j calls. +Two test cases simulate the typical calls that one can find in an application +that uses either log4j 1.2.x, or log4j 1.3.x. + +In the same directory is a build.xml file that uses ant to +compile the test cases with the corresponding log4j version, +and to runs these tests without log4j in the classpath but with +logback jars instead. + +To run the tests, one must have ant installed. Issuing the following command, +once in the compatibility directory will launch the tests: + +ant all + +To obtain more information about the use of the log4j-over-slf4j module, +please visit http://www..slf4j.org/log4j-over-slf4j.html \ No newline at end of file diff --git a/log4j-over-slf4j/compatibility/src/main/java/test/DummyObject.java b/log4j-over-slf4j/compatibility/src/main/java/test/DummyObject.java new file mode 100644 index 0000000..3a11790 --- /dev/null +++ b/log4j-over-slf4j/compatibility/src/main/java/test/DummyObject.java @@ -0,0 +1,8 @@ +package test; + +public class DummyObject { + + public String toString() { + return "dummy"; + } +} diff --git a/log4j-over-slf4j/compatibility/src/main/java/test/Log4j12Calls.java b/log4j-over-slf4j/compatibility/src/main/java/test/Log4j12Calls.java new file mode 100644 index 0000000..eeff93b --- /dev/null +++ b/log4j-over-slf4j/compatibility/src/main/java/test/Log4j12Calls.java @@ -0,0 +1,39 @@ +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * + * Copyright (C) 1999-2006, QOS.ch + * + * This library is free software, you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation. + */ +package test; + +import junit.framework.TestCase; + +import org.apache.log4j.Logger; +import org.apache.log4j.MDC; + +/** + * + * A test case that issues the typical calls + * that an application using log4j 1.2 would do. + * + * @author Ceki Gülcü + * @author Sébastien Pennec + */ +public class Log4j12Calls extends TestCase { + public static final Logger logger = Logger.getLogger(Log4j12Calls.class); + + public void testLog() { + MDC.put("key", "value1"); + + logger.trace("Trace level can be noisy"); + logger.debug("Entering application"); + logger.info("Violets are blue"); + logger.warn("Here is a warning"); + logger.error("Exiting application", new Exception("just testing")); + + MDC.remove("key"); + } +} diff --git a/log4j-over-slf4j/compatibility/src/main/java/test/Log4j13Calls.java b/log4j-over-slf4j/compatibility/src/main/java/test/Log4j13Calls.java new file mode 100644 index 0000000..54c6e9f --- /dev/null +++ b/log4j-over-slf4j/compatibility/src/main/java/test/Log4j13Calls.java @@ -0,0 +1,46 @@ +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * + * Copyright (C) 1999-2006, QOS.ch + * + * This library is free software, you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation. + */ + +package test; + +import junit.framework.TestCase; + +import org.apache.log4j.Logger; +import org.apache.log4j.MDC; + +/** + * + * A test case that issues the typical calls + * that an application using log4j 1.3 would do. + * + * @author Ceki Gülcü + * @author Sébastien Pennec + */ + +public class Log4j13Calls extends TestCase { + public static final Logger logger = Logger.getLogger(Log4j12Calls.class); + + public void testLog() { + MDC.put("key", "value1"); + + logger.trace("Trace level can be noisy"); + logger.debug("Entering application"); + logger.info("Violets are blue"); + logger.warn("Here is a warning"); + logger.info("The answer is {}.", new Integer(42)); + logger.info("Number: {} and another one: {}.", new Integer(42), new Integer(24)); + + logger.error("Exiting application", new Exception("just testing")); + + MDC.remove("key"); + + MDC.clear(); + } +} diff --git a/log4j-over-slf4j/compatibility/src/main/java/test/LoggerTest.java b/log4j-over-slf4j/compatibility/src/main/java/test/LoggerTest.java new file mode 100644 index 0000000..29c8a46 --- /dev/null +++ b/log4j-over-slf4j/compatibility/src/main/java/test/LoggerTest.java @@ -0,0 +1,169 @@ +package test; + +import junit.framework.TestCase; + +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import org.apache.log4j.Level; + +/** + * A class that tests the invocation of the org.apache.log4j.Logger class that + * belongs to the log4j-bridge package + * + * @author Sébastien Pennec + * @author Ceki Gülcü + */ + +public class LoggerTest extends TestCase { + + LoggerContext context; + ListAppender appender; + ch.qos.logback.classic.Logger logbackLogger; + org.apache.log4j.Logger log4jLogger; + + public void setUp() throws Exception { + context = (LoggerContext) LoggerFactory.getILoggerFactory(); + context.shutdownAndReset(); + appender = new ListAppender(); + appender.setContext(context); + appender.setName("listAppender"); + appender.start(); + ch.qos.logback.classic.Logger lbLogger = context + .getLogger(LoggerContext.ROOT_NAME); + lbLogger.addAppender(appender); + + log4jLogger = org.apache.log4j.Logger.getLogger(LoggerTest.class); + logbackLogger = context.getLogger(LoggerTest.class); + super.setUp(); + } + + public void tearDown() throws Exception { + appender.stop(); + context.stop(); + appender = null; + context = null; + logbackLogger = null; + log4jLogger = null; + super.tearDown(); + } + + public void testLogWithObjectMessages() { + LoggingEvent event; + + log4jLogger.debug("test"); + event = appender.list.get(0); + assertEquals("test", event.getMessage()); + appender.list.clear(); + + log4jLogger.debug(null); + event = appender.list.get(0); + assertEquals(null, event.getMessage()); + appender.list.clear(); + + DummyObject dummy = new DummyObject(); + log4jLogger.debug(dummy); + event = appender.list.get(0); + assertEquals(dummy.toString(), event.getMessage()); + appender.list.clear(); + } + + public void testIsEnabledAPI() { + assertFalse(log4jLogger.isTraceEnabled()); + assertTrue(log4jLogger.isDebugEnabled()); + assertTrue(log4jLogger.isInfoEnabled()); + assertTrue(log4jLogger.isWarnEnabled()); + assertTrue(log4jLogger.isErrorEnabled()); + } + + public void testPrintAPI() { + Exception e = new Exception("just testing"); + + log4jLogger.trace(null); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.debug(null); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.debug("debug message"); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.info(null); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.info("info message"); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.warn(null); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.warn("warn message"); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.error(null); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.error("error message"); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.debug(null, e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.debug("debug message", e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.info(null, e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.info("info message", e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.warn(null, e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.warn("warn message", e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.error(null, e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.error("error message", e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + } + + public void testLogAPI() { + log4jLogger.log("x", Level.TRACE, "x", null); + assertEquals(0, appender.list.size()); + + log4jLogger.log("x", Level.DEBUG, "x", null); + log4jLogger.log("x", Level.INFO, "x", null); + log4jLogger.log("x", Level.WARN, "x", null); + log4jLogger.log("x", Level.ERROR, "x", null); + log4jLogger.log("x", Level.FATAL, "x", null); + + assertEquals(5, appender.list.size()); + appender.list.clear(); + + } + +} diff --git a/log4j-over-slf4j/pom.xml b/log4j-over-slf4j/pom.xml old file mode 100644 new file mode 100755 index 53a3a48..2e6f87f 100755 --- a/log4j-over-slf4j/pom.xml +++ b/log4j-over-slf4j/pom.xml @@ -1,40 +1,40 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - - log4j-over-slf4j - jar - Log4j Implemented Over SLF4J - Log4j implemented over SLF4J - - http://www.slf4j.org - - - - Apache Software Licenses - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-jdk14 - test - - - - \ No newline at end of file + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + + log4j-over-slf4j + jar + Log4j Implemented Over SLF4J + Log4j implemented over SLF4J + + http://www.slf4j.org + + + + Apache Software Licenses + http://www.apache.org/licenses/LICENSE-2.0.txt + + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-jdk14 + test + + + + diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/Appender.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/Appender.java index 824513c..f391cef 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Appender.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Appender.java @@ -1,130 +1,130 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -import org.apache.log4j.spi.Filter; -import org.apache.log4j.spi.ErrorHandler; -import org.apache.log4j.spi.LoggingEvent; - -/** - * Implement this interface for your own strategies for outputting log - * statements. - * - * @author Ceki Gülcü - */ -public interface Appender { - - /** - * Add a filter to the end of the filter list. - * - * @since 0.9.0 - */ - void addFilter(Filter newFilter); - - /** - * Returns the head Filter. The Filters are organized in a linked list - * and so all Filters on this Appender are available through the result. - * - * @return the head Filter or null, if no Filters are present - * @since 1.1 - */ - public Filter getFilter(); - - /** - * Clear the list of filters by removing all the filters in it. - * - * @since 0.9.0 - */ - public void clearFilters(); - - /** - * Release any resources allocated within the appender such as file - * handles, network connections, etc. - *

- *

It is a programming error to append to a closed appender. - * - * @since 0.8.4 - */ - public void close(); - - /** - * Log in Appender specific way. When appropriate, - * Loggers will call the doAppend method of appender - * implementations in order to log. - */ - public void doAppend(LoggingEvent event); - - /** - * Get the name of this appender. The name uniquely identifies the - * appender. - */ - public String getName(); - - /** - * Set the {@link ErrorHandler} for this appender. - * - * @since 0.9.0 - */ - public void setErrorHandler(ErrorHandler errorHandler); - - /** - * Returns the {@link ErrorHandler} for this appender. - * - * @since 1.1 - */ - public ErrorHandler getErrorHandler(); - - /** - * Set the {@link Layout} for this appender. - * - * @since 0.8.1 - */ - public void setLayout(Layout layout); - - /** - * Returns this appenders layout. - * - * @since 1.1 - */ - public Layout getLayout(); - - /** - * Set the name of this appender. The name is used by other - * components to identify this appender. - * - * @since 0.8.1 - */ - public void setName(String name); - - /** - * Configurators call this method to determine if the appender - * requires a layout. If this method returns true, - * meaning that layout is required, then the configurator will - * configure an layout using the configuration information at its - * disposal. If this method returns false, meaning that - * a layout is not required, then layout configuration will be - * skipped even if there is available layout configuration - * information at the disposal of the configurator. - *

- *

In the rather exceptional case, where the appender - * implementation admits a layout but can also work without it, then - * the appender should return true. - * - * @since 0.8.4 - */ - public boolean requiresLayout(); -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j; + +import org.apache.log4j.spi.Filter; +import org.apache.log4j.spi.ErrorHandler; +import org.apache.log4j.spi.LoggingEvent; + +/** + * Implement this interface for your own strategies for outputting log + * statements. + * + * @author Ceki Gülcü + */ +public interface Appender { + + /** + * Add a filter to the end of the filter list. + * + * @since 0.9.0 + */ + void addFilter(Filter newFilter); + + /** + * Returns the head Filter. The Filters are organized in a linked list + * and so all Filters on this Appender are available through the result. + * + * @return the head Filter or null, if no Filters are present + * @since 1.1 + */ + public Filter getFilter(); + + /** + * Clear the list of filters by removing all the filters in it. + * + * @since 0.9.0 + */ + public void clearFilters(); + + /** + * Release any resources allocated within the appender such as file + * handles, network connections, etc. + *

+ *

It is a programming error to append to a closed appender. + * + * @since 0.8.4 + */ + public void close(); + + /** + * Log in Appender specific way. When appropriate, + * Loggers will call the doAppend method of appender + * implementations in order to log. + */ + public void doAppend(LoggingEvent event); + + /** + * Get the name of this appender. The name uniquely identifies the + * appender. + */ + public String getName(); + + /** + * Set the {@link ErrorHandler} for this appender. + * + * @since 0.9.0 + */ + public void setErrorHandler(ErrorHandler errorHandler); + + /** + * Returns the {@link ErrorHandler} for this appender. + * + * @since 1.1 + */ + public ErrorHandler getErrorHandler(); + + /** + * Set the {@link Layout} for this appender. + * + * @since 0.8.1 + */ + public void setLayout(Layout layout); + + /** + * Returns this appenders layout. + * + * @since 1.1 + */ + public Layout getLayout(); + + /** + * Set the name of this appender. The name is used by other + * components to identify this appender. + * + * @since 0.8.1 + */ + public void setName(String name); + + /** + * Configurators call this method to determine if the appender + * requires a layout. If this method returns true, + * meaning that layout is required, then the configurator will + * configure an layout using the configuration information at its + * disposal. If this method returns false, meaning that + * a layout is not required, then layout configuration will be + * skipped even if there is available layout configuration + * information at the disposal of the configurator. + *

+ *

In the rather exceptional case, where the appender + * implementation admits a layout but can also work without it, then + * the appender should return true. + * + * @since 0.8.4 + */ + public boolean requiresLayout(); +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/AppenderSkeleton.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/AppenderSkeleton.java index 184a47f..447c3b5 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/AppenderSkeleton.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/AppenderSkeleton.java @@ -1,33 +1,33 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.log4j; - -import org.apache.log4j.spi.OptionHandler; - -public class AppenderSkeleton implements OptionHandler { - - public void setLayout(Layout layout) { - } - - public void setName(String name) { - } - - public void activateOptions() { - } - - public void setThreshold(Priority threshold) { - } -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.log4j; + +import org.apache.log4j.spi.OptionHandler; + +public class AppenderSkeleton implements OptionHandler { + + public void setLayout(Layout layout) { + } + + public void setName(String name) { + } + + public void activateOptions() { + } + + public void setThreshold(Priority threshold) { + } +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/BasicConfigurator.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/BasicConfigurator.java index 46beb29..4209ca5 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/BasicConfigurator.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/BasicConfigurator.java @@ -1,31 +1,31 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -/** - * A minimal (nop) implementation of BasicConfigurator. - */ -public class BasicConfigurator { - public static void configure() { - } - - public static void configure(Appender appender) { - } - - public static void resetConfiguration() { - } -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j; + +/** + * A minimal (nop) implementation of BasicConfigurator. + */ +public class BasicConfigurator { + public static void configure() { + } + + public static void configure(Appender appender) { + } + + public static void resetConfiguration() { + } +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/Category.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/Category.java index 23230ea..fc8b50c 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Category.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Category.java @@ -1,359 +1,359 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -import org.apache.log4j.helpers.NullEnumeration; -import org.slf4j.LoggerFactory; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; -import org.slf4j.spi.LocationAwareLogger; - -import java.util.Enumeration; - -/** - *

- * This class is a minimal implementation of the original - * org.apache.log4j.Category class (as found in log4j 1.2) by - * delegation of all calls to a {@link org.slf4j.Logger} instance. - *

- * - *

- * Log4j's trace, debug(), info(), - * warn(), error() printing methods are directly - * mapped to their SLF4J equivalents. Log4j's fatal() printing - * method is mapped to SLF4J's error() method with a FATAL marker. - * - * @author Sébastien Pennec - * @author Ceki Gülcü - */ -@SuppressWarnings("rawtypes") -public class Category { - - private static final String CATEGORY_FQCN = Category.class.getName(); - - private String name; - - protected org.slf4j.Logger slf4jLogger; - private org.slf4j.spi.LocationAwareLogger locationAwareLogger; - - private static Marker FATAL_MARKER = MarkerFactory.getMarker("FATAL"); - - Category(String name) { - this.name = name; - slf4jLogger = LoggerFactory.getLogger(name); - if (slf4jLogger instanceof LocationAwareLogger) { - locationAwareLogger = (LocationAwareLogger) slf4jLogger; - } - } - - public static Category getInstance(Class clazz) { - return Log4jLoggerFactory.getLogger(clazz.getName()); - } - - public static Category getInstance(String name) { - return Log4jLoggerFactory.getLogger(name); - } - - public final Category getParent() { - return null; - } - - /** - * Returns the obvious. - * - * @return - */ - public String getName() { - return name; - } - - public Appender getAppender(String name) { - return null; - } - - public Enumeration getAllAppenders() { - return NullEnumeration.getInstance(); - } - - /** - * Return the level in effect for this category/logger. - * - *

- * The result is computed by simulation. - * - * @return - */ - public Level getEffectiveLevel() { - if (slf4jLogger.isTraceEnabled()) { - return Level.TRACE; - } - if (slf4jLogger.isDebugEnabled()) { - return Level.DEBUG; - } - if (slf4jLogger.isInfoEnabled()) { - return Level.INFO; - } - if (slf4jLogger.isWarnEnabled()) { - return Level.WARN; - } - return Level.ERROR; - } - - /** - * Returns the assigned {@link Level}, if any, for this Category. This - * implementation always returns null. - * - * @return Level - the assigned Level, can be null. - */ - final public Level getLevel() { - return null; - } - - /** - * @deprecated Please use {@link #getLevel} instead. - */ - final public Level getPriority() { - return null; - } - - /** - * Delegates to {@link org.slf4j.Logger#isDebugEnabled} method in SLF4J - */ - public boolean isDebugEnabled() { - return slf4jLogger.isDebugEnabled(); - } - - /** - * Delegates to {@link org.slf4j.Logger#isInfoEnabled} method in SLF4J - */ - public boolean isInfoEnabled() { - return slf4jLogger.isInfoEnabled(); - } - - /** - * Delegates to {@link org.slf4j.Logger#isWarnEnabled} method in SLF4J - */ - public boolean isWarnEnabled() { - return slf4jLogger.isWarnEnabled(); - } - - /** - * Delegates to {@link org.slf4j.Logger#isErrorEnabled} method in SLF4J - */ - public boolean isErrorEnabled() { - return slf4jLogger.isErrorEnabled(); - } - - /** - * Determines whether the priority passed as parameter is enabled in the - * underlying SLF4J logger. Each log4j priority is mapped directly to its - * SLF4J equivalent, except for FATAL which is mapped as ERROR. - * - * @param p - * the priority to check against - * @return true if this logger is enabled for the given level, false - * otherwise. - */ - public boolean isEnabledFor(Priority p) { - switch (p.level) { - case Level.TRACE_INT: - return slf4jLogger.isTraceEnabled(); - case Level.DEBUG_INT: - return slf4jLogger.isDebugEnabled(); - case Level.INFO_INT: - return slf4jLogger.isInfoEnabled(); - case Level.WARN_INT: - return slf4jLogger.isWarnEnabled(); - case Level.ERROR_INT: - return slf4jLogger.isErrorEnabled(); - case Priority.FATAL_INT: - return slf4jLogger.isErrorEnabled(); - } - return false; - } - - void differentiatedLog(Marker marker, String fqcn, int level, Object message, Throwable t) { - - String m = convertToString(message); - if (locationAwareLogger != null) { - locationAwareLogger.log(marker, fqcn, level, m, null, t); - } else { - switch (level) { - case LocationAwareLogger.TRACE_INT: - slf4jLogger.trace(marker, m); - break; - case LocationAwareLogger.DEBUG_INT: - slf4jLogger.debug(marker, m); - break; - case LocationAwareLogger.INFO_INT: - slf4jLogger.info(marker, m); - break; - case LocationAwareLogger.WARN_INT: - slf4jLogger.warn(marker, m); - break; - case LocationAwareLogger.ERROR_INT: - slf4jLogger.error(marker, m); - break; - } - } - } - - /** - * Delegates to {@link org.slf4j.Logger#debug(String)} method of SLF4J. - */ - public void debug(Object message) { - differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.DEBUG_INT, message, null); - } - - /** - * Delegates to {@link org.slf4j.Logger#debug(String,Throwable)} method in - * SLF4J. - */ - public void debug(Object message, Throwable t) { - differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.DEBUG_INT, message, t); - } - - /** - * Delegates to {@link org.slf4j.Logger#info(String)} method in SLF4J. - */ - public void info(Object message) { - differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.INFO_INT, message, null); - } - - /** - * Delegates to {@link org.slf4j.Logger#info(String,Throwable)} method in - * SLF4J. - */ - public void info(Object message, Throwable t) { - differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.INFO_INT, message, t); - } - - /** - * Delegates to {@link org.slf4j.Logger#warn(String)} method in SLF4J. - */ - public void warn(Object message) { - differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.WARN_INT, message, null); - } - - /** - * Delegates to {@link org.slf4j.Logger#warn(String,Throwable)} method in - * SLF4J. - */ - public void warn(Object message, Throwable t) { - differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.WARN_INT, message, t); - } - - /** - * Delegates to {@link org.slf4j.Logger#error(String)} method in SLF4J. - */ - public void error(Object message) { - differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, null); - } - - /** - * Delegates to {@link org.slf4j.Logger#error(String,Throwable)} method in - * SLF4J. - */ - public void error(Object message, Throwable t) { - differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, t); - } - - /** - * Delegates to {@link org.slf4j.Logger#error(String)} method in SLF4J. - */ - public void fatal(Object message) { - differentiatedLog(FATAL_MARKER, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, null); - } - - /** - * Delegates to {@link org.slf4j.Logger#error(String,Throwable)} method in - * SLF4J. In addition, the call is marked with a marker named "FATAL". - */ - public void fatal(Object message, Throwable t) { - differentiatedLog(FATAL_MARKER, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, t); - } - - protected void forcedLog(String FQCN, Priority p, Object msg, Throwable t) { - log(FQCN, p, msg, t); - } - - // See also http://jira.qos.ch/browse/SLF4J-159 - public void log(String FQCN, Priority p, Object msg, Throwable t) { - int levelInt = priorityToLevelInt(p); - differentiatedLog(null, FQCN, levelInt, msg, t); - } - - public void log(Priority p, Object message, Throwable t) { - int levelInt = priorityToLevelInt(p); - differentiatedLog(null, CATEGORY_FQCN, levelInt, message, t); - } - - public void log(Priority p, Object message) { - int levelInt = priorityToLevelInt(p); - differentiatedLog(null, CATEGORY_FQCN, levelInt, message, null); - } - - private int priorityToLevelInt(Priority p) { - switch (p.level) { - case Level.TRACE_INT: - case Level.X_TRACE_INT: - return LocationAwareLogger.TRACE_INT; - case Priority.DEBUG_INT: - return LocationAwareLogger.DEBUG_INT; - case Priority.INFO_INT: - return LocationAwareLogger.INFO_INT; - case Priority.WARN_INT: - return LocationAwareLogger.WARN_INT; - case Priority.ERROR_INT: - return LocationAwareLogger.ERROR_INT; - case Priority.FATAL_INT: - return LocationAwareLogger.ERROR_INT; - default: - throw new IllegalStateException("Unknown Priority " + p); - } - } - - protected final String convertToString(Object message) { - if (message == null) { - return (String) message; - } else { - return message.toString(); - } - } - - public void setAdditivity(boolean additive) { - // nothing to do - } - - public void addAppender(Appender newAppender) { - // nothing to do - } - - public void setLevel(Level level) { - // nothing to do - } - - public boolean getAdditivity() { - return false; - } - - public void assertLog(boolean assertion, String msg) { - if (!assertion) - error(msg); - } - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j; + +import org.apache.log4j.helpers.NullEnumeration; +import org.slf4j.LoggerFactory; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; +import org.slf4j.spi.LocationAwareLogger; + +import java.util.Enumeration; + +/** + *

+ * This class is a minimal implementation of the original + * org.apache.log4j.Category class (as found in log4j 1.2) by + * delegation of all calls to a {@link org.slf4j.Logger} instance. + *

+ * + *

+ * Log4j's trace, debug(), info(), + * warn(), error() printing methods are directly + * mapped to their SLF4J equivalents. Log4j's fatal() printing + * method is mapped to SLF4J's error() method with a FATAL marker. + * + * @author Sébastien Pennec + * @author Ceki Gülcü + */ +@SuppressWarnings("rawtypes") +public class Category { + + private static final String CATEGORY_FQCN = Category.class.getName(); + + private String name; + + protected org.slf4j.Logger slf4jLogger; + private org.slf4j.spi.LocationAwareLogger locationAwareLogger; + + private static Marker FATAL_MARKER = MarkerFactory.getMarker("FATAL"); + + Category(String name) { + this.name = name; + slf4jLogger = LoggerFactory.getLogger(name); + if (slf4jLogger instanceof LocationAwareLogger) { + locationAwareLogger = (LocationAwareLogger) slf4jLogger; + } + } + + public static Category getInstance(Class clazz) { + return Log4jLoggerFactory.getLogger(clazz.getName()); + } + + public static Category getInstance(String name) { + return Log4jLoggerFactory.getLogger(name); + } + + public final Category getParent() { + return null; + } + + /** + * Returns the obvious. + * + * @return + */ + public String getName() { + return name; + } + + public Appender getAppender(String name) { + return null; + } + + public Enumeration getAllAppenders() { + return NullEnumeration.getInstance(); + } + + /** + * Return the level in effect for this category/logger. + * + *

+ * The result is computed by simulation. + * + * @return + */ + public Level getEffectiveLevel() { + if (slf4jLogger.isTraceEnabled()) { + return Level.TRACE; + } + if (slf4jLogger.isDebugEnabled()) { + return Level.DEBUG; + } + if (slf4jLogger.isInfoEnabled()) { + return Level.INFO; + } + if (slf4jLogger.isWarnEnabled()) { + return Level.WARN; + } + return Level.ERROR; + } + + /** + * Returns the assigned {@link Level}, if any, for this Category. This + * implementation always returns null. + * + * @return Level - the assigned Level, can be null. + */ + final public Level getLevel() { + return null; + } + + /** + * @deprecated Please use {@link #getLevel} instead. + */ + final public Level getPriority() { + return null; + } + + /** + * Delegates to {@link org.slf4j.Logger#isDebugEnabled} method in SLF4J + */ + public boolean isDebugEnabled() { + return slf4jLogger.isDebugEnabled(); + } + + /** + * Delegates to {@link org.slf4j.Logger#isInfoEnabled} method in SLF4J + */ + public boolean isInfoEnabled() { + return slf4jLogger.isInfoEnabled(); + } + + /** + * Delegates to {@link org.slf4j.Logger#isWarnEnabled} method in SLF4J + */ + public boolean isWarnEnabled() { + return slf4jLogger.isWarnEnabled(); + } + + /** + * Delegates to {@link org.slf4j.Logger#isErrorEnabled} method in SLF4J + */ + public boolean isErrorEnabled() { + return slf4jLogger.isErrorEnabled(); + } + + /** + * Determines whether the priority passed as parameter is enabled in the + * underlying SLF4J logger. Each log4j priority is mapped directly to its + * SLF4J equivalent, except for FATAL which is mapped as ERROR. + * + * @param p + * the priority to check against + * @return true if this logger is enabled for the given level, false + * otherwise. + */ + public boolean isEnabledFor(Priority p) { + switch (p.level) { + case Level.TRACE_INT: + return slf4jLogger.isTraceEnabled(); + case Level.DEBUG_INT: + return slf4jLogger.isDebugEnabled(); + case Level.INFO_INT: + return slf4jLogger.isInfoEnabled(); + case Level.WARN_INT: + return slf4jLogger.isWarnEnabled(); + case Level.ERROR_INT: + return slf4jLogger.isErrorEnabled(); + case Priority.FATAL_INT: + return slf4jLogger.isErrorEnabled(); + } + return false; + } + + void differentiatedLog(Marker marker, String fqcn, int level, Object message, Throwable t) { + + String m = convertToString(message); + if (locationAwareLogger != null) { + locationAwareLogger.log(marker, fqcn, level, m, null, t); + } else { + switch (level) { + case LocationAwareLogger.TRACE_INT: + slf4jLogger.trace(marker, m); + break; + case LocationAwareLogger.DEBUG_INT: + slf4jLogger.debug(marker, m); + break; + case LocationAwareLogger.INFO_INT: + slf4jLogger.info(marker, m); + break; + case LocationAwareLogger.WARN_INT: + slf4jLogger.warn(marker, m); + break; + case LocationAwareLogger.ERROR_INT: + slf4jLogger.error(marker, m); + break; + } + } + } + + /** + * Delegates to {@link org.slf4j.Logger#debug(String)} method of SLF4J. + */ + public void debug(Object message) { + differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.DEBUG_INT, message, null); + } + + /** + * Delegates to {@link org.slf4j.Logger#debug(String,Throwable)} method in + * SLF4J. + */ + public void debug(Object message, Throwable t) { + differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.DEBUG_INT, message, t); + } + + /** + * Delegates to {@link org.slf4j.Logger#info(String)} method in SLF4J. + */ + public void info(Object message) { + differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.INFO_INT, message, null); + } + + /** + * Delegates to {@link org.slf4j.Logger#info(String,Throwable)} method in + * SLF4J. + */ + public void info(Object message, Throwable t) { + differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.INFO_INT, message, t); + } + + /** + * Delegates to {@link org.slf4j.Logger#warn(String)} method in SLF4J. + */ + public void warn(Object message) { + differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.WARN_INT, message, null); + } + + /** + * Delegates to {@link org.slf4j.Logger#warn(String,Throwable)} method in + * SLF4J. + */ + public void warn(Object message, Throwable t) { + differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.WARN_INT, message, t); + } + + /** + * Delegates to {@link org.slf4j.Logger#error(String)} method in SLF4J. + */ + public void error(Object message) { + differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, null); + } + + /** + * Delegates to {@link org.slf4j.Logger#error(String,Throwable)} method in + * SLF4J. + */ + public void error(Object message, Throwable t) { + differentiatedLog(null, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, t); + } + + /** + * Delegates to {@link org.slf4j.Logger#error(String)} method in SLF4J. + */ + public void fatal(Object message) { + differentiatedLog(FATAL_MARKER, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, null); + } + + /** + * Delegates to {@link org.slf4j.Logger#error(String,Throwable)} method in + * SLF4J. In addition, the call is marked with a marker named "FATAL". + */ + public void fatal(Object message, Throwable t) { + differentiatedLog(FATAL_MARKER, CATEGORY_FQCN, LocationAwareLogger.ERROR_INT, message, t); + } + + protected void forcedLog(String FQCN, Priority p, Object msg, Throwable t) { + log(FQCN, p, msg, t); + } + + // See also http://jira.qos.ch/browse/SLF4J-159 + public void log(String FQCN, Priority p, Object msg, Throwable t) { + int levelInt = priorityToLevelInt(p); + differentiatedLog(null, FQCN, levelInt, msg, t); + } + + public void log(Priority p, Object message, Throwable t) { + int levelInt = priorityToLevelInt(p); + differentiatedLog(null, CATEGORY_FQCN, levelInt, message, t); + } + + public void log(Priority p, Object message) { + int levelInt = priorityToLevelInt(p); + differentiatedLog(null, CATEGORY_FQCN, levelInt, message, null); + } + + private int priorityToLevelInt(Priority p) { + switch (p.level) { + case Level.TRACE_INT: + case Level.X_TRACE_INT: + return LocationAwareLogger.TRACE_INT; + case Priority.DEBUG_INT: + return LocationAwareLogger.DEBUG_INT; + case Priority.INFO_INT: + return LocationAwareLogger.INFO_INT; + case Priority.WARN_INT: + return LocationAwareLogger.WARN_INT; + case Priority.ERROR_INT: + return LocationAwareLogger.ERROR_INT; + case Priority.FATAL_INT: + return LocationAwareLogger.ERROR_INT; + default: + throw new IllegalStateException("Unknown Priority " + p); + } + } + + protected final String convertToString(Object message) { + if (message == null) { + return (String) message; + } else { + return message.toString(); + } + } + + public void setAdditivity(boolean additive) { + // nothing to do + } + + public void addAppender(Appender newAppender) { + // nothing to do + } + + public void setLevel(Level level) { + // nothing to do + } + + public boolean getAdditivity() { + return false; + } + + public void assertLog(boolean assertion, String msg) { + if (!assertion) + error(msg); + } + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/ConsoleAppender.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/ConsoleAppender.java index 2aee0e4..40e8f80 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/ConsoleAppender.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/ConsoleAppender.java @@ -1,20 +1,20 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.log4j; - -public class ConsoleAppender extends WriterAppender { - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.log4j; + +public class ConsoleAppender extends WriterAppender { + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/FileAppender.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/FileAppender.java old file mode 100644 new file mode 100755 index 1731f12..27e1f49 100755 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/FileAppender.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/FileAppender.java @@ -1,31 +1,31 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.log4j; - -public class FileAppender extends WriterAppender { - - public FileAppender() { - } - - public FileAppender(Layout layout, String filename) { - } - - public FileAppender(Layout layout, String filename, boolean append) { - } - - public FileAppender(Layout layout, String filename, boolean append, boolean bufferedIO, int bufferSize) { - } -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.log4j; + +public class FileAppender extends WriterAppender { + + public FileAppender() { + } + + public FileAppender(Layout layout, String filename) { + } + + public FileAppender(Layout layout, String filename, boolean append) { + } + + public FileAppender(Layout layout, String filename, boolean append, boolean bufferedIO, int bufferSize) { + } +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/Layout.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/Layout.java index 0be56b3..4ea3d99 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Layout.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Layout.java @@ -1,27 +1,27 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Contributors: Christian Trutz -package org.apache.log4j; - -/** - * This class is a minimal implementation of the original Log4J class. - * - * @author Christian Trutz - * */ -public class Layout { - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Contributors: Christian Trutz +package org.apache.log4j; + +/** + * This class is a minimal implementation of the original Log4J class. + * + * @author Christian Trutz + * */ +public class Layout { + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/Level.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/Level.java index 24d15aa..1cd0448 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Level.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Level.java @@ -1,228 +1,228 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Contributors: Kitching Simon -// Nicholas Wolff - -package org.apache.log4j; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamException; -import java.io.Serializable; - -/** - Defines the minimum set of levels recognized by the system, that is - OFF, FATAL, ERROR, - WARN, INFO, DEBUG and - ALL. - -

The Level class may be subclassed to define a larger - level set. - - @author Ceki Gülcü - - */ -public class Level extends Priority implements Serializable { - - /** - * TRACE level integer value. - * @since 1.2.12 - */ - public static final int TRACE_INT = 5000; - - // match jboss' xlevel - public static final int X_TRACE_INT = DEBUG_INT - 100; - - /** - The OFF has the highest possible rank and is - intended to turn off logging. */ - final static public Level OFF = new Level(OFF_INT, "OFF", 0); - - /** - The FATAL level designates very severe error - events that will presumably lead the application to abort. - */ - final static public Level FATAL = new Level(FATAL_INT, "FATAL", 0); - - /** - The ERROR level designates error events that - might still allow the application to continue running. */ - final static public Level ERROR = new Level(ERROR_INT, "ERROR", 3); - - /** - The WARN level designates potentially harmful situations. - */ - final static public Level WARN = new Level(WARN_INT, "WARN", 4); - - /** - The INFO level designates informational messages - that highlight the progress of the application at coarse-grained - level. */ - final static public Level INFO = new Level(INFO_INT, "INFO", 6); - - /** - The DEBUG Level designates fine-grained - informational events that are most useful to debug an - application. */ - final static public Level DEBUG = new Level(DEBUG_INT, "DEBUG", 7); - - /** - * The TRACE Level designates finer-grained - * informational events than the DEBUGALL has the lowest possible rank and is intended to - turn on all logging. */ - final static public Level ALL = new Level(ALL_INT, "ALL", 7); - - /** - * Serialization version id. - */ - static final long serialVersionUID = 3491141966387921974L; - - /** - Instantiate a Level object. - */ - protected Level(int level, String levelStr, int syslogEquivalent) { - super(level, levelStr, syslogEquivalent); - } - - /** - Convert the string passed as argument to a level. If the - conversion fails, then this method returns {@link #DEBUG}. - */ - public static Level toLevel(String sArg) { - return (Level) toLevel(sArg, Level.DEBUG); - } - - /** - Convert an integer passed as argument to a level. If the - conversion fails, then this method returns {@link #DEBUG}. - - */ - public static Level toLevel(int val) { - return (Level) toLevel(val, Level.DEBUG); - } - - /** - Convert an integer passed as argument to a level. If the - conversion fails, then this method returns the specified default. - */ - public static Level toLevel(int val, Level defaultLevel) { - switch (val) { - case ALL_INT: - return ALL; - case DEBUG_INT: - return Level.DEBUG; - case INFO_INT: - return Level.INFO; - case WARN_INT: - return Level.WARN; - case ERROR_INT: - return Level.ERROR; - case FATAL_INT: - return Level.FATAL; - case OFF_INT: - return OFF; - case TRACE_INT: - return Level.TRACE; - default: - return defaultLevel; - } - } - - /** - Convert the string passed as argument to a level. If the - conversion fails, then this method returns the value of - defaultLevel. - */ - public static Level toLevel(String sArg, Level defaultLevel) { - if (sArg == null) - return defaultLevel; - - String s = sArg.toUpperCase(); - - if (s.equals("ALL")) - return Level.ALL; - if (s.equals("DEBUG")) - return Level.DEBUG; - if (s.equals("INFO")) - return Level.INFO; - if (s.equals("WARN")) - return Level.WARN; - if (s.equals("ERROR")) - return Level.ERROR; - if (s.equals("FATAL")) - return Level.FATAL; - if (s.equals("OFF")) - return Level.OFF; - if (s.equals("TRACE")) - return Level.TRACE; - return defaultLevel; - } - - /** - * Custom deserialization of Level. - * @param s serialization stream. - * @throws IOException if IO exception. - * @throws ClassNotFoundException if class not found. - */ - private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException { - s.defaultReadObject(); - level = s.readInt(); - syslogEquivalent = s.readInt(); - levelStr = s.readUTF(); - if (levelStr == null) { - levelStr = ""; - } - } - - /** - * Serialize level. - * @param s serialization stream. - * @throws IOException if exception during serialization. - */ - private void writeObject(final ObjectOutputStream s) throws IOException { - s.defaultWriteObject(); - s.writeInt(level); - s.writeInt(syslogEquivalent); - s.writeUTF(levelStr); - } - - /** - * Resolved deserialized level to one of the stock instances. - * May be overridden in classes derived from Level. - * @return resolved object. - * @throws ObjectStreamException if exception during resolution. - */ - private Object readResolve() throws ObjectStreamException { - // - // if the deserialized object is exactly an instance of Level - // - if (getClass() == Level.class) { - return toLevel(level); - } - // - // extension of Level can't substitute stock item - // - return this; - } +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Contributors: Kitching Simon +// Nicholas Wolff + +package org.apache.log4j; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamException; +import java.io.Serializable; + +/** + Defines the minimum set of levels recognized by the system, that is + OFF, FATAL, ERROR, + WARN, INFO, DEBUG and + ALL. + +

The Level class may be subclassed to define a larger + level set. + + @author Ceki Gülcü + + */ +public class Level extends Priority implements Serializable { + + /** + * TRACE level integer value. + * @since 1.2.12 + */ + public static final int TRACE_INT = 5000; + + // match jboss' xlevel + public static final int X_TRACE_INT = DEBUG_INT - 100; + + /** + The OFF has the highest possible rank and is + intended to turn off logging. */ + final static public Level OFF = new Level(OFF_INT, "OFF", 0); + + /** + The FATAL level designates very severe error + events that will presumably lead the application to abort. + */ + final static public Level FATAL = new Level(FATAL_INT, "FATAL", 0); + + /** + The ERROR level designates error events that + might still allow the application to continue running. */ + final static public Level ERROR = new Level(ERROR_INT, "ERROR", 3); + + /** + The WARN level designates potentially harmful situations. + */ + final static public Level WARN = new Level(WARN_INT, "WARN", 4); + + /** + The INFO level designates informational messages + that highlight the progress of the application at coarse-grained + level. */ + final static public Level INFO = new Level(INFO_INT, "INFO", 6); + + /** + The DEBUG Level designates fine-grained + informational events that are most useful to debug an + application. */ + final static public Level DEBUG = new Level(DEBUG_INT, "DEBUG", 7); + + /** + * The TRACE Level designates finer-grained + * informational events than the DEBUGALL has the lowest possible rank and is intended to + turn on all logging. */ + final static public Level ALL = new Level(ALL_INT, "ALL", 7); + + /** + * Serialization version id. + */ + static final long serialVersionUID = 3491141966387921974L; + + /** + Instantiate a Level object. + */ + protected Level(int level, String levelStr, int syslogEquivalent) { + super(level, levelStr, syslogEquivalent); + } + + /** + Convert the string passed as argument to a level. If the + conversion fails, then this method returns {@link #DEBUG}. + */ + public static Level toLevel(String sArg) { + return (Level) toLevel(sArg, Level.DEBUG); + } + + /** + Convert an integer passed as argument to a level. If the + conversion fails, then this method returns {@link #DEBUG}. + + */ + public static Level toLevel(int val) { + return (Level) toLevel(val, Level.DEBUG); + } + + /** + Convert an integer passed as argument to a level. If the + conversion fails, then this method returns the specified default. + */ + public static Level toLevel(int val, Level defaultLevel) { + switch (val) { + case ALL_INT: + return ALL; + case DEBUG_INT: + return Level.DEBUG; + case INFO_INT: + return Level.INFO; + case WARN_INT: + return Level.WARN; + case ERROR_INT: + return Level.ERROR; + case FATAL_INT: + return Level.FATAL; + case OFF_INT: + return OFF; + case TRACE_INT: + return Level.TRACE; + default: + return defaultLevel; + } + } + + /** + Convert the string passed as argument to a level. If the + conversion fails, then this method returns the value of + defaultLevel. + */ + public static Level toLevel(String sArg, Level defaultLevel) { + if (sArg == null) + return defaultLevel; + + String s = sArg.toUpperCase(); + + if (s.equals("ALL")) + return Level.ALL; + if (s.equals("DEBUG")) + return Level.DEBUG; + if (s.equals("INFO")) + return Level.INFO; + if (s.equals("WARN")) + return Level.WARN; + if (s.equals("ERROR")) + return Level.ERROR; + if (s.equals("FATAL")) + return Level.FATAL; + if (s.equals("OFF")) + return Level.OFF; + if (s.equals("TRACE")) + return Level.TRACE; + return defaultLevel; + } + + /** + * Custom deserialization of Level. + * @param s serialization stream. + * @throws IOException if IO exception. + * @throws ClassNotFoundException if class not found. + */ + private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException { + s.defaultReadObject(); + level = s.readInt(); + syslogEquivalent = s.readInt(); + levelStr = s.readUTF(); + if (levelStr == null) { + levelStr = ""; + } + } + + /** + * Serialize level. + * @param s serialization stream. + * @throws IOException if exception during serialization. + */ + private void writeObject(final ObjectOutputStream s) throws IOException { + s.defaultWriteObject(); + s.writeInt(level); + s.writeInt(syslogEquivalent); + s.writeUTF(levelStr); + } + + /** + * Resolved deserialized level to one of the stock instances. + * May be overridden in classes derived from Level. + * @return resolved object. + * @throws ObjectStreamException if exception during resolution. + */ + private Object readResolve() throws ObjectStreamException { + // + // if the deserialized object is exactly an instance of Level + // + if (getClass() == Level.class) { + return toLevel(level); + } + // + // extension of Level can't substitute stock item + // + return this; + } }diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/Log4jLoggerFactory.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/Log4jLoggerFactory.java index 4bf7e77..30b3522 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Log4jLoggerFactory.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Log4jLoggerFactory.java @@ -1,59 +1,59 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -import org.apache.log4j.spi.LoggerFactory; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * This class is a factory that creates and maintains org.apache.log4j.Loggers - * wrapping org.slf4j.Loggers. - * - * It keeps a hashtable of all created org.apache.log4j.Logger instances so that - * all newly created instances are not duplicates of existing loggers. - * - * @author Sébastien Pennec - */ -class Log4jLoggerFactory { - - // String, Logger - private static ConcurrentMap log4jLoggers = new ConcurrentHashMap(); - - public static Logger getLogger(String name) { - org.apache.log4j.Logger instance = log4jLoggers.get(name); - if (instance != null) { - return instance; - } else { - Logger newInstance = new Logger(name); - Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance); - return oldInstance == null ? newInstance : oldInstance; - } - } - - public static Logger getLogger(String name, LoggerFactory loggerFactory) { - org.apache.log4j.Logger instance = log4jLoggers.get(name); - if (instance != null) { - return instance; - } else { - Logger newInstance = loggerFactory.makeNewLoggerInstance(name); - Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance); - return oldInstance == null ? newInstance : oldInstance; - } - } -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j; + +import org.apache.log4j.spi.LoggerFactory; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * This class is a factory that creates and maintains org.apache.log4j.Loggers + * wrapping org.slf4j.Loggers. + * + * It keeps a hashtable of all created org.apache.log4j.Logger instances so that + * all newly created instances are not duplicates of existing loggers. + * + * @author Sébastien Pennec + */ +class Log4jLoggerFactory { + + // String, Logger + private static ConcurrentMap log4jLoggers = new ConcurrentHashMap(); + + public static Logger getLogger(String name) { + org.apache.log4j.Logger instance = log4jLoggers.get(name); + if (instance != null) { + return instance; + } else { + Logger newInstance = new Logger(name); + Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance); + return oldInstance == null ? newInstance : oldInstance; + } + } + + public static Logger getLogger(String name, LoggerFactory loggerFactory) { + org.apache.log4j.Logger instance = log4jLoggers.get(name); + if (instance != null) { + return instance; + } else { + Logger newInstance = loggerFactory.makeNewLoggerInstance(name); + Logger oldInstance = log4jLoggers.putIfAbsent(name, newInstance); + return oldInstance == null ? newInstance : oldInstance; + } + } +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/LogManager.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/LogManager.java index 9e8f41d..57b6b25 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/LogManager.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/LogManager.java @@ -1,87 +1,87 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -import org.apache.log4j.spi.LoggerFactory; - -import java.util.Enumeration; -import java.util.Vector; - -/** - *

- * This class is a minimal implementation of the original - * org.apache.log4j.LogManager class (as found in log4j 1.2) - * delegating all calls to SLF4J. - *

- *

- * This implementation does NOT implement the setRepositorySelector(), - * getLoggerRepository(), exists(), getCurrentLoggers(), shutdown() and - * resetConfiguration() methods which do not have SLF4J equivalents. - * - * @author Ceki Gülcü - */ -@SuppressWarnings("rawtypes") -public class LogManager { - - public static Logger getRootLogger() { - return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); - } - - public static Logger getLogger(final String name) { - return Log4jLoggerFactory.getLogger(name); - } - - public static Logger getLogger(final Class clazz) { - return Log4jLoggerFactory.getLogger(clazz.getName()); - } - - /** - * Returns a logger instance created by loggerFactory. This method was requested in - * SLF4J-225. Note that - * log4j-over-slf4j does not ship with a LoggerFactory implementation. If this - * method is called, the caller must provide his/her own implementation. - * - * @param name the name of the desired logger - * @param loggerFactory an instance of {@link LoggerFactory} - * @return returns a logger instance created by loggerFactory - * @since 1.6.6 - */ - public static Logger getLogger(String name, LoggerFactory loggerFactory) { - return loggerFactory.makeNewLoggerInstance(name); - } - - /** - * This bogus implementation returns an empty enumeration. - * - * @return - */ - public static Enumeration getCurrentLoggers() { - return new Vector().elements(); - } - - /** - * Implemented as NOP. - */ - public static void shutdown() { - } - - /** - * Implemented as NOP. - */ - public static void resetConfiguration() { - } -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j; + +import org.apache.log4j.spi.LoggerFactory; + +import java.util.Enumeration; +import java.util.Vector; + +/** + *

+ * This class is a minimal implementation of the original + * org.apache.log4j.LogManager class (as found in log4j 1.2) + * delegating all calls to SLF4J. + *

+ *

+ * This implementation does NOT implement the setRepositorySelector(), + * getLoggerRepository(), exists(), getCurrentLoggers(), shutdown() and + * resetConfiguration() methods which do not have SLF4J equivalents. + * + * @author Ceki Gülcü + */ +@SuppressWarnings("rawtypes") +public class LogManager { + + public static Logger getRootLogger() { + return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + } + + public static Logger getLogger(final String name) { + return Log4jLoggerFactory.getLogger(name); + } + + public static Logger getLogger(final Class clazz) { + return Log4jLoggerFactory.getLogger(clazz.getName()); + } + + /** + * Returns a logger instance created by loggerFactory. This method was requested in + * SLF4J-225. Note that + * log4j-over-slf4j does not ship with a LoggerFactory implementation. If this + * method is called, the caller must provide his/her own implementation. + * + * @param name the name of the desired logger + * @param loggerFactory an instance of {@link LoggerFactory} + * @return returns a logger instance created by loggerFactory + * @since 1.6.6 + */ + public static Logger getLogger(String name, LoggerFactory loggerFactory) { + return loggerFactory.makeNewLoggerInstance(name); + } + + /** + * This bogus implementation returns an empty enumeration. + * + * @return + */ + public static Enumeration getCurrentLoggers() { + return new Vector().elements(); + } + + /** + * Implemented as NOP. + */ + public static void shutdown() { + } + + /** + * Implemented as NOP. + */ + public static void resetConfiguration() { + } +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/Logger.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/Logger.java index 6290c50..12ec176 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Logger.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Logger.java @@ -1,84 +1,84 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -import org.apache.log4j.spi.LoggerFactory; -import org.slf4j.spi.LocationAwareLogger; - -/** - *

- * This class is a minimal implementation of the original - * org.apache.log4j.Logger class (as found in log4j 1.2) - * delegating all calls to a {@link org.slf4j.Logger} instance. - *

- * - * @author Ceki Gülcü - * */ -@SuppressWarnings("rawtypes") -public class Logger extends Category { - - private static final String LOGGER_FQCN = Logger.class.getName(); - - protected Logger(String name) { - super(name); - } - - public static Logger getLogger(String name) { - return Log4jLoggerFactory.getLogger(name); - } - - public static Logger getLogger(String name, LoggerFactory loggerFactory) { - return Log4jLoggerFactory.getLogger(name, loggerFactory); - } - - public static Logger getLogger(Class clazz) { - return getLogger(clazz.getName()); - } - - /** - * Does the obvious. - * - * @return - */ - public static Logger getRootLogger() { - return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); - } - - /** - * Delegates to {@link org.slf4j.Logger#isTraceEnabled} - * method of SLF4J. - */ - public boolean isTraceEnabled() { - return slf4jLogger.isTraceEnabled(); - } - - /** - * Delegates to {@link org.slf4j.Logger#trace(String)} method in SLF4J. - */ - public void trace(Object message) { - differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, null); - } - - /** - * Delegates to {@link org.slf4j.Logger#trace(String,Throwable)} - * method in SLF4J. - */ - public void trace(Object message, Throwable t) { - differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, null); - } - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j; + +import org.apache.log4j.spi.LoggerFactory; +import org.slf4j.spi.LocationAwareLogger; + +/** + *

+ * This class is a minimal implementation of the original + * org.apache.log4j.Logger class (as found in log4j 1.2) + * delegating all calls to a {@link org.slf4j.Logger} instance. + *

+ * + * @author Ceki Gülcü + * */ +@SuppressWarnings("rawtypes") +public class Logger extends Category { + + private static final String LOGGER_FQCN = Logger.class.getName(); + + protected Logger(String name) { + super(name); + } + + public static Logger getLogger(String name) { + return Log4jLoggerFactory.getLogger(name); + } + + public static Logger getLogger(String name, LoggerFactory loggerFactory) { + return Log4jLoggerFactory.getLogger(name, loggerFactory); + } + + public static Logger getLogger(Class clazz) { + return getLogger(clazz.getName()); + } + + /** + * Does the obvious. + * + * @return + */ + public static Logger getRootLogger() { + return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + } + + /** + * Delegates to {@link org.slf4j.Logger#isTraceEnabled} + * method of SLF4J. + */ + public boolean isTraceEnabled() { + return slf4jLogger.isTraceEnabled(); + } + + /** + * Delegates to {@link org.slf4j.Logger#trace(String)} method in SLF4J. + */ + public void trace(Object message) { + differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, null); + } + + /** + * Delegates to {@link org.slf4j.Logger#trace(String,Throwable)} + * method in SLF4J. + */ + public void trace(Object message, Throwable t) { + differentiatedLog(null, LOGGER_FQCN, LocationAwareLogger.TRACE_INT, message, null); + } + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/MDC.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/MDC.java index 03b892b..c4a8eff 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/MDC.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/MDC.java @@ -1,64 +1,64 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -import java.util.Hashtable; -import java.util.Map; - -public class MDC { - - public static void put(String key, String value) { - org.slf4j.MDC.put(key, value); - } - - public static void put(String key, Object value) { - if (value != null) { - put(key, value.toString()); - } else { - put(key, null); - } - } - - public static Object get(String key) { - return org.slf4j.MDC.get(key); - } - - public static void remove(String key) { - org.slf4j.MDC.remove(key); - } - - public static void clear() { - org.slf4j.MDC.clear(); - } - - /** - * This method is not part of the Log4J public API. However it - * has been called by other projects. This method is here temporarily - * until projects who are depending on this method release fixes. - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Deprecated - public static Hashtable getContext() { - Map map = org.slf4j.MDC.getCopyOfContextMap(); - - if (map != null) { - return new Hashtable(map); - } else { - return new Hashtable(); - } - } -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j; + +import java.util.Hashtable; +import java.util.Map; + +public class MDC { + + public static void put(String key, String value) { + org.slf4j.MDC.put(key, value); + } + + public static void put(String key, Object value) { + if (value != null) { + put(key, value.toString()); + } else { + put(key, null); + } + } + + public static Object get(String key) { + return org.slf4j.MDC.get(key); + } + + public static void remove(String key) { + org.slf4j.MDC.remove(key); + } + + public static void clear() { + org.slf4j.MDC.clear(); + } + + /** + * This method is not part of the Log4J public API. However it + * has been called by other projects. This method is here temporarily + * until projects who are depending on this method release fixes. + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Deprecated + public static Hashtable getContext() { + Map map = org.slf4j.MDC.getCopyOfContextMap(); + + if (map != null) { + return new Hashtable(map); + } else { + return new Hashtable(); + } + } +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/NDC.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/NDC.java index 8aec3eb..b8e8929 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/NDC.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/NDC.java @@ -1,102 +1,102 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -import org.slf4j.MDC; - -import java.util.Stack; - -/** - * A log4j's NDC implemented in terms of SLF4J MDC primitives. - * - * @since SLF4J 1.6.0 - */ - -public class NDC { - - public final static String PREFIX = "NDC"; - - public static void clear() { - int depth = getDepth(); - for (int i = 0; i < depth; i++) { - String key = PREFIX + i; - MDC.remove(key); - } - } - - @SuppressWarnings("rawtypes") - public static Stack cloneStack() { - return null; - } - - @SuppressWarnings("rawtypes") - public static void inherit(Stack stack) { - } - - static public String get() { - return null; - } - - public static int getDepth() { - int i = 0; - while (true) { - String val = MDC.get(PREFIX + i); - if (val != null) { - i++; - } else { - break; - } - } - return i; - } - - public static String pop() { - int next = getDepth(); - if (next == 0) { - return ""; - } - int last = next - 1; - String key = PREFIX + last; - String val = MDC.get(key); - MDC.remove(key); - return val; - } - - public static String peek() { - int next = getDepth(); - if (next == 0) { - return ""; - } - int last = next - 1; - String key = PREFIX + last; - String val = MDC.get(key); - return val; - } - - public static void push(String message) { - int next = getDepth(); - MDC.put(PREFIX + next, message); - } - - static public void remove() { - clear(); - } - - static public void setMaxDepth(int maxDepth) { - } - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j; + +import org.slf4j.MDC; + +import java.util.Stack; + +/** + * A log4j's NDC implemented in terms of SLF4J MDC primitives. + * + * @since SLF4J 1.6.0 + */ + +public class NDC { + + public final static String PREFIX = "NDC"; + + public static void clear() { + int depth = getDepth(); + for (int i = 0; i < depth; i++) { + String key = PREFIX + i; + MDC.remove(key); + } + } + + @SuppressWarnings("rawtypes") + public static Stack cloneStack() { + return null; + } + + @SuppressWarnings("rawtypes") + public static void inherit(Stack stack) { + } + + static public String get() { + return null; + } + + public static int getDepth() { + int i = 0; + while (true) { + String val = MDC.get(PREFIX + i); + if (val != null) { + i++; + } else { + break; + } + } + return i; + } + + public static String pop() { + int next = getDepth(); + if (next == 0) { + return ""; + } + int last = next - 1; + String key = PREFIX + last; + String val = MDC.get(key); + MDC.remove(key); + return val; + } + + public static String peek() { + int next = getDepth(); + if (next == 0) { + return ""; + } + int last = next - 1; + String key = PREFIX + last; + String val = MDC.get(key); + return val; + } + + public static void push(String message) { + int next = getDepth(); + MDC.put(PREFIX + next, message); + } + + static public void remove() { + clear(); + } + + static public void setMaxDepth(int maxDepth) { + } + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/PatternLayout.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/PatternLayout.java index 021ccfe..a38df63 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/PatternLayout.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/PatternLayout.java @@ -1,35 +1,35 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Contributors: Christian Trutz -package org.apache.log4j; - -/** - * This class is a minimal implementation of the original Log4J class. - * - * @author Christian Trutz - * */ -public class PatternLayout extends Layout { - - public PatternLayout() { - super(); - } - - public PatternLayout(String pattern) { - super(); - } - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Contributors: Christian Trutz +package org.apache.log4j; + +/** + * This class is a minimal implementation of the original Log4J class. + * + * @author Christian Trutz + * */ +public class PatternLayout extends Layout { + + public PatternLayout() { + super(); + } + + public PatternLayout(String pattern) { + super(); + } + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/Priority.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/Priority.java index e8886e1..bb4f8d4 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Priority.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Priority.java @@ -1,170 +1,170 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Contributors: Kitching Simon - -package org.apache.log4j; - -// Contributors: Kitching Simon - -/** - Refrain from using this class directly, use - the {@link Level} class instead. - - @author Ceki Gülcü */ -public class Priority { - - transient int level; - transient String levelStr; - transient int syslogEquivalent; - - public final static int OFF_INT = Integer.MAX_VALUE; - public final static int FATAL_INT = 50000; - public final static int ERROR_INT = 40000; - public final static int WARN_INT = 30000; - public final static int INFO_INT = 20000; - public final static int DEBUG_INT = 10000; - // public final static int FINE_INT = DEBUG_INT; - public final static int ALL_INT = Integer.MIN_VALUE; - - /** - * @deprecated Use {@link Level#FATAL} instead. - */ - final static public Priority FATAL = new Level(FATAL_INT, "FATAL", 0); - - /** - * @deprecated Use {@link Level#ERROR} instead. - */ - final static public Priority ERROR = new Level(ERROR_INT, "ERROR", 3); - - /** - * @deprecated Use {@link Level#WARN} instead. - */ - final static public Priority WARN = new Level(WARN_INT, "WARN", 4); - - /** - * @deprecated Use {@link Level#INFO} instead. - */ - final static public Priority INFO = new Level(INFO_INT, "INFO", 6); - - /** - * @deprecated Use {@link Level#DEBUG} instead. - */ - final static public Priority DEBUG = new Level(DEBUG_INT, "DEBUG", 7); - - /** - * Default constructor for deserialization. - */ - protected Priority() { - level = DEBUG_INT; - levelStr = "DEBUG"; - syslogEquivalent = 7; - } - - /** - Instantiate a level object. - */ - protected Priority(int level, String levelStr, int syslogEquivalent) { - this.level = level; - this.levelStr = levelStr; - this.syslogEquivalent = syslogEquivalent; - } - - /** - Two priorities are equal if their level fields are equal. - @since 1.2 - */ - public boolean equals(Object o) { - if (o instanceof Priority) { - Priority r = (Priority) o; - return (this.level == r.level); - } else { - return false; - } - } - - /** - Return the syslog equivalent of this priority as an integer. - */ - public final int getSyslogEquivalent() { - return syslogEquivalent; - } - - /** - Returns true if this level has a higher or equal - level than the level passed as argument, false - otherwise. - -

You should think twice before overriding the default - implementation of isGreaterOrEqual method. - - */ - public boolean isGreaterOrEqual(Priority r) { - return level >= r.level; - } - - /** - Return all possible priorities as an array of Level objects in - descending order. - - @deprecated This method will be removed with no replacement. - */ - public static Priority[] getAllPossiblePriorities() { - return new Priority[] { Priority.FATAL, Priority.ERROR, Level.WARN, Priority.INFO, Priority.DEBUG }; - } - - /** - Returns the string representation of this priority. - */ - final public String toString() { - return levelStr; - } - - /** - Returns the integer representation of this level. - */ - public final int toInt() { - return level; - } - - /** - * @deprecated Please use the {@link Level#toLevel(String)} method instead. - */ - public static Priority toPriority(String sArg) { - return Level.toLevel(sArg); - } - - /** - * @deprecated Please use the {@link Level#toLevel(int)} method instead. - */ - public static Priority toPriority(int val) { - return toPriority(val, Priority.DEBUG); - } - - /** - * @deprecated Please use the {@link Level#toLevel(int, Level)} method instead. - */ - public static Priority toPriority(int val, Priority defaultPriority) { - return Level.toLevel(val, (Level) defaultPriority); - } - - /** - * @deprecated Please use the {@link Level#toLevel(String, Level)} method instead. - */ - public static Priority toPriority(String sArg, Priority defaultPriority) { - return Level.toLevel(sArg, (Level) defaultPriority); - } +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Contributors: Kitching Simon + +package org.apache.log4j; + +// Contributors: Kitching Simon + +/** + Refrain from using this class directly, use + the {@link Level} class instead. + + @author Ceki Gülcü */ +public class Priority { + + transient int level; + transient String levelStr; + transient int syslogEquivalent; + + public final static int OFF_INT = Integer.MAX_VALUE; + public final static int FATAL_INT = 50000; + public final static int ERROR_INT = 40000; + public final static int WARN_INT = 30000; + public final static int INFO_INT = 20000; + public final static int DEBUG_INT = 10000; + // public final static int FINE_INT = DEBUG_INT; + public final static int ALL_INT = Integer.MIN_VALUE; + + /** + * @deprecated Use {@link Level#FATAL} instead. + */ + final static public Priority FATAL = new Level(FATAL_INT, "FATAL", 0); + + /** + * @deprecated Use {@link Level#ERROR} instead. + */ + final static public Priority ERROR = new Level(ERROR_INT, "ERROR", 3); + + /** + * @deprecated Use {@link Level#WARN} instead. + */ + final static public Priority WARN = new Level(WARN_INT, "WARN", 4); + + /** + * @deprecated Use {@link Level#INFO} instead. + */ + final static public Priority INFO = new Level(INFO_INT, "INFO", 6); + + /** + * @deprecated Use {@link Level#DEBUG} instead. + */ + final static public Priority DEBUG = new Level(DEBUG_INT, "DEBUG", 7); + + /** + * Default constructor for deserialization. + */ + protected Priority() { + level = DEBUG_INT; + levelStr = "DEBUG"; + syslogEquivalent = 7; + } + + /** + Instantiate a level object. + */ + protected Priority(int level, String levelStr, int syslogEquivalent) { + this.level = level; + this.levelStr = levelStr; + this.syslogEquivalent = syslogEquivalent; + } + + /** + Two priorities are equal if their level fields are equal. + @since 1.2 + */ + public boolean equals(Object o) { + if (o instanceof Priority) { + Priority r = (Priority) o; + return (this.level == r.level); + } else { + return false; + } + } + + /** + Return the syslog equivalent of this priority as an integer. + */ + public final int getSyslogEquivalent() { + return syslogEquivalent; + } + + /** + Returns true if this level has a higher or equal + level than the level passed as argument, false + otherwise. + +

You should think twice before overriding the default + implementation of isGreaterOrEqual method. + + */ + public boolean isGreaterOrEqual(Priority r) { + return level >= r.level; + } + + /** + Return all possible priorities as an array of Level objects in + descending order. + + @deprecated This method will be removed with no replacement. + */ + public static Priority[] getAllPossiblePriorities() { + return new Priority[] { Priority.FATAL, Priority.ERROR, Level.WARN, Priority.INFO, Priority.DEBUG }; + } + + /** + Returns the string representation of this priority. + */ + final public String toString() { + return levelStr; + } + + /** + Returns the integer representation of this level. + */ + public final int toInt() { + return level; + } + + /** + * @deprecated Please use the {@link Level#toLevel(String)} method instead. + */ + public static Priority toPriority(String sArg) { + return Level.toLevel(sArg); + } + + /** + * @deprecated Please use the {@link Level#toLevel(int)} method instead. + */ + public static Priority toPriority(int val) { + return toPriority(val, Priority.DEBUG); + } + + /** + * @deprecated Please use the {@link Level#toLevel(int, Level)} method instead. + */ + public static Priority toPriority(int val, Priority defaultPriority) { + return Level.toLevel(val, (Level) defaultPriority); + } + + /** + * @deprecated Please use the {@link Level#toLevel(String, Level)} method instead. + */ + public static Priority toPriority(String sArg, Priority defaultPriority) { + return Level.toLevel(sArg, (Level) defaultPriority); + } }diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/PropertyConfigurator.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/PropertyConfigurator.java index 7f7bd2f..baf4c13 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/PropertyConfigurator.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/PropertyConfigurator.java @@ -1,52 +1,52 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -import java.net.URL; -import java.util.Properties; - -import org.apache.log4j.spi.Configurator; -import org.apache.log4j.spi.LoggerRepository; - -/** - * An nop implementation of PropertyConfigurator. - */ -public class PropertyConfigurator implements Configurator { - public static void configure(Properties properties) { - } - - public static void configure(String configFilename) { - } - - public static void configure(java.net.URL configURL) { - } - - public static void configureAndWatch(String configFilename) { - } - - public static void configureAndWatch(String configFilename, long delay) { - } - - public void doConfigure(Properties properties, LoggerRepository hierarchy) { - } - - public void doConfigure(String configFileName, LoggerRepository hierarchy) { - } - - public void doConfigure(URL configURL, LoggerRepository hierarchy) { - } -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j; + +import java.net.URL; +import java.util.Properties; + +import org.apache.log4j.spi.Configurator; +import org.apache.log4j.spi.LoggerRepository; + +/** + * An nop implementation of PropertyConfigurator. + */ +public class PropertyConfigurator implements Configurator { + public static void configure(Properties properties) { + } + + public static void configure(String configFilename) { + } + + public static void configure(java.net.URL configURL) { + } + + public static void configureAndWatch(String configFilename) { + } + + public static void configureAndWatch(String configFilename, long delay) { + } + + public void doConfigure(Properties properties, LoggerRepository hierarchy) { + } + + public void doConfigure(String configFileName, LoggerRepository hierarchy) { + } + + public void doConfigure(URL configURL, LoggerRepository hierarchy) { + } +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/RollingFileAppender.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/RollingFileAppender.java index f902b01..b329597 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/RollingFileAppender.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/RollingFileAppender.java @@ -1,49 +1,49 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Contributors: Christian Trutz -package org.apache.log4j; - -import java.io.IOException; - -/** - * This class is a minimal implementation of the original Log4J class. - * - * @author Christian Trutz - * */ -public class RollingFileAppender { - - public RollingFileAppender() { - super(); - } - - public RollingFileAppender(Layout layout, String filename) throws IOException { - super(); - } - - public RollingFileAppender(Layout layout, String filename, boolean append) throws IOException { - super(); - } - - public void setMaxBackupIndex(int maxBackups) { - // nothing to do - } - - public void setMaximumFileSize(long maxFileSize) { - // nothing to do - } - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Contributors: Christian Trutz +package org.apache.log4j; + +import java.io.IOException; + +/** + * This class is a minimal implementation of the original Log4J class. + * + * @author Christian Trutz + * */ +public class RollingFileAppender { + + public RollingFileAppender() { + super(); + } + + public RollingFileAppender(Layout layout, String filename) throws IOException { + super(); + } + + public RollingFileAppender(Layout layout, String filename, boolean append) throws IOException { + super(); + } + + public void setMaxBackupIndex(int maxBackups) { + // nothing to do + } + + public void setMaximumFileSize(long maxFileSize) { + // nothing to do + } + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/SimpleLayout.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/SimpleLayout.java index 3e2c273..c2765f8 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/SimpleLayout.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/SimpleLayout.java @@ -1,19 +1,19 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.log4j; - -public class SimpleLayout extends Layout { -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.log4j; + +public class SimpleLayout extends Layout { +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/WriterAppender.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/WriterAppender.java index 873175d..cb4df57 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/WriterAppender.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/WriterAppender.java @@ -1,20 +1,20 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.log4j; - -public class WriterAppender extends AppenderSkeleton { - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.log4j; + +public class WriterAppender extends AppenderSkeleton { + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/helpers/LogLog.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/helpers/LogLog.java index 18ea234..01157ab 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/helpers/LogLog.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/helpers/LogLog.java @@ -1,161 +1,161 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j.helpers; - -/** - This class used to output log statements from within the log4j package. - -

Log4j components cannot make log4j logging calls. However, it is - sometimes useful for the user to learn about what log4j is - doing. You can enable log4j internal logging by defining the - log4j.configDebug variable. - -

All log4j internal debug calls go to System.out - where as internal error messages are sent to - System.err. All internal messages are prepended with - the string "log4j: ". - - @since 0.8.2 - @author Ceki Gülcü -*/ -public class LogLog { - - /** - Defining this value makes log4j print log4j-internal debug - statements to System.out. - -

The value of this string is log4j.debug. - -

Note that the search for all option names is case sensitive. */ - public static final String DEBUG_KEY = "log4j.debug"; - - /** - Defining this value makes log4j components print log4j-internal - debug statements to System.out. - -

The value of this string is log4j.configDebug. - -

Note that the search for all option names is case sensitive. - - @deprecated Use {@link #DEBUG_KEY} instead. - */ - public static final String CONFIG_DEBUG_KEY = "log4j.configDebug"; - - protected static boolean debugEnabled = false; - - /** - In quietMode not even errors generate any output. - */ - private static boolean quietMode = false; - - private static final String PREFIX = "log4j: "; - private static final String ERR_PREFIX = "log4j:ERROR "; - private static final String WARN_PREFIX = "log4j:WARN "; - - static { - } - - /** - Allows to enable/disable log4j internal logging. - */ - static public void setInternalDebugging(boolean enabled) { - debugEnabled = enabled; - } - - /** - This method is used to output log4j internal debug - statements. Output goes to System.out. - */ - public static void debug(String msg) { - if (debugEnabled && !quietMode) { - System.out.println(PREFIX + msg); - } - } - - /** - This method is used to output log4j internal debug - statements. Output goes to System.out. - */ - public static void debug(String msg, Throwable t) { - if (debugEnabled && !quietMode) { - System.out.println(PREFIX + msg); - if (t != null) - t.printStackTrace(System.out); - } - } - - /** - This method is used to output log4j internal error - statements. There is no way to disable error statements. - Output goes to System.err. - */ - public static void error(String msg) { - if (quietMode) - return; - System.err.println(ERR_PREFIX + msg); - } - - /** - This method is used to output log4j internal error - statements. There is no way to disable error statements. - Output goes to System.err. - */ - public static void error(String msg, Throwable t) { - if (quietMode) - return; - - System.err.println(ERR_PREFIX + msg); - if (t != null) { - t.printStackTrace(); - } - } - - /** - In quite mode no LogLog generates strictly no output, not even - for errors. - - @param quietMode A true for not - */ - public static void setQuietMode(boolean quietMode) { - LogLog.quietMode = quietMode; - } - - /** - This method is used to output log4j internal warning - statements. There is no way to disable warning statements. - Output goes to System.err. */ - public static void warn(String msg) { - if (quietMode) - return; - - System.err.println(WARN_PREFIX + msg); - } - - /** - This method is used to output log4j internal warnings. There is - no way to disable warning statements. Output goes to - System.err. */ - public static void warn(String msg, Throwable t) { - if (quietMode) - return; - - System.err.println(WARN_PREFIX + msg); - if (t != null) { - t.printStackTrace(); - } - } -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.helpers; + +/** + This class used to output log statements from within the log4j package. + +

Log4j components cannot make log4j logging calls. However, it is + sometimes useful for the user to learn about what log4j is + doing. You can enable log4j internal logging by defining the + log4j.configDebug variable. + +

All log4j internal debug calls go to System.out + where as internal error messages are sent to + System.err. All internal messages are prepended with + the string "log4j: ". + + @since 0.8.2 + @author Ceki Gülcü +*/ +public class LogLog { + + /** + Defining this value makes log4j print log4j-internal debug + statements to System.out. + +

The value of this string is log4j.debug. + +

Note that the search for all option names is case sensitive. */ + public static final String DEBUG_KEY = "log4j.debug"; + + /** + Defining this value makes log4j components print log4j-internal + debug statements to System.out. + +

The value of this string is log4j.configDebug. + +

Note that the search for all option names is case sensitive. + + @deprecated Use {@link #DEBUG_KEY} instead. + */ + public static final String CONFIG_DEBUG_KEY = "log4j.configDebug"; + + protected static boolean debugEnabled = false; + + /** + In quietMode not even errors generate any output. + */ + private static boolean quietMode = false; + + private static final String PREFIX = "log4j: "; + private static final String ERR_PREFIX = "log4j:ERROR "; + private static final String WARN_PREFIX = "log4j:WARN "; + + static { + } + + /** + Allows to enable/disable log4j internal logging. + */ + static public void setInternalDebugging(boolean enabled) { + debugEnabled = enabled; + } + + /** + This method is used to output log4j internal debug + statements. Output goes to System.out. + */ + public static void debug(String msg) { + if (debugEnabled && !quietMode) { + System.out.println(PREFIX + msg); + } + } + + /** + This method is used to output log4j internal debug + statements. Output goes to System.out. + */ + public static void debug(String msg, Throwable t) { + if (debugEnabled && !quietMode) { + System.out.println(PREFIX + msg); + if (t != null) + t.printStackTrace(System.out); + } + } + + /** + This method is used to output log4j internal error + statements. There is no way to disable error statements. + Output goes to System.err. + */ + public static void error(String msg) { + if (quietMode) + return; + System.err.println(ERR_PREFIX + msg); + } + + /** + This method is used to output log4j internal error + statements. There is no way to disable error statements. + Output goes to System.err. + */ + public static void error(String msg, Throwable t) { + if (quietMode) + return; + + System.err.println(ERR_PREFIX + msg); + if (t != null) { + t.printStackTrace(); + } + } + + /** + In quite mode no LogLog generates strictly no output, not even + for errors. + + @param quietMode A true for not + */ + public static void setQuietMode(boolean quietMode) { + LogLog.quietMode = quietMode; + } + + /** + This method is used to output log4j internal warning + statements. There is no way to disable warning statements. + Output goes to System.err. */ + public static void warn(String msg) { + if (quietMode) + return; + + System.err.println(WARN_PREFIX + msg); + } + + /** + This method is used to output log4j internal warnings. There is + no way to disable warning statements. Output goes to + System.err. */ + public static void warn(String msg, Throwable t) { + if (quietMode) + return; + + System.err.println(WARN_PREFIX + msg); + if (t != null) { + t.printStackTrace(); + } + } +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/helpers/NullEnumeration.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/helpers/NullEnumeration.java index a10ce57..9c92396 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/helpers/NullEnumeration.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/helpers/NullEnumeration.java @@ -1,47 +1,47 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j.helpers; - -import java.util.Enumeration; -import java.util.NoSuchElementException; - -/** - * An always-empty Enumerator. - * - * @author Anders Kristensen - * @since version 1.0 - */ -@SuppressWarnings("rawtypes") -public class NullEnumeration implements Enumeration { - private static final NullEnumeration instance = new NullEnumeration(); - - private NullEnumeration() { - } - - public static NullEnumeration getInstance() { - return instance; - } - - public boolean hasMoreElements() { - return false; - } - - public Object nextElement() { - throw new NoSuchElementException(); - } +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.helpers; + +import java.util.Enumeration; +import java.util.NoSuchElementException; + +/** + * An always-empty Enumerator. + * + * @author Anders Kristensen + * @since version 1.0 + */ +@SuppressWarnings("rawtypes") +public class NullEnumeration implements Enumeration { + private static final NullEnumeration instance = new NullEnumeration(); + + private NullEnumeration() { + } + + public static NullEnumeration getInstance() { + return instance; + } + + public boolean hasMoreElements() { + return false; + } + + public Object nextElement() { + throw new NoSuchElementException(); + } }diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/package.html b/log4j-over-slf4j/src/main/java/org/apache/log4j/package.html index 357d0e6..c3c8346 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/package.html +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/package.html @@ -1,18 +1,18 @@ - - - - - - - - - - - -

An rather minimal but sufficient implementation redirecting all - calls to a log4j logger to a logback logger.

- - - - - + + + + + + + + + + + +

An rather minimal but sufficient implementation redirecting all + calls to a log4j logger to a logback logger.

+ + + + + diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/Configurator.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/Configurator.java index ef6ed89..abf7560 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/Configurator.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/Configurator.java @@ -1,52 +1,52 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j.spi; - -import org.apache.log4j.spi.LoggerRepository; -import java.net.URL; - -/** - Implemented by classes capable of configuring log4j using a URL. - - @since 1.0 - @author Anders Kristensen - */ -public interface Configurator { - - /** - Special level value signifying inherited behaviour. The current - value of this string constant is inherited. {@link #NULL} - is a synonym. */ - public static final String INHERITED = "inherited"; - - /** - Special level signifying inherited behaviour, same as {@link - #INHERITED}. The current value of this string constant is - null. */ - public static final String NULL = "null"; - - /** - Interpret a resource pointed by a URL and set up log4j accordingly. - - The configuration is done relative to the hierarchy - parameter. - - @param url The URL to parse - @param repository The hierarchy to operation upon. - */ - void doConfigure(URL url, LoggerRepository repository); -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.spi; + +import org.apache.log4j.spi.LoggerRepository; +import java.net.URL; + +/** + Implemented by classes capable of configuring log4j using a URL. + + @since 1.0 + @author Anders Kristensen + */ +public interface Configurator { + + /** + Special level value signifying inherited behaviour. The current + value of this string constant is inherited. {@link #NULL} + is a synonym. */ + public static final String INHERITED = "inherited"; + + /** + Special level signifying inherited behaviour, same as {@link + #INHERITED}. The current value of this string constant is + null. */ + public static final String NULL = "null"; + + /** + Interpret a resource pointed by a URL and set up log4j accordingly. + + The configuration is done relative to the hierarchy + parameter. + + @param url The URL to parse + @param repository The hierarchy to operation upon. + */ + void doConfigure(URL url, LoggerRepository repository); +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/ErrorHandler.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/ErrorHandler.java index 89f0b4e..0f1ccaf 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/ErrorHandler.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/ErrorHandler.java @@ -1,27 +1,27 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j.spi; - -/** - * Created by IntelliJ IDEA. - * User: ceki - * Date: 19 oct. 2010 - * Time: 11:46:24 - * To change this template use File | Settings | File Templates. - */ -public class ErrorHandler { -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.spi; + +/** + * Created by IntelliJ IDEA. + * User: ceki + * Date: 19 oct. 2010 + * Time: 11:46:24 + * To change this template use File | Settings | File Templates. + */ +public class ErrorHandler { +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/Filter.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/Filter.java index e9b3f05..7e15506 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/Filter.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/Filter.java @@ -1,20 +1,20 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j.spi; - -public class Filter { -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.spi; + +public class Filter { +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/HierarchyEventListener.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/HierarchyEventListener.java index 05d934d..9271b70 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/HierarchyEventListener.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/HierarchyEventListener.java @@ -1,38 +1,38 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j.spi; - -import org.apache.log4j.*; - -/** - Listen to events occurring within a {@link - org.apache.log4j.Hierarchy Hierarchy}. - - @author Ceki Gülcü - @since 1.2 - - */ -public interface HierarchyEventListener { - - // public - // void categoryCreationEvent(Category cat); - - public void addAppenderEvent(Category cat, Appender appender); - - public void removeAppenderEvent(Category cat, Appender appender); - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.spi; + +import org.apache.log4j.*; + +/** + Listen to events occurring within a {@link + org.apache.log4j.Hierarchy Hierarchy}. + + @author Ceki Gülcü + @since 1.2 + + */ +public interface HierarchyEventListener { + + // public + // void categoryCreationEvent(Category cat); + + public void addAppenderEvent(Category cat, Appender appender); + + public void removeAppenderEvent(Category cat, Appender appender); + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggerFactory.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggerFactory.java index 3eead60..c3e756d 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggerFactory.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggerFactory.java @@ -1,36 +1,36 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j.spi; - -import org.apache.log4j.Logger; - -/** - - Implement this interface to create new instances of Logger or - a sub-class of Logger. - -

See examples/subclass/MyLogger.java for an example. - - @author Ceki Gülcü - @since version 0.8.5 - - */ -public interface LoggerFactory { - - public Logger makeNewLoggerInstance(String name); - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.spi; + +import org.apache.log4j.Logger; + +/** + + Implement this interface to create new instances of Logger or + a sub-class of Logger. + +

See examples/subclass/MyLogger.java for an example. + + @author Ceki Gülcü + @since version 0.8.5 + + */ +public interface LoggerFactory { + + public Logger makeNewLoggerInstance(String name); + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggerRepository.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggerRepository.java index 41368c4..4decdb7 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggerRepository.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggerRepository.java @@ -1,95 +1,95 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j.spi; - -import org.apache.log4j.*; - -import java.util.Enumeration; - -/** - * A LoggerRepository is used to create and retrieve - * Loggers. The relation between loggers in a repository - * depends on the repository but typically loggers are arranged in a - * named hierarchy. - *

- *

In addition to the creational methods, a - * LoggerRepository can be queried for existing loggers, - * can act as a point of registry for events related to loggers. - * - * @author Ceki Gülcü - * @since 1.2 - */ -public interface LoggerRepository { - - /** - * Add a {@link HierarchyEventListener} event to the repository. - */ - public void addHierarchyEventListener(HierarchyEventListener listener); - - /** - * Returns whether this repository is disabled for a given - * level. The answer depends on the repository threshold and the - * level parameter. See also {@link #setThreshold} - * method. - */ - boolean isDisabled(int level); - - /** - * Set the repository-wide threshold. All logging requests below the - * threshold are immediately dropped. By default, the threshold is - * set to Level.ALL which has the lowest possible rank. - */ - public void setThreshold(Level level); - - /** - * Another form of {@link #setThreshold(Level)} accepting a string - * parameter instead of a Level. - */ - public void setThreshold(String val); - - public void emitNoAppenderWarning(Category cat); - - /** - * Get the repository-wide threshold. See {@link - * #setThreshold(Level)} for an explanation. - */ - public Level getThreshold(); - - public Logger getLogger(String name); - - public Logger getLogger(String name, LoggerFactory factory); - - public Logger getRootLogger(); - - public abstract Logger exists(String name); - - public abstract void shutdown(); - - @SuppressWarnings("rawtypes") - public Enumeration getCurrentLoggers(); - - /** - * Deprecated. Please use {@link #getCurrentLoggers} instead. - */ - @SuppressWarnings("rawtypes") - public Enumeration getCurrentCategories(); - - public abstract void fireAddAppenderEvent(Category logger, Appender appender); - - public abstract void resetConfiguration(); - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.spi; + +import org.apache.log4j.*; + +import java.util.Enumeration; + +/** + * A LoggerRepository is used to create and retrieve + * Loggers. The relation between loggers in a repository + * depends on the repository but typically loggers are arranged in a + * named hierarchy. + *

+ *

In addition to the creational methods, a + * LoggerRepository can be queried for existing loggers, + * can act as a point of registry for events related to loggers. + * + * @author Ceki Gülcü + * @since 1.2 + */ +public interface LoggerRepository { + + /** + * Add a {@link HierarchyEventListener} event to the repository. + */ + public void addHierarchyEventListener(HierarchyEventListener listener); + + /** + * Returns whether this repository is disabled for a given + * level. The answer depends on the repository threshold and the + * level parameter. See also {@link #setThreshold} + * method. + */ + boolean isDisabled(int level); + + /** + * Set the repository-wide threshold. All logging requests below the + * threshold are immediately dropped. By default, the threshold is + * set to Level.ALL which has the lowest possible rank. + */ + public void setThreshold(Level level); + + /** + * Another form of {@link #setThreshold(Level)} accepting a string + * parameter instead of a Level. + */ + public void setThreshold(String val); + + public void emitNoAppenderWarning(Category cat); + + /** + * Get the repository-wide threshold. See {@link + * #setThreshold(Level)} for an explanation. + */ + public Level getThreshold(); + + public Logger getLogger(String name); + + public Logger getLogger(String name, LoggerFactory factory); + + public Logger getRootLogger(); + + public abstract Logger exists(String name); + + public abstract void shutdown(); + + @SuppressWarnings("rawtypes") + public Enumeration getCurrentLoggers(); + + /** + * Deprecated. Please use {@link #getCurrentLoggers} instead. + */ + @SuppressWarnings("rawtypes") + public Enumeration getCurrentCategories(); + + public abstract void fireAddAppenderEvent(Category logger, Appender appender); + + public abstract void resetConfiguration(); + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggingEvent.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggingEvent.java index 43e4a4c..ea78c89 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggingEvent.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/LoggingEvent.java @@ -1,20 +1,20 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j.spi; - -public class LoggingEvent { -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.spi; + +public class LoggingEvent { +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/OptionHandler.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/OptionHandler.java index b2e5305..c1e0150 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/OptionHandler.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/OptionHandler.java @@ -1,22 +1,22 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.log4j.spi; - -public interface OptionHandler { - - void activateOptions(); - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.log4j.spi; + +public interface OptionHandler { + + void activateOptions(); + +} diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/xml/DOMConfigurator.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/xml/DOMConfigurator.java index 7cb1440..c133716 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/xml/DOMConfigurator.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/xml/DOMConfigurator.java @@ -1,66 +1,66 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j.xml; - -import org.apache.log4j.spi.Configurator; -import org.apache.log4j.spi.LoggerRepository; - -import javax.xml.parsers.FactoryConfigurationError; -import java.io.InputStream; -import java.io.Reader; -import java.net.URL; -import java.util.Properties; - -import org.w3c.dom.Element; - -public class DOMConfigurator implements Configurator { - - public static void configure(Element element) { - } - - public static void configure(String filename) throws FactoryConfigurationError { - } - - static public void configure(URL url) throws FactoryConfigurationError { - } - - static public void configureAndWatch(String configFilename) { - } - - public static void configureAndWatch(String configFilename, long delay) { - } - - public void doConfigure(Element element, LoggerRepository repository) { - } - - public void doConfigure(InputStream inputStream, LoggerRepository repository) throws FactoryConfigurationError { - } - - public void doConfigure(Reader reader, LoggerRepository repository) throws FactoryConfigurationError { - } - - public void doConfigure(String filename, LoggerRepository repository) { - } - - public void doConfigure(URL url, LoggerRepository repository) { - } - - public static String subst(String value, Properties props) { - return value; - } - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j.xml; + +import org.apache.log4j.spi.Configurator; +import org.apache.log4j.spi.LoggerRepository; + +import javax.xml.parsers.FactoryConfigurationError; +import java.io.InputStream; +import java.io.Reader; +import java.net.URL; +import java.util.Properties; + +import org.w3c.dom.Element; + +public class DOMConfigurator implements Configurator { + + public static void configure(Element element) { + } + + public static void configure(String filename) throws FactoryConfigurationError { + } + + static public void configure(URL url) throws FactoryConfigurationError { + } + + static public void configureAndWatch(String configFilename) { + } + + public static void configureAndWatch(String configFilename, long delay) { + } + + public void doConfigure(Element element, LoggerRepository repository) { + } + + public void doConfigure(InputStream inputStream, LoggerRepository repository) throws FactoryConfigurationError { + } + + public void doConfigure(Reader reader, LoggerRepository repository) throws FactoryConfigurationError { + } + + public void doConfigure(String filename, LoggerRepository repository) { + } + + public void doConfigure(URL url, LoggerRepository repository) { + } + + public static String subst(String value, Properties props) { + return value; + } + +} diff --git a/log4j-over-slf4j/src/main/resources/META-INF/MANIFEST.MF b/log4j-over-slf4j/src/main/resources/META-INF/MANIFEST.MF old file mode 100644 new file mode 100755 index 3e98459..b63540a 100755 --- a/log4j-over-slf4j/src/main/resources/META-INF/MANIFEST.MF +++ b/log4j-over-slf4j/src/main/resources/META-INF/MANIFEST.MF @@ -1,13 +1,13 @@ -Implementation-Title: log4j-over-slf4j -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: log4j.over.slf4j -Bundle-Name: log4j-over-slf4j -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -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} -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} +Implementation-Title: log4j-over-slf4j +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: log4j.over.slf4j +Bundle-Name: log4j-over-slf4j +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +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} +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} diff --git a/log4j-over-slf4j/src/test/java/org/apache/log4j/NDCTest.java b/log4j-over-slf4j/src/test/java/org/apache/log4j/NDCTest.java index 82e2326..8b12fbe 100644 --- a/log4j-over-slf4j/src/test/java/org/apache/log4j/NDCTest.java +++ b/log4j-over-slf4j/src/test/java/org/apache/log4j/NDCTest.java @@ -1,69 +1,69 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.apache.log4j; - -import static org.junit.Assert.assertEquals; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * @author Ceki Gülcü - */ -public class NDCTest { - - @Before - public void setUp() { - assertEquals(0, NDC.getDepth()); - } - - @After - public void tearDown() { - NDC.clear(); - } - - @Test - public void testSmoke() { - NDC.push("a"); - String back = NDC.pop(); - assertEquals("a", back); - } - - @Test - public void testPop() { - NDC.push("peek"); - String back = NDC.peek(); - assertEquals("peek", back); - } - - @Test - public void testClear() { - NDC.push("clear"); - NDC.clear(); - assertEquals(0, NDC.getDepth()); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.apache.log4j; + +import static org.junit.Assert.assertEquals; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * @author Ceki Gülcü + */ +public class NDCTest { + + @Before + public void setUp() { + assertEquals(0, NDC.getDepth()); + } + + @After + public void tearDown() { + NDC.clear(); + } + + @Test + public void testSmoke() { + NDC.push("a"); + String back = NDC.pop(); + assertEquals("a", back); + } + + @Test + public void testPop() { + NDC.push("peek"); + String back = NDC.peek(); + assertEquals("peek", back); + } + + @Test + public void testClear() { + NDC.push("clear"); + NDC.clear(); + assertEquals(0, NDC.getDepth()); + } + +} diff --git a/log4j-over-slf4j/src/test/java/org/apache/log4j/Trivial.java b/log4j-over-slf4j/src/test/java/org/apache/log4j/Trivial.java index cb157e7..50edf2d 100644 --- a/log4j-over-slf4j/src/test/java/org/apache/log4j/Trivial.java +++ b/log4j-over-slf4j/src/test/java/org/apache/log4j/Trivial.java @@ -1,51 +1,51 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.apache.log4j; - -import org.apache.log4j.Logger; - -import junit.framework.TestCase; - -public class Trivial extends TestCase { - - public void testSmoke() { - Logger l = Logger.getLogger("a"); - l.trace("t"); - l.debug("d"); - l.info("i"); - l.warn("w"); - l.error("e"); - l.fatal("f"); - - Exception e = new Exception("testing"); - l.trace("t", e); - l.debug("d", e); - l.info("i", e); - l.warn("w", e); - l.error("e", e); - l.fatal("f", e); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.apache.log4j; + +import org.apache.log4j.Logger; + +import junit.framework.TestCase; + +public class Trivial extends TestCase { + + public void testSmoke() { + Logger l = Logger.getLogger("a"); + l.trace("t"); + l.debug("d"); + l.info("i"); + l.warn("w"); + l.error("e"); + l.fatal("f"); + + Exception e = new Exception("testing"); + l.trace("t", e); + l.debug("d", e); + l.info("i", e); + l.warn("w", e); + l.error("e", e); + l.fatal("f", e); + } + +} diff --git a/log4j-over-slf4j/src/test/java/org/dummy/Bug131.java b/log4j-over-slf4j/src/test/java/org/dummy/Bug131.java index 506f8a3..4453ac2 100644 --- a/log4j-over-slf4j/src/test/java/org/dummy/Bug131.java +++ b/log4j-over-slf4j/src/test/java/org/dummy/Bug131.java @@ -1,70 +1,70 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.dummy; - -import static org.junit.Assert.assertEquals; - -import java.util.logging.Level; -import java.util.logging.LogRecord; - -import org.apache.log4j.Category; -import org.apache.log4j.Logger; -import org.junit.Test; - -public class Bug131 { - - @Test - public void testBug131() { - - ListHandler listHandler = new ListHandler(); - java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); - root.addHandler(listHandler); - root.setLevel(Level.FINEST); - Logger log4jLogger = Logger.getLogger("a"); - Category log4jCategory = Logger.getLogger("b"); - - int n = 0; - - log4jLogger.trace("msg" + (n++)); - log4jLogger.debug("msg" + (n++)); - log4jLogger.info("msg" + (n++)); - log4jLogger.warn("msg" + (n++)); - log4jLogger.error("msg" + (n++)); - log4jLogger.fatal("msg" + (n++)); - - log4jCategory.debug("msg" + (n++)); - log4jCategory.info("msg" + (n++)); - log4jCategory.warn("msg" + (n++)); - log4jCategory.error("msg" + (n++)); - log4jCategory.fatal("msg" + (n++)); - - assertEquals(n, listHandler.list.size()); - - for (int i = 0; i < n; i++) { - LogRecord logRecord = (LogRecord) listHandler.list.get(i); - assertEquals("testBug131", logRecord.getSourceMethodName()); - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.dummy; + +import static org.junit.Assert.assertEquals; + +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import org.apache.log4j.Category; +import org.apache.log4j.Logger; +import org.junit.Test; + +public class Bug131 { + + @Test + public void testBug131() { + + ListHandler listHandler = new ListHandler(); + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); + root.addHandler(listHandler); + root.setLevel(Level.FINEST); + Logger log4jLogger = Logger.getLogger("a"); + Category log4jCategory = Logger.getLogger("b"); + + int n = 0; + + log4jLogger.trace("msg" + (n++)); + log4jLogger.debug("msg" + (n++)); + log4jLogger.info("msg" + (n++)); + log4jLogger.warn("msg" + (n++)); + log4jLogger.error("msg" + (n++)); + log4jLogger.fatal("msg" + (n++)); + + log4jCategory.debug("msg" + (n++)); + log4jCategory.info("msg" + (n++)); + log4jCategory.warn("msg" + (n++)); + log4jCategory.error("msg" + (n++)); + log4jCategory.fatal("msg" + (n++)); + + assertEquals(n, listHandler.list.size()); + + for (int i = 0; i < n; i++) { + LogRecord logRecord = (LogRecord) listHandler.list.get(i); + assertEquals("testBug131", logRecord.getSourceMethodName()); + } + } +} diff --git a/log4j-over-slf4j/src/test/java/org/dummy/Bug139.java b/log4j-over-slf4j/src/test/java/org/dummy/Bug139.java index 0b1916e..1bb280c 100644 --- a/log4j-over-slf4j/src/test/java/org/dummy/Bug139.java +++ b/log4j-over-slf4j/src/test/java/org/dummy/Bug139.java @@ -1,59 +1,59 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.dummy; - -import static org.junit.Assert.assertEquals; - -import java.util.logging.Level; -import java.util.logging.LogRecord; - -import org.apache.log4j.Category; -import org.apache.log4j.Logger; -import org.junit.Test; - -public class Bug139 { - - @Test - public void test() { - ListHandler listHandler = new ListHandler(); - java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); - root.addHandler(listHandler); - root.setLevel(Level.FINEST); - Logger log4jLogger = Logger.getLogger("a"); - Category log4jCategory = Logger.getLogger("b"); - - int n = 0; - - log4jLogger.log(org.apache.log4j.Level.DEBUG, "hello" + (++n)); - log4jCategory.log(org.apache.log4j.Level.DEBUG, "world" + (++n)); - - assertEquals(n, listHandler.list.size()); - - for (int i = 0; i < n; i++) { - LogRecord logRecord = (LogRecord) listHandler.list.get(i); - assertEquals("test", logRecord.getSourceMethodName()); - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.dummy; + +import static org.junit.Assert.assertEquals; + +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import org.apache.log4j.Category; +import org.apache.log4j.Logger; +import org.junit.Test; + +public class Bug139 { + + @Test + public void test() { + ListHandler listHandler = new ListHandler(); + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); + root.addHandler(listHandler); + root.setLevel(Level.FINEST); + Logger log4jLogger = Logger.getLogger("a"); + Category log4jCategory = Logger.getLogger("b"); + + int n = 0; + + log4jLogger.log(org.apache.log4j.Level.DEBUG, "hello" + (++n)); + log4jCategory.log(org.apache.log4j.Level.DEBUG, "world" + (++n)); + + assertEquals(n, listHandler.list.size()); + + for (int i = 0; i < n; i++) { + LogRecord logRecord = (LogRecord) listHandler.list.get(i); + assertEquals("test", logRecord.getSourceMethodName()); + } + } +} diff --git a/log4j-over-slf4j/src/test/java/org/dummy/ListHandler.java b/log4j-over-slf4j/src/test/java/org/dummy/ListHandler.java index 23fc473..c29ebfa 100644 --- a/log4j-over-slf4j/src/test/java/org/dummy/ListHandler.java +++ b/log4j-over-slf4j/src/test/java/org/dummy/ListHandler.java @@ -1,49 +1,49 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.dummy; - -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Handler; -import java.util.logging.LogRecord; - -public class ListHandler extends Handler { - - List list = new ArrayList(); - - public void close() throws SecurityException { - - } - - public void flush() { - - } - - public void publish(LogRecord logRecord) { - logRecord.getSourceClassName(); - list.add(logRecord); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.dummy; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; + +public class ListHandler extends Handler { + + List list = new ArrayList(); + + public void close() throws SecurityException { + + } + + public void flush() { + + } + + public void publish(LogRecord logRecord) { + logRecord.getSourceClassName(); + list.add(logRecord); + } + +} diff --git a/osgi-over-slf4j/pom.xml b/osgi-over-slf4j/pom.xml old file mode 100644 new file mode 100755 index 2b0d80a..967c369 100755 --- a/osgi-over-slf4j/pom.xml +++ b/osgi-over-slf4j/pom.xml @@ -1,44 +1,46 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - osgi-over-slf4j - - jar - OSGi LogService implemented over SLF4J - - http://www.slf4j.org - - OSGi LogService implementation over SLF4J - - - - - org.osgi - org.osgi.core - 4.2.0 - provided - - - org.osgi - org.osgi.enterprise - 4.2.0 - provided - - - - org.slf4j - slf4j-simple - ${project.version} - provided - - - + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + osgi-over-slf4j + + jar + OSGi LogService implemented over SLF4J + + http://www.slf4j.org + + OSGi LogService implementation over SLF4J + + + + + org.osgi + org.osgi.core + 4.2.0 + provided + + + org.osgi + org.osgi.enterprise + 4.2.0 + provided + + + + org.slf4j + slf4j-simple + ${project.version} + provided + + + + + diff --git a/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/Activator.java b/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/Activator.java index baa6695..8ac9039 100644 --- a/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/Activator.java +++ b/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/Activator.java @@ -1,78 +1,78 @@ -/* - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.osgi.logservice.impl; - -import java.util.Properties; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceFactory; -import org.osgi.service.log.LogService; - -/** - * Activator implements a simple bundle that registers a - * {@link LogServiceFactory} for the creation of {@link LogService} implementations. - * - * @author John Conlon - * @author Matt Bishop - **/ -public class Activator implements BundleActivator { - /** - * - * Implements BundleActivator.start() to register a - * LogServiceFactory. - * - * @param bundleContext the framework context for the bundle - * @throws Exception - */ - public void start(BundleContext bundleContext) throws Exception { - - Properties props = new Properties(); - props.put("description", "An SLF4J LogService implementation."); - ServiceFactory factory = new LogServiceFactory(); - bundleContext.registerService(LogService.class.getName(), factory, props); - } - - /** - * - * Implements BundleActivator.stop(). - * - * @param bundleContext the framework context for the bundle - * @throws Exception - */ - public void stop(BundleContext bundleContext) throws Exception { - - // Note: It is not required that we remove the service here, since - // the framework will do it automatically. - } -} +/* + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.osgi.logservice.impl; + +import java.util.Properties; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceFactory; +import org.osgi.service.log.LogService; + +/** + * Activator implements a simple bundle that registers a + * {@link LogServiceFactory} for the creation of {@link LogService} implementations. + * + * @author John Conlon + * @author Matt Bishop + **/ +public class Activator implements BundleActivator { + /** + * + * Implements BundleActivator.start() to register a + * LogServiceFactory. + * + * @param bundleContext the framework context for the bundle + * @throws Exception + */ + public void start(BundleContext bundleContext) throws Exception { + + Properties props = new Properties(); + props.put("description", "An SLF4J LogService implementation."); + ServiceFactory factory = new LogServiceFactory(); + bundleContext.registerService(LogService.class.getName(), factory, props); + } + + /** + * + * Implements BundleActivator.stop(). + * + * @param bundleContext the framework context for the bundle + * @throws Exception + */ + public void stop(BundleContext bundleContext) throws Exception { + + // Note: It is not required that we remove the service here, since + // the framework will do it automatically. + } +} diff --git a/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/LogServiceFactory.java b/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/LogServiceFactory.java index e52d10d..c626a2c 100644 --- a/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/LogServiceFactory.java +++ b/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/LogServiceFactory.java @@ -1,65 +1,65 @@ -/* - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.osgi.logservice.impl; - -import org.osgi.framework.Bundle; -import org.osgi.framework.ServiceFactory; -import org.osgi.framework.ServiceRegistration; - -/** - * LogServiceFactory creates LogService implementations. - * - * @author John Conlon - * @version $Rev$, $Date$ - */ -public class LogServiceFactory implements ServiceFactory { - /* - * (non-Javadoc) - * - * @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle, - * org.osgi.framework.ServiceRegistration) - */ - public Object getService(Bundle bundle, ServiceRegistration arg1) { - return new LogServiceImpl(bundle); - } - - /* - * (non-Javadoc) - * - * @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle, - * org.osgi.framework.ServiceRegistration, java.lang.Object) - */ - public void ungetService(Bundle bundle, ServiceRegistration arg1, Object arg2) { - // nothing to do. - } -} +/* + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.osgi.logservice.impl; + +import org.osgi.framework.Bundle; +import org.osgi.framework.ServiceFactory; +import org.osgi.framework.ServiceRegistration; + +/** + * LogServiceFactory creates LogService implementations. + * + * @author John Conlon + * @version $Rev$, $Date$ + */ +public class LogServiceFactory implements ServiceFactory { + /* + * (non-Javadoc) + * + * @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle, + * org.osgi.framework.ServiceRegistration) + */ + public Object getService(Bundle bundle, ServiceRegistration arg1) { + return new LogServiceImpl(bundle); + } + + /* + * (non-Javadoc) + * + * @see org.osgi.framework.ServiceFactory#ungetService(org.osgi.framework.Bundle, + * org.osgi.framework.ServiceRegistration, java.lang.Object) + */ + public void ungetService(Bundle bundle, ServiceRegistration arg1, Object arg2) { + // nothing to do. + } +} diff --git a/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/LogServiceImpl.java b/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/LogServiceImpl.java index 68e3379..c020c4e 100644 --- a/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/LogServiceImpl.java +++ b/osgi-over-slf4j/src/main/java/org/slf4j/osgi/logservice/impl/LogServiceImpl.java @@ -1,206 +1,206 @@ -/* - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.osgi.logservice.impl; - -import org.osgi.framework.Bundle; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.Version; -import org.osgi.service.log.LogService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * LogServiceImpl is a simple OSGi LogService implementation that delegates to a slf4j - * Logger. - * - * @author John Conlon - * @author Matt Bishop - */ -public class LogServiceImpl implements LogService { - - private static final String UNKNOWN = "[Unknown]"; - - private final Logger delegate; - - /** - * Creates a new instance of LogServiceImpl. - * - * @param bundle The bundle to create a new LogService for. - */ - public LogServiceImpl(Bundle bundle) { - - String name = bundle.getSymbolicName(); - Version version = bundle.getVersion(); - if (version == null) { - version = Version.emptyVersion; - } - delegate = LoggerFactory.getLogger(name + '.' + version); - } - - /* - * (non-Javadoc) - * - * @see org.osgi.service.log.LogService#log(int, java.lang.String) - */ - public void log(int level, String message) { - - switch (level) { - case LOG_DEBUG: - delegate.debug(message); - break; - case LOG_ERROR: - delegate.error(message); - break; - case LOG_INFO: - delegate.info(message); - break; - case LOG_WARNING: - delegate.warn(message); - break; - default: - break; - } - } - - /* - * (non-Javadoc) - * - * @see org.osgi.service.log.LogService#log(int, java.lang.String, java.lang.Throwable) - */ - public void log(int level, String message, Throwable exception) { - - switch (level) { - case LOG_DEBUG: - delegate.debug(message, exception); - break; - case LOG_ERROR: - delegate.error(message, exception); - break; - case LOG_INFO: - delegate.info(message, exception); - break; - case LOG_WARNING: - delegate.warn(message, exception); - break; - default: - break; - } - } - - /* - * (non-Javadoc) - * - * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String) - */ - public void log(ServiceReference sr, int level, String message) { - - switch (level) { - case LOG_DEBUG: - if (delegate.isDebugEnabled()) { - delegate.debug(createMessage(sr, message)); - } - break; - case LOG_ERROR: - if (delegate.isErrorEnabled()) { - delegate.error(createMessage(sr, message)); - } - break; - case LOG_INFO: - if (delegate.isInfoEnabled()) { - delegate.info(createMessage(sr, message)); - } - break; - case LOG_WARNING: - if (delegate.isWarnEnabled()) { - delegate.warn(createMessage(sr, message)); - } - break; - default: - break; - } - } - - /** - * Formats the log message to indicate the service sending it, if known. - * - * @param sr the ServiceReference sending the message. - * @param message The message to log. - * @return The formatted log message. - */ - private String createMessage(ServiceReference sr, String message) { - - StringBuilder output = new StringBuilder(); - if (sr != null) { - output.append('[').append(sr.toString()).append(']'); - } else { - output.append(UNKNOWN); - } - output.append(message); - - return output.toString(); - } - - /* - * (non-Javadoc) - * - * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String, - * java.lang.Throwable) - */ - public void log(ServiceReference sr, int level, String message, Throwable exception) { - - switch (level) { - case LOG_DEBUG: - if (delegate.isDebugEnabled()) { - delegate.debug(createMessage(sr, message), exception); - } - break; - case LOG_ERROR: - if (delegate.isErrorEnabled()) { - delegate.error(createMessage(sr, message), exception); - } - break; - case LOG_INFO: - if (delegate.isInfoEnabled()) { - delegate.info(createMessage(sr, message), exception); - } - break; - case LOG_WARNING: - if (delegate.isWarnEnabled()) { - delegate.warn(createMessage(sr, message), exception); - } - break; - default: - break; - } - } -} +/* + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.osgi.logservice.impl; + +import org.osgi.framework.Bundle; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.Version; +import org.osgi.service.log.LogService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * LogServiceImpl is a simple OSGi LogService implementation that delegates to a slf4j + * Logger. + * + * @author John Conlon + * @author Matt Bishop + */ +public class LogServiceImpl implements LogService { + + private static final String UNKNOWN = "[Unknown]"; + + private final Logger delegate; + + /** + * Creates a new instance of LogServiceImpl. + * + * @param bundle The bundle to create a new LogService for. + */ + public LogServiceImpl(Bundle bundle) { + + String name = bundle.getSymbolicName(); + Version version = bundle.getVersion(); + if (version == null) { + version = Version.emptyVersion; + } + delegate = LoggerFactory.getLogger(name + '.' + version); + } + + /* + * (non-Javadoc) + * + * @see org.osgi.service.log.LogService#log(int, java.lang.String) + */ + public void log(int level, String message) { + + switch (level) { + case LOG_DEBUG: + delegate.debug(message); + break; + case LOG_ERROR: + delegate.error(message); + break; + case LOG_INFO: + delegate.info(message); + break; + case LOG_WARNING: + delegate.warn(message); + break; + default: + break; + } + } + + /* + * (non-Javadoc) + * + * @see org.osgi.service.log.LogService#log(int, java.lang.String, java.lang.Throwable) + */ + public void log(int level, String message, Throwable exception) { + + switch (level) { + case LOG_DEBUG: + delegate.debug(message, exception); + break; + case LOG_ERROR: + delegate.error(message, exception); + break; + case LOG_INFO: + delegate.info(message, exception); + break; + case LOG_WARNING: + delegate.warn(message, exception); + break; + default: + break; + } + } + + /* + * (non-Javadoc) + * + * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String) + */ + public void log(ServiceReference sr, int level, String message) { + + switch (level) { + case LOG_DEBUG: + if (delegate.isDebugEnabled()) { + delegate.debug(createMessage(sr, message)); + } + break; + case LOG_ERROR: + if (delegate.isErrorEnabled()) { + delegate.error(createMessage(sr, message)); + } + break; + case LOG_INFO: + if (delegate.isInfoEnabled()) { + delegate.info(createMessage(sr, message)); + } + break; + case LOG_WARNING: + if (delegate.isWarnEnabled()) { + delegate.warn(createMessage(sr, message)); + } + break; + default: + break; + } + } + + /** + * Formats the log message to indicate the service sending it, if known. + * + * @param sr the ServiceReference sending the message. + * @param message The message to log. + * @return The formatted log message. + */ + private String createMessage(ServiceReference sr, String message) { + + StringBuilder output = new StringBuilder(); + if (sr != null) { + output.append('[').append(sr.toString()).append(']'); + } else { + output.append(UNKNOWN); + } + output.append(message); + + return output.toString(); + } + + /* + * (non-Javadoc) + * + * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String, + * java.lang.Throwable) + */ + public void log(ServiceReference sr, int level, String message, Throwable exception) { + + switch (level) { + case LOG_DEBUG: + if (delegate.isDebugEnabled()) { + delegate.debug(createMessage(sr, message), exception); + } + break; + case LOG_ERROR: + if (delegate.isErrorEnabled()) { + delegate.error(createMessage(sr, message), exception); + } + break; + case LOG_INFO: + if (delegate.isInfoEnabled()) { + delegate.info(createMessage(sr, message), exception); + } + break; + case LOG_WARNING: + if (delegate.isWarnEnabled()) { + delegate.warn(createMessage(sr, message), exception); + } + break; + default: + break; + } + } +} diff --git a/osgi-over-slf4j/src/main/resources/META-INF/MANIFEST.MF b/osgi-over-slf4j/src/main/resources/META-INF/MANIFEST.MF index 97b13da..73cebcf 100644 --- a/osgi-over-slf4j/src/main/resources/META-INF/MANIFEST.MF +++ b/osgi-over-slf4j/src/main/resources/META-INF/MANIFEST.MF @@ -1,8 +1,8 @@ -Implementation-Title: osgi-over-slf4j -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: org.slf4j.osgi-over-slf4j -Bundle-Name: OSGi LogService implemented over SLF4J -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Bundle-Activator: org.slf4j.osgi.logservice.impl.Activator -Bundle-Category: osgi -Import-Package: org.osgi.framework;version="[1.5,2)",org.osgi.service.log;version="[1.3,2)",org.slf4j;version=${parsedVersion.osgiVersion} +Implementation-Title: osgi-over-slf4j +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: org.slf4j.osgi-over-slf4j +Bundle-Name: OSGi LogService implemented over SLF4J +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Bundle-Activator: org.slf4j.osgi.logservice.impl.Activator +Bundle-Category: osgi +Import-Package: org.osgi.framework;version="[1.5,2)",org.osgi.service.log;version="[1.3,2)",org.slf4j;version=${parsedVersion.osgiVersion} diff --git a/pom.xml b/pom.xml old file mode 100644 new file mode 100755 index 0df1e97..e39dafe 100755 --- a/pom.xml +++ b/pom.xml @@ -1,424 +1,427 @@ - - - - 4.0.0 - - org.slf4j - slf4j-parent - 1.7.25 - - pom - SLF4J - Top SLF4J project pom.xml file - http://www.slf4j.org - - - QOS.ch - http://www.qos.ch - - 2005 - - - - MIT License - http://www.opensource.org/licenses/mit-license.php - repo - - - - - https://github.com/qos-ch/slf4j - git@github.com:qos-ch/slf4j.git - - - - 1.5 - ${required.jdk.version} - ${required.jdk.version} - UTF-8 - UTF-8 - UTF-8 - - 1.6.0 - 0.8.1 - 1.2.17 - 1.0.13 - 4.12 - 3.3 - 2.10.4 - - - - - ceki - Ceki Gulcu - ceki@qos.ch - - - - - slf4j-api - slf4j-simple - slf4j-nop - slf4j-jdk14 - slf4j-log4j12 - slf4j-jcl - slf4j-android - slf4j-ext - jcl-over-slf4j - log4j-over-slf4j - jul-to-slf4j - osgi-over-slf4j - integration - slf4j-site - slf4j-migrator - - - - - junit - junit - ${junit.version} - test - - - - - - - - org.slf4j - slf4j-api - ${project.version} - - - - org.slf4j - slf4j-jdk14 - ${project.version} - - - - log4j - log4j - ${log4j.version} - - - - ch.qos.cal10n - cal10n-api - ${cal10n.version} - - - - - - - - - org.apache.maven.wagon - wagon-ssh - 2.0 - - - - - - ${project.basedir}/src/main/resources - true - - - - - - - org.codehaus.mojo - animal-sniffer-maven-plugin - 1.14 - - - org.codehaus.mojo.signature - java15 - 1.0 - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.3 - - ${required.jdk.version} - ${required.jdk.version} - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.3.1 - - - - ${parsedVersion.osgiVersion} - ${project.description} - ${maven.compiler.source} - ${maven.compiler.target} - ${project.version} - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - true - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.19.1 - - 2C - true - plain - false - - **/AllTest.java - **/PackageTest.java - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - package - - jar - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.2 - - - src/main/assembly/source.xml - - slf4j-${project.version} - false - target/site/dist/ - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 1.7 - - - parse-version - - parse-version - - - - - - - - org.apache.maven.plugins - maven-site-plugin - ${maven-site-plugin.version} - - - - - org.apache.maven.plugins - maven-jxr-plugin - 2.3 - - true - target/site/apidocs/ - true - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${javadoc.plugin.version} - - true - - org.slf4j.migrator:org.slf4j.migrator.* - - - http://java.sun.com/j2se/1.5.0/docs/api - - - - - SLF4J packages - org.slf4j:org.slf4j.* - - - - SLF4J extensions - - org.slf4j.cal10n:org.slf4j.profiler:org.slf4j.ext:org.slf4j.instrumentation:org.slf4j.agent - - - - - Jakarta Commons Logging packages - org.apache.commons.* - - - - java.util.logging (JUL) to SLF4J bridge - org.slf4j.bridge - - - - Apache log4j - org.apache.log4j:org.apache.log4j.* - - - - - - - - - - - - - - - skipTests - - true - - - - - javadocjar - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${javadoc.plugin.version} - - - attach-javadocs - - jar - - - - - - - - - - license - - - - com.google.code.maven-license-plugin - maven-license-plugin - -

src/main/licenseHeader.txt
- false - true - true - - src/**/*.java - - true - true - - 1999 - - - src/main/javadocHeaders.xml - - - - - - - - - mc-release - Local Maven repository of releases - http://mc-repo.googlecode.com/svn/maven2/releases - - false - - - true - - - - - - - sign-artifacts - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.1 - - - sign-artifacts - verify - - sign - - - - - - - - - - - - - - - - qos_ch - scp://te.qos.ch/var/www/www.slf4j.org/htdocs/ - - - - - - sonatype-nexus-staging - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - + + + + 4.0.0 + + org.slf4j + slf4j-parent + 1.7.26 + + pom + SLF4J + Top SLF4J project pom.xml file + http://www.slf4j.org + + + QOS.ch + http://www.qos.ch + + 2005 + + + + MIT License + http://www.opensource.org/licenses/mit-license.php + repo + + + + + https://github.com/qos-ch/slf4j + git@github.com:qos-ch/slf4j.git + + + + 1.5 + ${required.jdk.version} + ${required.jdk.version} + UTF-8 + UTF-8 + UTF-8 + + 1.6.0 + 0.8.1 + 1.2.17 + 1.0.13 + 4.12 + 3.3 + 3.0.1 + 2.10.4 + + + + + ceki + Ceki Gulcu + ceki@qos.ch + + + + + slf4j-api + slf4j-simple + slf4j-nop + slf4j-jdk14 + slf4j-log4j12 + slf4j-jcl + slf4j-android + slf4j-ext + jcl-over-slf4j + log4j-over-slf4j + jul-to-slf4j + osgi-over-slf4j + integration + slf4j-site + slf4j-migrator + + + + + junit + junit + ${junit.version} + test + + + + + + + + org.slf4j + slf4j-api + ${project.version} + + + + org.slf4j + slf4j-jdk14 + ${project.version} + + + + log4j + log4j + ${log4j.version} + + + + ch.qos.cal10n + cal10n-api + ${cal10n.version} + + + + + + + + + org.apache.maven.wagon + wagon-ssh + 2.0 + + + + + + ${project.basedir}/src/main/resources + true + + + + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + 1.14 + + + org.codehaus.mojo.signature + java15 + 1.0 + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + ${required.jdk.version} + ${required.jdk.version} + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.3.1 + + + + ${parsedVersion.osgiVersion} + ${project.description} + ${maven.compiler.source} + ${maven.compiler.target} + ${project.version} + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + true + + + + + org.apache.maven.plugins + maven-source-plugin + ${maven-source-plugin.version} + + + package + + jar + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + 2C + true + plain + false + + **/AllTest.java + **/PackageTest.java + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.2 + + + src/main/assembly/source.xml + + slf4j-${project.version} + false + target/site/dist/ + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.7 + + + parse-version + + parse-version + + + + + + + + org.apache.maven.plugins + maven-site-plugin + ${maven-site-plugin.version} + + + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + + true + target/site/apidocs/ + true + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${javadoc.plugin.version} + + true + none + + + org.slf4j.migrator:org.slf4j.migrator.* + + + http://java.sun.com/j2se/1.5.0/docs/api + + + + + SLF4J packages + org.slf4j:org.slf4j.* + + + + SLF4J extensions + + org.slf4j.cal10n:org.slf4j.profiler:org.slf4j.ext:org.slf4j.instrumentation:org.slf4j.agent + + + + + Jakarta Commons Logging packages + org.apache.commons.* + + + + java.util.logging (JUL) to SLF4J bridge + org.slf4j.bridge + + + + Apache log4j + org.apache.log4j:org.apache.log4j.* + + + + + + + + + + + + + + + skipTests + + true + + + + + javadocjar + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${javadoc.plugin.version} + + + attach-javadocs + + jar + + + + + + + + + + license + + + + com.google.code.maven-license-plugin + maven-license-plugin + +
src/main/licenseHeader.txt
+ false + true + true + + src/**/*.java + + true + true + + 1999 + + + src/main/javadocHeaders.xml + +
+
+
+
+ + + + mc-release + Local Maven repository of releases + http://mc-repo.googlecode.com/svn/maven2/releases + + false + + + true + + + +
+ + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.1 + + + sign-artifacts + verify + + sign + + + + + + + + +
+ + + + + + + qos_ch + scp://te.qos.ch/var/www/www.slf4j.org/htdocs/ + + + + + + sonatype-nexus-staging + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + +
diff --git a/release.sh b/release.sh new file mode 100755 index 0000000..4934ebd --- /dev/null +++ b/release.sh @@ -0,0 +1,49 @@ +#mvn versions:set -DgenerateBackupPoms=false -DnewVersion=${VERSION_NUMBER} + +MVN='/java/maven-3.5.2//bin/mvn' + +PASS=$1 +echo $PASS + +function checkExit(){ + if test "$?" != "0"; then + echo Command $1 exited with abnormal status + exit 1; + else echo $? + fi +} + +function echoThenRun () { # echo and then run the command + echo $1 + $1 + ret=$? + echo $ret + return $ret +} + +$MVN clean +checkExit "mvn clean" + + +$MVN install +checkExit "mvn install" + + +$MVN site:site +checkExit "mvn site:ste" + + +$MVN assembly:single +checkExit "mvn assembly:single" + + +$MVN deploy -P javadocjar,sign-artifacts -Dgpg.passphrase=$PASS +checkExit "mvn deploy -P javadocjar,sign-artifacts -Dgpg.passphrase=xxx" + +#$MVN site:deploy -N # with Java 8!!! +#checkExit "mvn site:deploy -N" + +#git tag -m "tagging" -a v_${VERSION_NUMBER} +#git push --tags + +#release version and add next version on jira diff --git a/slf4j-android/.gitignore b/slf4j-android/.gitignore new file mode 100755 index 0000000..7792e06 --- /dev/null +++ b/slf4j-android/.gitignore @@ -0,0 +1,2 @@ +bin/ +gen/ diff --git a/slf4j-android/AndroidManifest.xml b/slf4j-android/AndroidManifest.xml new file mode 100755 index 0000000..a2b9e40 --- /dev/null +++ b/slf4j-android/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/slf4j-android/LICENSE.txt b/slf4j-android/LICENSE.txt new file mode 100644 index 0000000..361d2ce --- /dev/null +++ b/slf4j-android/LICENSE.txt @@ -0,0 +1,24 @@ +Copyright (c) 2004-2013 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-android/pom.xml b/slf4j-android/pom.xml index a0bd3cb..bd3d651 100644 --- a/slf4j-android/pom.xml +++ b/slf4j-android/pom.xml @@ -1,34 +1,34 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - slf4j-android - jar - SLF4J Android Binding - SLF4J Android Binding - http://www.slf4j.org - - - - org.slf4j - slf4j-api - ${project.version} - - - - com.google.android - android - 1.5_r4 - provided - - - + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + slf4j-android + jar + SLF4J Android Binding + SLF4J Android Binding + http://www.slf4j.org + + + + org.slf4j + slf4j-api + ${project.version} + + + + com.google.android + android + 1.5_r4 + provided + + + diff --git a/slf4j-android/project.properties b/slf4j-android/project.properties new file mode 100755 index 0000000..0d4e760 --- /dev/null +++ b/slf4j-android/project.properties @@ -0,0 +1,14 @@ +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must be checked in Version Control Systems. +# +# To customize properties used by the Ant build system use, +# "ant.properties", and override values to adapt the script to your +# project structure. + +android.library=true +# Indicates whether an apk should be generated for each density. +split.density=false +# Project target. +target=android-3 diff --git a/slf4j-android/src/main/java/org/slf4j/impl/AndroidLoggerAdapter.java b/slf4j-android/src/main/java/org/slf4j/impl/AndroidLoggerAdapter.java old file mode 100644 new file mode 100755 index 8221324..ed47f1f 100755 --- a/slf4j-android/src/main/java/org/slf4j/impl/AndroidLoggerAdapter.java +++ b/slf4j-android/src/main/java/org/slf4j/impl/AndroidLoggerAdapter.java @@ -1,552 +1,552 @@ -/* - * Copyright (c) 2004-2013 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import android.util.Log; -import org.slf4j.helpers.FormattingTuple; -import org.slf4j.helpers.MarkerIgnoringBase; -import org.slf4j.helpers.MessageFormatter; - -/** - *

A simple implementation that delegates all log requests to the Google Android - * logging facilities. Note that this logger does not support {@link org.slf4j.Marker}. - * Methods taking marker data as parameter simply invoke the eponymous method - * without the Marker argument, discarding any marker data in the process.

- * - *

The logging levels specified for SLF4J can be almost directly mapped to - * the levels that exist in the Google Android platform. The following table - * shows the mapping implemented by this logger.

- * - * - * - * - * - * - * - * - *
SLF4JAndroid
TRACE{@link android.util.Log#VERBOSE}
DEBUG{@link android.util.Log#DEBUG}
INFO{@link android.util.Log#INFO}
WARN{@link android.util.Log#WARN}
ERROR{@link android.util.Log#ERROR}
- * - *

Use loggers as usual: - *

    - *
  • - * Declare a logger
    - * private static final Logger logger = LoggerFactory.getLogger(MyClass.class); - *
  • - *
  • - * Invoke logging methods, e.g.,
    - * logger.debug("Some log message. Details: {}", someObject);
    - * logger.debug("Some log message with varargs. Details: {}, {}, {}", someObject1, someObject2, someObject3); - *
  • - *
- *

- * - *

Logger instances created using the LoggerFactory are named either according to the name - * or the fully qualified class name of the class given as a parameter. - * Each logger name will be used as the log message tag on the Android platform. - * However, tag names cannot be longer than 23 characters so if logger name exceeds this limit then - * it will be truncated by the LoggerFactory. The following examples illustrate this. - * - * - * - * - * - * - *
Original NameTruncated Name
org.example.myproject.mypackage.MyClasso*.e*.m*.m*.MyClass
o.e.myproject.mypackage.MyClasso.e.m*.m*.MyClass
org.example.ThisNameIsWayTooLongAndWillBeTruncated*LongAndWillBeTruncated
ThisNameIsWayTooLongAndWillBeTruncated*LongAndWillBeTruncated
- *

- * - * @author Andrey Korzhevskiy - */ -class AndroidLoggerAdapter extends MarkerIgnoringBase { - private static final long serialVersionUID = -1227274521521287937L; - - /** - * Package access allows only {@link AndroidLoggerFactory} to instantiate - * SimpleLogger instances. - */ - AndroidLoggerAdapter(String tag) { - this.name = tag; - } - - /** - * Is this logger instance enabled for the VERBOSE level? - * - * @return True if this Logger is enabled for level VERBOSE, false otherwise. - */ - public boolean isTraceEnabled() { - return isLoggable(Log.VERBOSE); - } - - /** - * Log a message object at level VERBOSE. - * - * @param msg - * - the message object to be logged - */ - public void trace(String msg) { - log(Log.VERBOSE, msg, null); - } - - /** - * Log a message at level VERBOSE according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for level VERBOSE. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void trace(String format, Object arg) { - formatAndLog(Log.VERBOSE, format, arg); - } - - /** - * Log a message at level VERBOSE according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the VERBOSE level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void trace(String format, Object arg1, Object arg2) { - formatAndLog(Log.VERBOSE, format, arg1, arg2); - } - - /** - * Log a message at level VERBOSE according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the VERBOSE level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void trace(String format, Object... argArray) { - formatAndLog(Log.VERBOSE, format, argArray); - } - - /** - * Log an exception (throwable) at level VERBOSE with an accompanying message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void trace(String msg, Throwable t) { - log(Log.VERBOSE, msg, t); - } - - /** - * Is this logger instance enabled for the DEBUG level? - * - * @return True if this Logger is enabled for level DEBUG, false otherwise. - */ - public boolean isDebugEnabled() { - return isLoggable(Log.DEBUG); - } - - /** - * Log a message object at level DEBUG. - * - * @param msg - * - the message object to be logged - */ - public void debug(String msg) { - log(Log.DEBUG, msg, null); - } - - /** - * Log a message at level DEBUG according to the specified format and argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for level DEBUG. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void debug(String format, Object arg) { - formatAndLog(Log.DEBUG, format, arg); - } - - /** - * Log a message at level DEBUG according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the DEBUG level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void debug(String format, Object arg1, Object arg2) { - formatAndLog(Log.DEBUG, format, arg1, arg2); - } - - /** - * Log a message at level DEBUG according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the DEBUG level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void debug(String format, Object... argArray) { - formatAndLog(Log.DEBUG, format, argArray); - } - - /** - * Log an exception (throwable) at level DEBUG with an accompanying message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void debug(String msg, Throwable t) { - log(Log.VERBOSE, msg, t); - } - - /** - * Is this logger instance enabled for the INFO level? - * - * @return True if this Logger is enabled for the INFO level, false otherwise. - */ - public boolean isInfoEnabled() { - return isLoggable(Log.INFO); - } - - /** - * Log a message object at the INFO level. - * - * @param msg - * - the message object to be logged - */ - public void info(String msg) { - log(Log.INFO, msg, null); - } - - /** - * Log a message at level INFO according to the specified format and argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void info(String format, Object arg) { - formatAndLog(Log.INFO, format, arg); - } - - /** - * Log a message at the INFO level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void info(String format, Object arg1, Object arg2) { - formatAndLog(Log.INFO, format, arg1, arg2); - } - - /** - * Log a message at level INFO according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void info(String format, Object... argArray) { - formatAndLog(Log.INFO, format, argArray); - } - - /** - * Log an exception (throwable) at the INFO level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void info(String msg, Throwable t) { - log(Log.INFO, msg, t); - } - - /** - * Is this logger instance enabled for the WARN level? - * - * @return True if this Logger is enabled for the WARN level, false - * otherwise. - */ - public boolean isWarnEnabled() { - return isLoggable(Log.WARN); - } - - /** - * Log a message object at the WARN level. - * - * @param msg - * - the message object to be logged - */ - public void warn(String msg) { - log(Log.WARN, msg, null); - } - - /** - * Log a message at the WARN level according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARN level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void warn(String format, Object arg) { - formatAndLog(Log.WARN, format, arg); - } - - /** - * Log a message at the WARN level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARN level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void warn(String format, Object arg1, Object arg2) { - formatAndLog(Log.WARN, format, arg1, arg2); - } - - /** - * Log a message at level WARN according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARN level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void warn(String format, Object... argArray) { - formatAndLog(Log.WARN, format, argArray); - } - - /** - * Log an exception (throwable) at the WARN level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void warn(String msg, Throwable t) { - log(Log.WARN, msg, t); - } - - /** - * Is this logger instance enabled for level ERROR? - * - * @return True if this Logger is enabled for level ERROR, false otherwise. - */ - public boolean isErrorEnabled() { - return isLoggable(Log.ERROR); - } - - /** - * Log a message object at the ERROR level. - * - * @param msg - * - the message object to be logged - */ - public void error(String msg) { - log(Log.ERROR, msg, null); - } - - /** - * Log a message at the ERROR level according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the ERROR level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void error(String format, Object arg) { - formatAndLog(Log.ERROR, format, arg); - } - - /** - * Log a message at the ERROR level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the ERROR level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void error(String format, Object arg1, Object arg2) { - formatAndLog(Log.ERROR, format, arg1, arg2); - } - - /** - * Log a message at level ERROR according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the ERROR level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void error(String format, Object... argArray) { - formatAndLog(Log.ERROR, format, argArray); - } - - /** - * Log an exception (throwable) at the ERROR level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void error(String msg, Throwable t) { - log(Log.ERROR, msg, t); - } - - private void formatAndLog(int priority, String format, Object... argArray) { - if (isLoggable(priority)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - logInternal(priority, ft.getMessage(), ft.getThrowable()); - } - } - - private void log(int priority, String message, Throwable throwable) { - if (isLoggable(priority)) { - logInternal(priority, message, throwable); - } - } - - private boolean isLoggable(int priority) { - return Log.isLoggable(name, priority); - } - - private void logInternal(int priority, String message, Throwable throwable) { - if (throwable != null) { - message += '\n' + Log.getStackTraceString(throwable); - } - Log.println(priority, name, message); - } +/* + * Copyright (c) 2004-2013 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import android.util.Log; +import org.slf4j.helpers.FormattingTuple; +import org.slf4j.helpers.MarkerIgnoringBase; +import org.slf4j.helpers.MessageFormatter; + +/** + *

A simple implementation that delegates all log requests to the Google Android + * logging facilities. Note that this logger does not support {@link org.slf4j.Marker}. + * Methods taking marker data as parameter simply invoke the eponymous method + * without the Marker argument, discarding any marker data in the process.

+ * + *

The logging levels specified for SLF4J can be almost directly mapped to + * the levels that exist in the Google Android platform. The following table + * shows the mapping implemented by this logger.

+ * + * + * + * + * + * + * + * + *
SLF4JAndroid
TRACE{@link android.util.Log#VERBOSE}
DEBUG{@link android.util.Log#DEBUG}
INFO{@link android.util.Log#INFO}
WARN{@link android.util.Log#WARN}
ERROR{@link android.util.Log#ERROR}
+ * + *

Use loggers as usual: + *

    + *
  • + * Declare a logger
    + * private static final Logger logger = LoggerFactory.getLogger(MyClass.class); + *
  • + *
  • + * Invoke logging methods, e.g.,
    + * logger.debug("Some log message. Details: {}", someObject);
    + * logger.debug("Some log message with varargs. Details: {}, {}, {}", someObject1, someObject2, someObject3); + *
  • + *
+ *

+ * + *

Logger instances created using the LoggerFactory are named either according to the name + * or the fully qualified class name of the class given as a parameter. + * Each logger name will be used as the log message tag on the Android platform. + * However, tag names cannot be longer than 23 characters so if logger name exceeds this limit then + * it will be truncated by the LoggerFactory. The following examples illustrate this. + * + * + * + * + * + * + *
Original NameTruncated Name
org.example.myproject.mypackage.MyClasso*.e*.m*.m*.MyClass
o.e.myproject.mypackage.MyClasso.e.m*.m*.MyClass
org.example.ThisNameIsWayTooLongAndWillBeTruncated*LongAndWillBeTruncated
ThisNameIsWayTooLongAndWillBeTruncated*LongAndWillBeTruncated
+ *

+ * + * @author Andrey Korzhevskiy + */ +class AndroidLoggerAdapter extends MarkerIgnoringBase { + private static final long serialVersionUID = -1227274521521287937L; + + /** + * Package access allows only {@link AndroidLoggerFactory} to instantiate + * SimpleLogger instances. + */ + AndroidLoggerAdapter(String tag) { + this.name = tag; + } + + /** + * Is this logger instance enabled for the VERBOSE level? + * + * @return True if this Logger is enabled for level VERBOSE, false otherwise. + */ + public boolean isTraceEnabled() { + return isLoggable(Log.VERBOSE); + } + + /** + * Log a message object at level VERBOSE. + * + * @param msg + * - the message object to be logged + */ + public void trace(String msg) { + log(Log.VERBOSE, msg, null); + } + + /** + * Log a message at level VERBOSE according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for level VERBOSE. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void trace(String format, Object arg) { + formatAndLog(Log.VERBOSE, format, arg); + } + + /** + * Log a message at level VERBOSE according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the VERBOSE level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void trace(String format, Object arg1, Object arg2) { + formatAndLog(Log.VERBOSE, format, arg1, arg2); + } + + /** + * Log a message at level VERBOSE according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the VERBOSE level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void trace(String format, Object... argArray) { + formatAndLog(Log.VERBOSE, format, argArray); + } + + /** + * Log an exception (throwable) at level VERBOSE with an accompanying message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void trace(String msg, Throwable t) { + log(Log.VERBOSE, msg, t); + } + + /** + * Is this logger instance enabled for the DEBUG level? + * + * @return True if this Logger is enabled for level DEBUG, false otherwise. + */ + public boolean isDebugEnabled() { + return isLoggable(Log.DEBUG); + } + + /** + * Log a message object at level DEBUG. + * + * @param msg + * - the message object to be logged + */ + public void debug(String msg) { + log(Log.DEBUG, msg, null); + } + + /** + * Log a message at level DEBUG according to the specified format and argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for level DEBUG. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void debug(String format, Object arg) { + formatAndLog(Log.DEBUG, format, arg); + } + + /** + * Log a message at level DEBUG according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the DEBUG level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void debug(String format, Object arg1, Object arg2) { + formatAndLog(Log.DEBUG, format, arg1, arg2); + } + + /** + * Log a message at level DEBUG according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the DEBUG level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void debug(String format, Object... argArray) { + formatAndLog(Log.DEBUG, format, argArray); + } + + /** + * Log an exception (throwable) at level DEBUG with an accompanying message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void debug(String msg, Throwable t) { + log(Log.VERBOSE, msg, t); + } + + /** + * Is this logger instance enabled for the INFO level? + * + * @return True if this Logger is enabled for the INFO level, false otherwise. + */ + public boolean isInfoEnabled() { + return isLoggable(Log.INFO); + } + + /** + * Log a message object at the INFO level. + * + * @param msg + * - the message object to be logged + */ + public void info(String msg) { + log(Log.INFO, msg, null); + } + + /** + * Log a message at level INFO according to the specified format and argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void info(String format, Object arg) { + formatAndLog(Log.INFO, format, arg); + } + + /** + * Log a message at the INFO level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void info(String format, Object arg1, Object arg2) { + formatAndLog(Log.INFO, format, arg1, arg2); + } + + /** + * Log a message at level INFO according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void info(String format, Object... argArray) { + formatAndLog(Log.INFO, format, argArray); + } + + /** + * Log an exception (throwable) at the INFO level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void info(String msg, Throwable t) { + log(Log.INFO, msg, t); + } + + /** + * Is this logger instance enabled for the WARN level? + * + * @return True if this Logger is enabled for the WARN level, false + * otherwise. + */ + public boolean isWarnEnabled() { + return isLoggable(Log.WARN); + } + + /** + * Log a message object at the WARN level. + * + * @param msg + * - the message object to be logged + */ + public void warn(String msg) { + log(Log.WARN, msg, null); + } + + /** + * Log a message at the WARN level according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARN level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void warn(String format, Object arg) { + formatAndLog(Log.WARN, format, arg); + } + + /** + * Log a message at the WARN level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARN level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void warn(String format, Object arg1, Object arg2) { + formatAndLog(Log.WARN, format, arg1, arg2); + } + + /** + * Log a message at level WARN according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARN level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void warn(String format, Object... argArray) { + formatAndLog(Log.WARN, format, argArray); + } + + /** + * Log an exception (throwable) at the WARN level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void warn(String msg, Throwable t) { + log(Log.WARN, msg, t); + } + + /** + * Is this logger instance enabled for level ERROR? + * + * @return True if this Logger is enabled for level ERROR, false otherwise. + */ + public boolean isErrorEnabled() { + return isLoggable(Log.ERROR); + } + + /** + * Log a message object at the ERROR level. + * + * @param msg + * - the message object to be logged + */ + public void error(String msg) { + log(Log.ERROR, msg, null); + } + + /** + * Log a message at the ERROR level according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the ERROR level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void error(String format, Object arg) { + formatAndLog(Log.ERROR, format, arg); + } + + /** + * Log a message at the ERROR level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the ERROR level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void error(String format, Object arg1, Object arg2) { + formatAndLog(Log.ERROR, format, arg1, arg2); + } + + /** + * Log a message at level ERROR according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the ERROR level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void error(String format, Object... argArray) { + formatAndLog(Log.ERROR, format, argArray); + } + + /** + * Log an exception (throwable) at the ERROR level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void error(String msg, Throwable t) { + log(Log.ERROR, msg, t); + } + + private void formatAndLog(int priority, String format, Object... argArray) { + if (isLoggable(priority)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + logInternal(priority, ft.getMessage(), ft.getThrowable()); + } + } + + private void log(int priority, String message, Throwable throwable) { + if (isLoggable(priority)) { + logInternal(priority, message, throwable); + } + } + + private boolean isLoggable(int priority) { + return Log.isLoggable(name, priority); + } + + private void logInternal(int priority, String message, Throwable throwable) { + if (throwable != null) { + message += '\n' + Log.getStackTraceString(throwable); + } + Log.println(priority, name, message); + } }diff --git a/slf4j-android/src/main/java/org/slf4j/impl/AndroidLoggerFactory.java b/slf4j-android/src/main/java/org/slf4j/impl/AndroidLoggerFactory.java old file mode 100644 new file mode 100755 index 3033378..d4ae5ef 100755 --- a/slf4j-android/src/main/java/org/slf4j/impl/AndroidLoggerFactory.java +++ b/slf4j-android/src/main/java/org/slf4j/impl/AndroidLoggerFactory.java @@ -1,123 +1,123 @@ -/* - * Copyright (c) 2004-2013 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.Logger; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * AndroidLoggerFactory is an implementation of {@link ILoggerFactory} returning - * the appropriately named {@link AndroidLoggerFactory} instance. - * - * @author Andrey Korzhevskiy - */ -class AndroidLoggerFactory implements ILoggerFactory { - static final String ANONYMOUS_TAG = "null"; - static final int TAG_MAX_LENGTH = 23; - - private final ConcurrentMap loggerMap = new ConcurrentHashMap(); - - /** - * Return an appropriate {@link AndroidLoggerAdapter} instance by name. - */ - public Logger getLogger(String name) { - String tag = loggerNameToTag(name); - Logger logger = loggerMap.get(tag); - if (logger == null) { - Logger newInstance = new AndroidLoggerAdapter(tag); - Logger oldInstance = loggerMap.putIfAbsent(tag, newInstance); - logger = oldInstance == null ? newInstance : oldInstance; - } - return logger; - } - - /** - * Tag names cannot be longer than {@value #TAG_MAX_LENGTH} characters on Android platform. - * - * Returns the short logger tag (up to {@value #TAG_MAX_LENGTH} characters) for the given logger name. - * Traditionally loggers are named by fully-qualified Java classes; this - * method attempts to return a concise identifying part of such names. - * - * See also: - * android/system/core/include/cutils/property.h - * android/frameworks/base/core/jni/android_util_Log.cpp - * dalvik.system.DalvikLogging - * - */ - static String loggerNameToTag(String loggerName) { - // Anonymous logger - if (loggerName == null) { - return ANONYMOUS_TAG; - } - - int length = loggerName.length(); - if (length <= TAG_MAX_LENGTH) { - return loggerName; - } - - int tagLength = 0; - int lastTokenIndex = 0; - int lastPeriodIndex; - StringBuilder tagName = new StringBuilder(TAG_MAX_LENGTH + 3); - while ((lastPeriodIndex = loggerName.indexOf('.', lastTokenIndex)) != -1) { - tagName.append(loggerName.charAt(lastTokenIndex)); - // token of one character appended as is otherwise truncate it to one character - int tokenLength = lastPeriodIndex - lastTokenIndex; - if (tokenLength > 1) { - tagName.append('*'); - } - tagName.append('.'); - lastTokenIndex = lastPeriodIndex + 1; - - // check if name is already too long - tagLength = tagName.length(); - if (tagLength > TAG_MAX_LENGTH) { - return getSimpleName(loggerName); - } - } - - // Either we had no useful dot location at all - // or last token would exceed TAG_MAX_LENGTH - int tokenLength = length - lastTokenIndex; - if (tagLength == 0 || (tagLength + tokenLength) > TAG_MAX_LENGTH) { - return getSimpleName(loggerName); - } - - // last token (usually class name) appended as is - tagName.append(loggerName, lastTokenIndex, length); - return tagName.toString(); - } - - private static String getSimpleName(String loggerName) { - // Take leading part and append '*' to indicate that it was truncated - int length = loggerName.length(); - int lastPeriodIndex = loggerName.lastIndexOf('.'); - return lastPeriodIndex != -1 && length - (lastPeriodIndex + 1) <= TAG_MAX_LENGTH ? loggerName.substring(lastPeriodIndex + 1) : '*' + loggerName - .substring(length - TAG_MAX_LENGTH + 1); - } +/* + * Copyright (c) 2004-2013 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.Logger; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * AndroidLoggerFactory is an implementation of {@link ILoggerFactory} returning + * the appropriately named {@link AndroidLoggerFactory} instance. + * + * @author Andrey Korzhevskiy + */ +class AndroidLoggerFactory implements ILoggerFactory { + static final String ANONYMOUS_TAG = "null"; + static final int TAG_MAX_LENGTH = 23; + + private final ConcurrentMap loggerMap = new ConcurrentHashMap(); + + /** + * Return an appropriate {@link AndroidLoggerAdapter} instance by name. + */ + public Logger getLogger(String name) { + String tag = loggerNameToTag(name); + Logger logger = loggerMap.get(tag); + if (logger == null) { + Logger newInstance = new AndroidLoggerAdapter(tag); + Logger oldInstance = loggerMap.putIfAbsent(tag, newInstance); + logger = oldInstance == null ? newInstance : oldInstance; + } + return logger; + } + + /** + * Tag names cannot be longer than {@value #TAG_MAX_LENGTH} characters on Android platform. + * + * Returns the short logger tag (up to {@value #TAG_MAX_LENGTH} characters) for the given logger name. + * Traditionally loggers are named by fully-qualified Java classes; this + * method attempts to return a concise identifying part of such names. + * + * See also: + * android/system/core/include/cutils/property.h + * android/frameworks/base/core/jni/android_util_Log.cpp + * dalvik.system.DalvikLogging + * + */ + static String loggerNameToTag(String loggerName) { + // Anonymous logger + if (loggerName == null) { + return ANONYMOUS_TAG; + } + + int length = loggerName.length(); + if (length <= TAG_MAX_LENGTH) { + return loggerName; + } + + int tagLength = 0; + int lastTokenIndex = 0; + int lastPeriodIndex; + StringBuilder tagName = new StringBuilder(TAG_MAX_LENGTH + 3); + while ((lastPeriodIndex = loggerName.indexOf('.', lastTokenIndex)) != -1) { + tagName.append(loggerName.charAt(lastTokenIndex)); + // token of one character appended as is otherwise truncate it to one character + int tokenLength = lastPeriodIndex - lastTokenIndex; + if (tokenLength > 1) { + tagName.append('*'); + } + tagName.append('.'); + lastTokenIndex = lastPeriodIndex + 1; + + // check if name is already too long + tagLength = tagName.length(); + if (tagLength > TAG_MAX_LENGTH) { + return getSimpleName(loggerName); + } + } + + // Either we had no useful dot location at all + // or last token would exceed TAG_MAX_LENGTH + int tokenLength = length - lastTokenIndex; + if (tagLength == 0 || (tagLength + tokenLength) > TAG_MAX_LENGTH) { + return getSimpleName(loggerName); + } + + // last token (usually class name) appended as is + tagName.append(loggerName, lastTokenIndex, length); + return tagName.toString(); + } + + private static String getSimpleName(String loggerName) { + // Take leading part and append '*' to indicate that it was truncated + int length = loggerName.length(); + int lastPeriodIndex = loggerName.lastIndexOf('.'); + return lastPeriodIndex != -1 && length - (lastPeriodIndex + 1) <= TAG_MAX_LENGTH ? loggerName.substring(lastPeriodIndex + 1) : '*' + loggerName + .substring(length - TAG_MAX_LENGTH + 1); + } }diff --git a/slf4j-android/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/slf4j-android/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index 426ccae..e21eafe 100644 --- a/slf4j-android/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-android/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,80 +1,80 @@ -/** - * Copyright (c) 2004-2013 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - * @author Andrey Korzhevskiy - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - /** - * Declare the version of the SLF4J API this implementation is compiled against. - * The value of this field is modified with each major release. - */ - // to avoid constant folding by the compiler, this field must *not* be final - public static String REQUESTED_API_VERSION = "1.6.99"; // !final - - private static final String loggerFactoryClassStr = AndroidLoggerFactory.class.getName(); - - /** - * The ILoggerFactory instance returned by the {@link #getLoggerFactory} method - * should always be the same object - */ - private final ILoggerFactory loggerFactory; - - private StaticLoggerBinder() { - loggerFactory = new AndroidLoggerFactory(); - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/** + * Copyright (c) 2004-2013 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + * @author Andrey Korzhevskiy + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is modified with each major release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; // !final + + private static final String loggerFactoryClassStr = AndroidLoggerFactory.class.getName(); + + /** + * The ILoggerFactory instance returned by the {@link #getLoggerFactory} method + * should always be the same object + */ + private final ILoggerFactory loggerFactory; + + private StaticLoggerBinder() { + loggerFactory = new AndroidLoggerFactory(); + } + + public ILoggerFactory getLoggerFactory() { + return loggerFactory; + } + + public String getLoggerFactoryClassStr() { + return loggerFactoryClassStr; + } +} diff --git a/slf4j-android/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/slf4j-android/src/main/java/org/slf4j/impl/StaticMDCBinder.java index 953e0e2..93f58fb 100644 --- a/slf4j-android/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-android/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,67 +1,67 @@ -/** - * Copyright (c) 2004-2013 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.helpers.NOPMDCAdapter; -import org.slf4j.spi.MDCAdapter; - -/** - * This implementation is bound to {@link NOPMDCAdapter}. - * - * @author Ceki Gülcü - * @author Andrey Korzhevskiy - */ -public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - - private StaticMDCBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMDCBinder singleton - * @since 1.7.14 - */ - public static final StaticMDCBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link NOPMDCAdapter}. - */ - public MDCAdapter getMDCA() { - return new NOPMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return NOPMDCAdapter.class.getName(); - } -} +/** + * Copyright (c) 2004-2013 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.helpers.NOPMDCAdapter; +import org.slf4j.spi.MDCAdapter; + +/** + * This implementation is bound to {@link NOPMDCAdapter}. + * + * @author Ceki Gülcü + * @author Andrey Korzhevskiy + */ +public class StaticMDCBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMDCBinder singleton + * @since 1.7.14 + */ + public static final StaticMDCBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link NOPMDCAdapter}. + */ + public MDCAdapter getMDCA() { + return new NOPMDCAdapter(); + } + + public String getMDCAdapterClassStr() { + return NOPMDCAdapter.class.getName(); + } +} diff --git a/slf4j-android/src/main/java/org/slf4j/impl/StaticMarkerBinder.java b/slf4j-android/src/main/java/org/slf4j/impl/StaticMarkerBinder.java index 21a4427..2c50662 100644 --- a/slf4j-android/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-android/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,77 +1,77 @@ -/** - * Copyright (c) 2004-2013 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - * @author Andrey Korzhevskiy - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMarkerBinder singleton - * @since 1.7.14 - */ - public static StaticMarkerBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } -} +/** + * Copyright (c) 2004-2013 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + * @author Andrey Korzhevskiy + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMarkerBinder singleton + * @since 1.7.14 + */ + public static StaticMarkerBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } +} diff --git a/slf4j-android/src/main/resources/META-INF/MANIFEST.MF b/slf4j-android/src/main/resources/META-INF/MANIFEST.MF index 7bb0895..d71f94c 100644 --- a/slf4j-android/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-android/src/main/resources/META-INF/MANIFEST.MF @@ -1,9 +1,9 @@ -Implementation-Title: slf4j-android -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.android -Bundle-Name: slf4j-android -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion} +Implementation-Title: slf4j-android +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.android +Bundle-Name: slf4j-android +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion} Fragment-Host: slf4j.apidiff --git a/slf4j-android/src/test/java/org/slf4j/impl/AndroidLoggerFactoryTest.java b/slf4j-android/src/test/java/org/slf4j/impl/AndroidLoggerFactoryTest.java index 993474f..12c0a7a 100644 --- a/slf4j-android/src/test/java/org/slf4j/impl/AndroidLoggerFactoryTest.java +++ b/slf4j-android/src/test/java/org/slf4j/impl/AndroidLoggerFactoryTest.java @@ -1,79 +1,79 @@ -/* - * Copyright (c) 2004-2013 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class AndroidLoggerFactoryTest { - @Test - public void shortLoggerNames() { - assertEquals("o.test.p.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.p.TestClass")); - assertEquals("ex.test.TestClass", AndroidLoggerFactory.loggerNameToTag("ex.test.TestClass")); - assertEquals("MyClass", AndroidLoggerFactory.loggerNameToTag("MyClass")); - } - - @Test - public void emptyLoggerNames() { - assertEquals(AndroidLoggerFactory.ANONYMOUS_TAG, AndroidLoggerFactory.loggerNameToTag(null)); - assertEquals("", AndroidLoggerFactory.loggerNameToTag("")); - } - - @Test - public void simpleLoggerName() { - assertEquals("o*.t*.p*.TestClass", AndroidLoggerFactory.loggerNameToTag("org.test.package.TestClass")); - } - - @Test - public void loggerNameWithOneCharPackage() { - assertEquals("o.t*.p*.p*.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.project.package.TestClass")); - assertEquals("o.t*.p*.p.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.project.p.TestClass")); - } - - @Test - public void longLoggerName() { - assertEquals("AndroidLoggerFactory", AndroidLoggerFactory.loggerNameToTag("org.slf4j.impl.AndroidLoggerFactory")); - } - - @Test - public void veryLongLoggerName() { - assertEquals("*meAndShouldBeTruncated", AndroidLoggerFactory.loggerNameToTag("IAmAVeryLongLoggerNameAndShouldBeTruncated")); - } - - @Test - public void oneWordLoggerName() { - assertEquals("TestClass", AndroidLoggerFactory.loggerNameToTag("TestClass")); - } - - @Test - public void weirdLoggerNames() { - assertEquals("WeirdLoggerName.", AndroidLoggerFactory.loggerNameToTag("WeirdLoggerName.")); - assertEquals(".WeirdLoggerName", AndroidLoggerFactory.loggerNameToTag(".WeirdLoggerName")); - assertEquals(".WeirdLoggerName.", AndroidLoggerFactory.loggerNameToTag(".WeirdLoggerName.")); - assertEquals(".", AndroidLoggerFactory.loggerNameToTag(".")); - assertEquals("..", AndroidLoggerFactory.loggerNameToTag("..")); - } -} +/* + * Copyright (c) 2004-2013 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AndroidLoggerFactoryTest { + @Test + public void shortLoggerNames() { + assertEquals("o.test.p.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.p.TestClass")); + assertEquals("ex.test.TestClass", AndroidLoggerFactory.loggerNameToTag("ex.test.TestClass")); + assertEquals("MyClass", AndroidLoggerFactory.loggerNameToTag("MyClass")); + } + + @Test + public void emptyLoggerNames() { + assertEquals(AndroidLoggerFactory.ANONYMOUS_TAG, AndroidLoggerFactory.loggerNameToTag(null)); + assertEquals("", AndroidLoggerFactory.loggerNameToTag("")); + } + + @Test + public void simpleLoggerName() { + assertEquals("o*.t*.p*.TestClass", AndroidLoggerFactory.loggerNameToTag("org.test.package.TestClass")); + } + + @Test + public void loggerNameWithOneCharPackage() { + assertEquals("o.t*.p*.p*.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.project.package.TestClass")); + assertEquals("o.t*.p*.p.TestClass", AndroidLoggerFactory.loggerNameToTag("o.test.project.p.TestClass")); + } + + @Test + public void longLoggerName() { + assertEquals("AndroidLoggerFactory", AndroidLoggerFactory.loggerNameToTag("org.slf4j.impl.AndroidLoggerFactory")); + } + + @Test + public void veryLongLoggerName() { + assertEquals("*meAndShouldBeTruncated", AndroidLoggerFactory.loggerNameToTag("IAmAVeryLongLoggerNameAndShouldBeTruncated")); + } + + @Test + public void oneWordLoggerName() { + assertEquals("TestClass", AndroidLoggerFactory.loggerNameToTag("TestClass")); + } + + @Test + public void weirdLoggerNames() { + assertEquals("WeirdLoggerName.", AndroidLoggerFactory.loggerNameToTag("WeirdLoggerName.")); + assertEquals(".WeirdLoggerName", AndroidLoggerFactory.loggerNameToTag(".WeirdLoggerName")); + assertEquals(".WeirdLoggerName.", AndroidLoggerFactory.loggerNameToTag(".WeirdLoggerName.")); + assertEquals(".", AndroidLoggerFactory.loggerNameToTag(".")); + assertEquals("..", AndroidLoggerFactory.loggerNameToTag("..")); + } +} diff --git a/slf4j-api/LICENSE.txt b/slf4j-api/LICENSE.txt new file mode 100644 index 0000000..508a272 --- /dev/null +++ b/slf4j-api/LICENSE.txt @@ -0,0 +1,24 @@ +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-api/pom.xml b/slf4j-api/pom.xml old file mode 100644 new file mode 100755 index a33ed63..587adfe 100755 --- a/slf4j-api/pom.xml +++ b/slf4j-api/pom.xml @@ -1,120 +1,120 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - slf4j-api - - jar - SLF4J API Module - The slf4j API - - http://www.slf4j.org - - - - - org.codehaus.mojo - animal-sniffer-maven-plugin - - - - org.slf4j.impl.StaticMDCBinder - org.slf4j.impl.StaticLoggerBinder - org.slf4j.impl.StaticMarkerBinder - - - - - org.apache.maven.plugins - maven-surefire-plugin - - once - plain - false - - **/AllTest.java - **/PackageTest.java - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - bundle-test-jar - package - - jar - test-jar - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - process-classes - - run - - - - - - Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder - - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-antrun-plugin - - [1.3,) - - run - - - - - - - - - - - - - - - \ No newline at end of file + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + slf4j-api + + jar + SLF4J API Module + The slf4j API + + http://www.slf4j.org + + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + + + + org.slf4j.impl.StaticMDCBinder + org.slf4j.impl.StaticLoggerBinder + org.slf4j.impl.StaticMarkerBinder + + + + + org.apache.maven.plugins + maven-surefire-plugin + + once + plain + false + + **/AllTest.java + **/PackageTest.java + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + bundle-test-jar + package + + jar + test-jar + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + process-classes + + run + + + + + + Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder + + + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-antrun-plugin + + [1.3,) + + run + + + + + + + + + + + + + + + diff --git a/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java b/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java index cdd6338..8ed82f3 100644 --- a/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java @@ -1,57 +1,57 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -/** - * ILoggerFactory instances manufacture {@link Logger} - * instances by name. - * - *

Most users retrieve {@link Logger} instances through the static - * {@link LoggerFactory#getLogger(String)} method. An instance of of this - * interface is bound internally with {@link LoggerFactory} class at - * compile time. - * - * @author Ceki Gülcü - */ -public interface ILoggerFactory { - - /** - * Return an appropriate {@link Logger} instance as specified by the - * name parameter. - * - *

If the name parameter is equal to {@link Logger#ROOT_LOGGER_NAME}, that is - * the string value "ROOT" (case insensitive), then the root logger of the - * underlying logging system is returned. - * - *

Null-valued name arguments are considered invalid. - * - *

Certain extremely simple logging systems, e.g. NOP, may always - * return the same logger instance regardless of the requested name. - * - * @param name the name of the Logger to return - * @return a Logger instance - */ - public Logger getLogger(String name); -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +/** + * ILoggerFactory instances manufacture {@link Logger} + * instances by name. + * + *

Most users retrieve {@link Logger} instances through the static + * {@link LoggerFactory#getLogger(String)} method. An instance of of this + * interface is bound internally with {@link LoggerFactory} class at + * compile time. + * + * @author Ceki Gülcü + */ +public interface ILoggerFactory { + + /** + * Return an appropriate {@link Logger} instance as specified by the + * name parameter. + * + *

If the name parameter is equal to {@link Logger#ROOT_LOGGER_NAME}, that is + * the string value "ROOT" (case insensitive), then the root logger of the + * underlying logging system is returned. + * + *

Null-valued name arguments are considered invalid. + * + *

Certain extremely simple logging systems, e.g. NOP, may always + * return the same logger instance regardless of the requested name. + * + * @param name the name of the Logger to return + * @return a Logger instance + */ + public Logger getLogger(String name); +} diff --git a/slf4j-api/src/main/java/org/slf4j/IMarkerFactory.java b/slf4j-api/src/main/java/org/slf4j/IMarkerFactory.java index 88a1d42..7570221 100644 --- a/slf4j-api/src/main/java/org/slf4j/IMarkerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/IMarkerFactory.java @@ -1,81 +1,81 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -/** - * Implementations of this interface are used to manufacture {@link Marker} - * instances. - * - *

See the section Implementing - * the SLF4J API in the FAQ for details on how to make your logging - * system conform to SLF4J. - * - * @author Ceki Gülcü - */ -public interface IMarkerFactory { - - /** - * Manufacture a {@link Marker} instance by name. If the instance has been - * created earlier, return the previously created instance. - * - *

Null name values are not allowed. - * - * @param name the name of the marker to be created, null value is - * not allowed. - * - * @return a Marker instance - */ - Marker getMarker(String name); - - /** - * Checks if the marker with the name already exists. If name is null, then false - * is returned. - * - * @param name logger name to check for - * @return true id the marker exists, false otherwise. - */ - boolean exists(String name); - - /** - * Detach an existing marker. - *

- * Note that after a marker is detached, there might still be "dangling" references - * to the detached marker. - * - * - * @param name The name of the marker to detach - * @return whether the marker could be detached or not - */ - boolean detachMarker(String name); - - /** - * Create a marker which is detached (even at birth) from this IMarkerFactory. - * - * @param name marker name - * @return a dangling marker - * @since 1.5.1 - */ - Marker getDetachedMarker(String name); -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +/** + * Implementations of this interface are used to manufacture {@link Marker} + * instances. + * + *

See the section Implementing + * the SLF4J API in the FAQ for details on how to make your logging + * system conform to SLF4J. + * + * @author Ceki Gülcü + */ +public interface IMarkerFactory { + + /** + * Manufacture a {@link Marker} instance by name. If the instance has been + * created earlier, return the previously created instance. + * + *

Null name values are not allowed. + * + * @param name the name of the marker to be created, null value is + * not allowed. + * + * @return a Marker instance + */ + Marker getMarker(String name); + + /** + * Checks if the marker with the name already exists. If name is null, then false + * is returned. + * + * @param name logger name to check for + * @return true id the marker exists, false otherwise. + */ + boolean exists(String name); + + /** + * Detach an existing marker. + *

+ * Note that after a marker is detached, there might still be "dangling" references + * to the detached marker. + * + * + * @param name The name of the marker to detach + * @return whether the marker could be detached or not + */ + boolean detachMarker(String name); + + /** + * Create a marker which is detached (even at birth) from this IMarkerFactory. + * + * @param name marker name + * @return a dangling marker + * @since 1.5.1 + */ + Marker getDetachedMarker(String name); +} diff --git a/slf4j-api/src/main/java/org/slf4j/Logger.java b/slf4j-api/src/main/java/org/slf4j/Logger.java index 6e4b552..93dd994 100644 --- a/slf4j-api/src/main/java/org/slf4j/Logger.java +++ b/slf4j-api/src/main/java/org/slf4j/Logger.java @@ -1,721 +1,721 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -package org.slf4j; - -/** - * The org.slf4j.Logger interface is the main user entry point of SLF4J API. - * It is expected that logging takes place through concrete implementations - * of this interface. - *

- *

Typical usage pattern:

- *
- * import org.slf4j.Logger;
- * import org.slf4j.LoggerFactory;
- *
- * public class Wombat {
- *
- *   final static Logger logger = LoggerFactory.getLogger(Wombat.class);
- *   Integer t;
- *   Integer oldT;
- *
- *   public void setTemperature(Integer temperature) {
- *     oldT = t;
- *     t = temperature;
- *     logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);
- *     if(temperature.intValue() > 50) {
- *       logger.info("Temperature has risen above 50 degrees.");
- *     }
- *   }
- * }
- * 
- * - * Be sure to read the FAQ entry relating to parameterized - * logging. Note that logging statements can be parameterized in - * presence of an exception/throwable. - * - *

Once you are comfortable using loggers, i.e. instances of this interface, consider using - * MDC as well as Markers.

- * - * @author Ceki Gülcü - */ -public interface Logger { - - /** - * Case insensitive String constant used to retrieve the name of the root logger. - * - * @since 1.3 - */ - final public String ROOT_LOGGER_NAME = "ROOT"; - - /** - * Return the name of this Logger instance. - * @return name of this logger instance - */ - public String getName(); - - /** - * Is the logger instance enabled for the TRACE level? - * - * @return True if this Logger is enabled for the TRACE level, - * false otherwise. - * @since 1.4 - */ - public boolean isTraceEnabled(); - - /** - * Log a message at the TRACE level. - * - * @param msg the message string to be logged - * @since 1.4 - */ - public void trace(String msg); - - /** - * Log a message at the TRACE level according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the TRACE level.

- * - * @param format the format string - * @param arg the argument - * @since 1.4 - */ - public void trace(String format, Object arg); - - /** - * Log a message at the TRACE level according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the TRACE level.

- * - * @param format the format string - * @param arg1 the first argument - * @param arg2 the second argument - * @since 1.4 - */ - public void trace(String format, Object arg1, Object arg2); - - /** - * Log a message at the TRACE level according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the TRACE level. However, this variant incurs the hidden - * (and relatively small) cost of creating an Object[] before invoking the method, - * even if this logger is disabled for TRACE. The variants taking {@link #trace(String, Object) one} and - * {@link #trace(String, Object, Object) two} arguments exist solely in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - * @since 1.4 - */ - public void trace(String format, Object... arguments); - - /** - * Log an exception (throwable) at the TRACE level with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - * @since 1.4 - */ - public void trace(String msg, Throwable t); - - /** - * Similar to {@link #isTraceEnabled()} method except that the - * marker data is also taken into account. - * - * @param marker The marker data to take into consideration - * @return True if this Logger is enabled for the TRACE level, - * false otherwise. - * - * @since 1.4 - */ - public boolean isTraceEnabled(Marker marker); - - /** - * Log a message with the specific Marker at the TRACE level. - * - * @param marker the marker data specific to this log statement - * @param msg the message string to be logged - * @since 1.4 - */ - public void trace(Marker marker, String msg); - - /** - * This method is similar to {@link #trace(String, Object)} method except that the - * marker data is also taken into consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arg the argument - * @since 1.4 - */ - public void trace(Marker marker, String format, Object arg); - - /** - * This method is similar to {@link #trace(String, Object, Object)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arg1 the first argument - * @param arg2 the second argument - * @since 1.4 - */ - public void trace(Marker marker, String format, Object arg1, Object arg2); - - /** - * This method is similar to {@link #trace(String, Object...)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param argArray an array of arguments - * @since 1.4 - */ - public void trace(Marker marker, String format, Object... argArray); - - /** - * This method is similar to {@link #trace(String, Throwable)} method except that the - * marker data is also taken into consideration. - * - * @param marker the marker data specific to this log statement - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - * @since 1.4 - */ - public void trace(Marker marker, String msg, Throwable t); - - /** - * Is the logger instance enabled for the DEBUG level? - * - * @return True if this Logger is enabled for the DEBUG level, - * false otherwise. - */ - public boolean isDebugEnabled(); - - /** - * Log a message at the DEBUG level. - * - * @param msg the message string to be logged - */ - public void debug(String msg); - - /** - * Log a message at the DEBUG level according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the DEBUG level.

- * - * @param format the format string - * @param arg the argument - */ - public void debug(String format, Object arg); - - /** - * Log a message at the DEBUG level according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the DEBUG level.

- * - * @param format the format string - * @param arg1 the first argument - * @param arg2 the second argument - */ - public void debug(String format, Object arg1, Object arg2); - - /** - * Log a message at the DEBUG level according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the DEBUG level. However, this variant incurs the hidden - * (and relatively small) cost of creating an Object[] before invoking the method, - * even if this logger is disabled for DEBUG. The variants taking - * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two} - * arguments exist solely in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void debug(String format, Object... arguments); - - /** - * Log an exception (throwable) at the DEBUG level with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - public void debug(String msg, Throwable t); - - /** - * Similar to {@link #isDebugEnabled()} method except that the - * marker data is also taken into account. - * - * @param marker The marker data to take into consideration - * @return True if this Logger is enabled for the DEBUG level, - * false otherwise. - */ - public boolean isDebugEnabled(Marker marker); - - /** - * Log a message with the specific Marker at the DEBUG level. - * - * @param marker the marker data specific to this log statement - * @param msg the message string to be logged - */ - public void debug(Marker marker, String msg); - - /** - * This method is similar to {@link #debug(String, Object)} method except that the - * marker data is also taken into consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arg the argument - */ - public void debug(Marker marker, String format, Object arg); - - /** - * This method is similar to {@link #debug(String, Object, Object)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arg1 the first argument - * @param arg2 the second argument - */ - public void debug(Marker marker, String format, Object arg1, Object arg2); - - /** - * This method is similar to {@link #debug(String, Object...)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void debug(Marker marker, String format, Object... arguments); - - /** - * This method is similar to {@link #debug(String, Throwable)} method except that the - * marker data is also taken into consideration. - * - * @param marker the marker data specific to this log statement - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - public void debug(Marker marker, String msg, Throwable t); - - /** - * Is the logger instance enabled for the INFO level? - * - * @return True if this Logger is enabled for the INFO level, - * false otherwise. - */ - public boolean isInfoEnabled(); - - /** - * Log a message at the INFO level. - * - * @param msg the message string to be logged - */ - public void info(String msg); - - /** - * Log a message at the INFO level according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the INFO level.

- * - * @param format the format string - * @param arg the argument - */ - public void info(String format, Object arg); - - /** - * Log a message at the INFO level according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the INFO level.

- * - * @param format the format string - * @param arg1 the first argument - * @param arg2 the second argument - */ - public void info(String format, Object arg1, Object arg2); - - /** - * Log a message at the INFO level according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the INFO level. However, this variant incurs the hidden - * (and relatively small) cost of creating an Object[] before invoking the method, - * even if this logger is disabled for INFO. The variants taking - * {@link #info(String, Object) one} and {@link #info(String, Object, Object) two} - * arguments exist solely in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void info(String format, Object... arguments); - - /** - * Log an exception (throwable) at the INFO level with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - public void info(String msg, Throwable t); - - /** - * Similar to {@link #isInfoEnabled()} method except that the marker - * data is also taken into consideration. - * - * @param marker The marker data to take into consideration - * @return true if this logger is warn enabled, false otherwise - */ - public boolean isInfoEnabled(Marker marker); - - /** - * Log a message with the specific Marker at the INFO level. - * - * @param marker The marker specific to this log statement - * @param msg the message string to be logged - */ - public void info(Marker marker, String msg); - - /** - * This method is similar to {@link #info(String, Object)} method except that the - * marker data is also taken into consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arg the argument - */ - public void info(Marker marker, String format, Object arg); - - /** - * This method is similar to {@link #info(String, Object, Object)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arg1 the first argument - * @param arg2 the second argument - */ - public void info(Marker marker, String format, Object arg1, Object arg2); - - /** - * This method is similar to {@link #info(String, Object...)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void info(Marker marker, String format, Object... arguments); - - /** - * This method is similar to {@link #info(String, Throwable)} method - * except that the marker data is also taken into consideration. - * - * @param marker the marker data for this log statement - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - public void info(Marker marker, String msg, Throwable t); - - /** - * Is the logger instance enabled for the WARN level? - * - * @return True if this Logger is enabled for the WARN level, - * false otherwise. - */ - public boolean isWarnEnabled(); - - /** - * Log a message at the WARN level. - * - * @param msg the message string to be logged - */ - public void warn(String msg); - - /** - * Log a message at the WARN level according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the WARN level.

- * - * @param format the format string - * @param arg the argument - */ - public void warn(String format, Object arg); - - /** - * Log a message at the WARN level according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the WARN level. However, this variant incurs the hidden - * (and relatively small) cost of creating an Object[] before invoking the method, - * even if this logger is disabled for WARN. The variants taking - * {@link #warn(String, Object) one} and {@link #warn(String, Object, Object) two} - * arguments exist solely in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void warn(String format, Object... arguments); - - /** - * Log a message at the WARN level according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the WARN level.

- * - * @param format the format string - * @param arg1 the first argument - * @param arg2 the second argument - */ - public void warn(String format, Object arg1, Object arg2); - - /** - * Log an exception (throwable) at the WARN level with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - public void warn(String msg, Throwable t); - - /** - * Similar to {@link #isWarnEnabled()} method except that the marker - * data is also taken into consideration. - * - * @param marker The marker data to take into consideration - * @return True if this Logger is enabled for the WARN level, - * false otherwise. - */ - public boolean isWarnEnabled(Marker marker); - - /** - * Log a message with the specific Marker at the WARN level. - * - * @param marker The marker specific to this log statement - * @param msg the message string to be logged - */ - public void warn(Marker marker, String msg); - - /** - * This method is similar to {@link #warn(String, Object)} method except that the - * marker data is also taken into consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arg the argument - */ - public void warn(Marker marker, String format, Object arg); - - /** - * This method is similar to {@link #warn(String, Object, Object)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arg1 the first argument - * @param arg2 the second argument - */ - public void warn(Marker marker, String format, Object arg1, Object arg2); - - /** - * This method is similar to {@link #warn(String, Object...)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void warn(Marker marker, String format, Object... arguments); - - /** - * This method is similar to {@link #warn(String, Throwable)} method - * except that the marker data is also taken into consideration. - * - * @param marker the marker data for this log statement - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - public void warn(Marker marker, String msg, Throwable t); - - /** - * Is the logger instance enabled for the ERROR level? - * - * @return True if this Logger is enabled for the ERROR level, - * false otherwise. - */ - public boolean isErrorEnabled(); - - /** - * Log a message at the ERROR level. - * - * @param msg the message string to be logged - */ - public void error(String msg); - - /** - * Log a message at the ERROR level according to the specified format - * and argument. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the ERROR level.

- * - * @param format the format string - * @param arg the argument - */ - public void error(String format, Object arg); - - /** - * Log a message at the ERROR level according to the specified format - * and arguments. - *

- *

This form avoids superfluous object creation when the logger - * is disabled for the ERROR level.

- * - * @param format the format string - * @param arg1 the first argument - * @param arg2 the second argument - */ - public void error(String format, Object arg1, Object arg2); - - /** - * Log a message at the ERROR level according to the specified format - * and arguments. - *

- *

This form avoids superfluous string concatenation when the logger - * is disabled for the ERROR level. However, this variant incurs the hidden - * (and relatively small) cost of creating an Object[] before invoking the method, - * even if this logger is disabled for ERROR. The variants taking - * {@link #error(String, Object) one} and {@link #error(String, Object, Object) two} - * arguments exist solely in order to avoid this hidden cost.

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void error(String format, Object... arguments); - - /** - * Log an exception (throwable) at the ERROR level with an - * accompanying message. - * - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - public void error(String msg, Throwable t); - - /** - * Similar to {@link #isErrorEnabled()} method except that the - * marker data is also taken into consideration. - * - * @param marker The marker data to take into consideration - * @return True if this Logger is enabled for the ERROR level, - * false otherwise. - */ - public boolean isErrorEnabled(Marker marker); - - /** - * Log a message with the specific Marker at the ERROR level. - * - * @param marker The marker specific to this log statement - * @param msg the message string to be logged - */ - public void error(Marker marker, String msg); - - /** - * This method is similar to {@link #error(String, Object)} method except that the - * marker data is also taken into consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arg the argument - */ - public void error(Marker marker, String format, Object arg); - - /** - * This method is similar to {@link #error(String, Object, Object)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arg1 the first argument - * @param arg2 the second argument - */ - public void error(Marker marker, String format, Object arg1, Object arg2); - - /** - * This method is similar to {@link #error(String, Object...)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void error(Marker marker, String format, Object... arguments); - - /** - * This method is similar to {@link #error(String, Throwable)} - * method except that the marker data is also taken into - * consideration. - * - * @param marker the marker data specific to this log statement - * @param msg the message accompanying the exception - * @param t the exception (throwable) to log - */ - public void error(Marker marker, String msg, Throwable t); - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +package org.slf4j; + +/** + * The org.slf4j.Logger interface is the main user entry point of SLF4J API. + * It is expected that logging takes place through concrete implementations + * of this interface. + *

+ *

Typical usage pattern:

+ *
+ * import org.slf4j.Logger;
+ * import org.slf4j.LoggerFactory;
+ *
+ * public class Wombat {
+ *
+ *   final static Logger logger = LoggerFactory.getLogger(Wombat.class);
+ *   Integer t;
+ *   Integer oldT;
+ *
+ *   public void setTemperature(Integer temperature) {
+ *     oldT = t;
+ *     t = temperature;
+ *     logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);
+ *     if(temperature.intValue() > 50) {
+ *       logger.info("Temperature has risen above 50 degrees.");
+ *     }
+ *   }
+ * }
+ * 
+ * + * Be sure to read the FAQ entry relating to parameterized + * logging. Note that logging statements can be parameterized in + * presence of an exception/throwable. + * + *

Once you are comfortable using loggers, i.e. instances of this interface, consider using + * MDC as well as Markers.

+ * + * @author Ceki Gülcü + */ +public interface Logger { + + /** + * Case insensitive String constant used to retrieve the name of the root logger. + * + * @since 1.3 + */ + final public String ROOT_LOGGER_NAME = "ROOT"; + + /** + * Return the name of this Logger instance. + * @return name of this logger instance + */ + public String getName(); + + /** + * Is the logger instance enabled for the TRACE level? + * + * @return True if this Logger is enabled for the TRACE level, + * false otherwise. + * @since 1.4 + */ + public boolean isTraceEnabled(); + + /** + * Log a message at the TRACE level. + * + * @param msg the message string to be logged + * @since 1.4 + */ + public void trace(String msg); + + /** + * Log a message at the TRACE level according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the TRACE level.

+ * + * @param format the format string + * @param arg the argument + * @since 1.4 + */ + public void trace(String format, Object arg); + + /** + * Log a message at the TRACE level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the TRACE level.

+ * + * @param format the format string + * @param arg1 the first argument + * @param arg2 the second argument + * @since 1.4 + */ + public void trace(String format, Object arg1, Object arg2); + + /** + * Log a message at the TRACE level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the TRACE level. However, this variant incurs the hidden + * (and relatively small) cost of creating an Object[] before invoking the method, + * even if this logger is disabled for TRACE. The variants taking {@link #trace(String, Object) one} and + * {@link #trace(String, Object, Object) two} arguments exist solely in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + * @since 1.4 + */ + public void trace(String format, Object... arguments); + + /** + * Log an exception (throwable) at the TRACE level with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + * @since 1.4 + */ + public void trace(String msg, Throwable t); + + /** + * Similar to {@link #isTraceEnabled()} method except that the + * marker data is also taken into account. + * + * @param marker The marker data to take into consideration + * @return True if this Logger is enabled for the TRACE level, + * false otherwise. + * + * @since 1.4 + */ + public boolean isTraceEnabled(Marker marker); + + /** + * Log a message with the specific Marker at the TRACE level. + * + * @param marker the marker data specific to this log statement + * @param msg the message string to be logged + * @since 1.4 + */ + public void trace(Marker marker, String msg); + + /** + * This method is similar to {@link #trace(String, Object)} method except that the + * marker data is also taken into consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arg the argument + * @since 1.4 + */ + public void trace(Marker marker, String format, Object arg); + + /** + * This method is similar to {@link #trace(String, Object, Object)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arg1 the first argument + * @param arg2 the second argument + * @since 1.4 + */ + public void trace(Marker marker, String format, Object arg1, Object arg2); + + /** + * This method is similar to {@link #trace(String, Object...)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param argArray an array of arguments + * @since 1.4 + */ + public void trace(Marker marker, String format, Object... argArray); + + /** + * This method is similar to {@link #trace(String, Throwable)} method except that the + * marker data is also taken into consideration. + * + * @param marker the marker data specific to this log statement + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + * @since 1.4 + */ + public void trace(Marker marker, String msg, Throwable t); + + /** + * Is the logger instance enabled for the DEBUG level? + * + * @return True if this Logger is enabled for the DEBUG level, + * false otherwise. + */ + public boolean isDebugEnabled(); + + /** + * Log a message at the DEBUG level. + * + * @param msg the message string to be logged + */ + public void debug(String msg); + + /** + * Log a message at the DEBUG level according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the DEBUG level.

+ * + * @param format the format string + * @param arg the argument + */ + public void debug(String format, Object arg); + + /** + * Log a message at the DEBUG level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the DEBUG level.

+ * + * @param format the format string + * @param arg1 the first argument + * @param arg2 the second argument + */ + public void debug(String format, Object arg1, Object arg2); + + /** + * Log a message at the DEBUG level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the DEBUG level. However, this variant incurs the hidden + * (and relatively small) cost of creating an Object[] before invoking the method, + * even if this logger is disabled for DEBUG. The variants taking + * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two} + * arguments exist solely in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void debug(String format, Object... arguments); + + /** + * Log an exception (throwable) at the DEBUG level with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + public void debug(String msg, Throwable t); + + /** + * Similar to {@link #isDebugEnabled()} method except that the + * marker data is also taken into account. + * + * @param marker The marker data to take into consideration + * @return True if this Logger is enabled for the DEBUG level, + * false otherwise. + */ + public boolean isDebugEnabled(Marker marker); + + /** + * Log a message with the specific Marker at the DEBUG level. + * + * @param marker the marker data specific to this log statement + * @param msg the message string to be logged + */ + public void debug(Marker marker, String msg); + + /** + * This method is similar to {@link #debug(String, Object)} method except that the + * marker data is also taken into consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arg the argument + */ + public void debug(Marker marker, String format, Object arg); + + /** + * This method is similar to {@link #debug(String, Object, Object)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arg1 the first argument + * @param arg2 the second argument + */ + public void debug(Marker marker, String format, Object arg1, Object arg2); + + /** + * This method is similar to {@link #debug(String, Object...)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void debug(Marker marker, String format, Object... arguments); + + /** + * This method is similar to {@link #debug(String, Throwable)} method except that the + * marker data is also taken into consideration. + * + * @param marker the marker data specific to this log statement + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + public void debug(Marker marker, String msg, Throwable t); + + /** + * Is the logger instance enabled for the INFO level? + * + * @return True if this Logger is enabled for the INFO level, + * false otherwise. + */ + public boolean isInfoEnabled(); + + /** + * Log a message at the INFO level. + * + * @param msg the message string to be logged + */ + public void info(String msg); + + /** + * Log a message at the INFO level according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the INFO level.

+ * + * @param format the format string + * @param arg the argument + */ + public void info(String format, Object arg); + + /** + * Log a message at the INFO level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the INFO level.

+ * + * @param format the format string + * @param arg1 the first argument + * @param arg2 the second argument + */ + public void info(String format, Object arg1, Object arg2); + + /** + * Log a message at the INFO level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the INFO level. However, this variant incurs the hidden + * (and relatively small) cost of creating an Object[] before invoking the method, + * even if this logger is disabled for INFO. The variants taking + * {@link #info(String, Object) one} and {@link #info(String, Object, Object) two} + * arguments exist solely in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void info(String format, Object... arguments); + + /** + * Log an exception (throwable) at the INFO level with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + public void info(String msg, Throwable t); + + /** + * Similar to {@link #isInfoEnabled()} method except that the marker + * data is also taken into consideration. + * + * @param marker The marker data to take into consideration + * @return true if this logger is warn enabled, false otherwise + */ + public boolean isInfoEnabled(Marker marker); + + /** + * Log a message with the specific Marker at the INFO level. + * + * @param marker The marker specific to this log statement + * @param msg the message string to be logged + */ + public void info(Marker marker, String msg); + + /** + * This method is similar to {@link #info(String, Object)} method except that the + * marker data is also taken into consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arg the argument + */ + public void info(Marker marker, String format, Object arg); + + /** + * This method is similar to {@link #info(String, Object, Object)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arg1 the first argument + * @param arg2 the second argument + */ + public void info(Marker marker, String format, Object arg1, Object arg2); + + /** + * This method is similar to {@link #info(String, Object...)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void info(Marker marker, String format, Object... arguments); + + /** + * This method is similar to {@link #info(String, Throwable)} method + * except that the marker data is also taken into consideration. + * + * @param marker the marker data for this log statement + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + public void info(Marker marker, String msg, Throwable t); + + /** + * Is the logger instance enabled for the WARN level? + * + * @return True if this Logger is enabled for the WARN level, + * false otherwise. + */ + public boolean isWarnEnabled(); + + /** + * Log a message at the WARN level. + * + * @param msg the message string to be logged + */ + public void warn(String msg); + + /** + * Log a message at the WARN level according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the WARN level.

+ * + * @param format the format string + * @param arg the argument + */ + public void warn(String format, Object arg); + + /** + * Log a message at the WARN level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the WARN level. However, this variant incurs the hidden + * (and relatively small) cost of creating an Object[] before invoking the method, + * even if this logger is disabled for WARN. The variants taking + * {@link #warn(String, Object) one} and {@link #warn(String, Object, Object) two} + * arguments exist solely in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void warn(String format, Object... arguments); + + /** + * Log a message at the WARN level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the WARN level.

+ * + * @param format the format string + * @param arg1 the first argument + * @param arg2 the second argument + */ + public void warn(String format, Object arg1, Object arg2); + + /** + * Log an exception (throwable) at the WARN level with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + public void warn(String msg, Throwable t); + + /** + * Similar to {@link #isWarnEnabled()} method except that the marker + * data is also taken into consideration. + * + * @param marker The marker data to take into consideration + * @return True if this Logger is enabled for the WARN level, + * false otherwise. + */ + public boolean isWarnEnabled(Marker marker); + + /** + * Log a message with the specific Marker at the WARN level. + * + * @param marker The marker specific to this log statement + * @param msg the message string to be logged + */ + public void warn(Marker marker, String msg); + + /** + * This method is similar to {@link #warn(String, Object)} method except that the + * marker data is also taken into consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arg the argument + */ + public void warn(Marker marker, String format, Object arg); + + /** + * This method is similar to {@link #warn(String, Object, Object)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arg1 the first argument + * @param arg2 the second argument + */ + public void warn(Marker marker, String format, Object arg1, Object arg2); + + /** + * This method is similar to {@link #warn(String, Object...)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void warn(Marker marker, String format, Object... arguments); + + /** + * This method is similar to {@link #warn(String, Throwable)} method + * except that the marker data is also taken into consideration. + * + * @param marker the marker data for this log statement + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + public void warn(Marker marker, String msg, Throwable t); + + /** + * Is the logger instance enabled for the ERROR level? + * + * @return True if this Logger is enabled for the ERROR level, + * false otherwise. + */ + public boolean isErrorEnabled(); + + /** + * Log a message at the ERROR level. + * + * @param msg the message string to be logged + */ + public void error(String msg); + + /** + * Log a message at the ERROR level according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the ERROR level.

+ * + * @param format the format string + * @param arg the argument + */ + public void error(String format, Object arg); + + /** + * Log a message at the ERROR level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the ERROR level.

+ * + * @param format the format string + * @param arg1 the first argument + * @param arg2 the second argument + */ + public void error(String format, Object arg1, Object arg2); + + /** + * Log a message at the ERROR level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the ERROR level. However, this variant incurs the hidden + * (and relatively small) cost of creating an Object[] before invoking the method, + * even if this logger is disabled for ERROR. The variants taking + * {@link #error(String, Object) one} and {@link #error(String, Object, Object) two} + * arguments exist solely in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void error(String format, Object... arguments); + + /** + * Log an exception (throwable) at the ERROR level with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + public void error(String msg, Throwable t); + + /** + * Similar to {@link #isErrorEnabled()} method except that the + * marker data is also taken into consideration. + * + * @param marker The marker data to take into consideration + * @return True if this Logger is enabled for the ERROR level, + * false otherwise. + */ + public boolean isErrorEnabled(Marker marker); + + /** + * Log a message with the specific Marker at the ERROR level. + * + * @param marker The marker specific to this log statement + * @param msg the message string to be logged + */ + public void error(Marker marker, String msg); + + /** + * This method is similar to {@link #error(String, Object)} method except that the + * marker data is also taken into consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arg the argument + */ + public void error(Marker marker, String format, Object arg); + + /** + * This method is similar to {@link #error(String, Object, Object)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arg1 the first argument + * @param arg2 the second argument + */ + public void error(Marker marker, String format, Object arg1, Object arg2); + + /** + * This method is similar to {@link #error(String, Object...)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void error(Marker marker, String format, Object... arguments); + + /** + * This method is similar to {@link #error(String, Throwable)} + * method except that the marker data is also taken into + * consideration. + * + * @param marker the marker data specific to this log statement + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + public void error(Marker marker, String msg, Throwable t); + +} diff --git a/slf4j-api/src/main/java/org/slf4j/LoggerFactory.java b/slf4j-api/src/main/java/org/slf4j/LoggerFactory.java old file mode 100644 new file mode 100755 index c245a70..30b5c72 100755 --- a/slf4j-api/src/main/java/org/slf4j/LoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/LoggerFactory.java @@ -1,430 +1,430 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.LinkedBlockingQueue; - -import org.slf4j.event.SubstituteLoggingEvent; -import org.slf4j.helpers.NOPLoggerFactory; -import org.slf4j.helpers.SubstituteLogger; -import org.slf4j.helpers.SubstituteLoggerFactory; -import org.slf4j.helpers.Util; -import org.slf4j.impl.StaticLoggerBinder; - -/** - * The LoggerFactory is a utility class producing Loggers for - * various logging APIs, most notably for log4j, logback and JDK 1.4 logging. - * Other implementations such as {@link org.slf4j.impl.NOPLogger NOPLogger} and - * {@link org.slf4j.impl.SimpleLogger SimpleLogger} are also supported. - *

- *

- * LoggerFactory is essentially a wrapper around an - * {@link ILoggerFactory} instance bound with LoggerFactory at - * compile time. - *

- *

- * Please note that all methods in LoggerFactory are static. - * - * - * @author Alexander Dorokhine - * @author Robert Elliot - * @author Ceki Gülcü - * - */ -public final class LoggerFactory { - - static final String CODES_PREFIX = "http://www.slf4j.org/codes.html"; - - static final String NO_STATICLOGGERBINDER_URL = CODES_PREFIX + "#StaticLoggerBinder"; - static final String MULTIPLE_BINDINGS_URL = CODES_PREFIX + "#multiple_bindings"; - static final String NULL_LF_URL = CODES_PREFIX + "#null_LF"; - static final String VERSION_MISMATCH = CODES_PREFIX + "#version_mismatch"; - static final String SUBSTITUTE_LOGGER_URL = CODES_PREFIX + "#substituteLogger"; - static final String LOGGER_NAME_MISMATCH_URL = CODES_PREFIX + "#loggerNameMismatch"; - static final String REPLAY_URL = CODES_PREFIX + "#replay"; - - static final String UNSUCCESSFUL_INIT_URL = CODES_PREFIX + "#unsuccessfulInit"; - static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory in failed state. Original exception was thrown EARLIER. See also " + UNSUCCESSFUL_INIT_URL; - - static final int UNINITIALIZED = 0; - static final int ONGOING_INITIALIZATION = 1; - static final int FAILED_INITIALIZATION = 2; - static final int SUCCESSFUL_INITIALIZATION = 3; - static final int NOP_FALLBACK_INITIALIZATION = 4; - - static volatile int INITIALIZATION_STATE = UNINITIALIZED; - static final SubstituteLoggerFactory SUBST_FACTORY = new SubstituteLoggerFactory(); - static final NOPLoggerFactory NOP_FALLBACK_FACTORY = new NOPLoggerFactory(); - - // Support for detecting mismatched logger names. - static final String DETECT_LOGGER_NAME_MISMATCH_PROPERTY = "slf4j.detectLoggerNameMismatch"; - static final String JAVA_VENDOR_PROPERTY = "java.vendor.url"; - - static boolean DETECT_LOGGER_NAME_MISMATCH = Util.safeGetBooleanSystemProperty(DETECT_LOGGER_NAME_MISMATCH_PROPERTY); - - /** - * It is LoggerFactory's responsibility to track version changes and manage - * the compatibility list. - *

- *

- * It is assumed that all versions in the 1.6 are mutually compatible. - */ - static private final String[] API_COMPATIBILITY_LIST = new String[] { "1.6", "1.7" }; - - // private constructor prevents instantiation - private LoggerFactory() { - } - - /** - * Force LoggerFactory to consider itself uninitialized. - *

- *

- * This method is intended to be called by classes (in the same package) for - * testing purposes. This method is internal. It can be modified, renamed or - * removed at any time without notice. - *

- *

- * You are strongly discouraged from calling this method in production code. - */ - static void reset() { - INITIALIZATION_STATE = UNINITIALIZED; - } - - private final static void performInitialization() { - bind(); - if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) { - versionSanityCheck(); - } - } - - private static boolean messageContainsOrgSlf4jImplStaticLoggerBinder(String msg) { - if (msg == null) - return false; - if (msg.contains("org/slf4j/impl/StaticLoggerBinder")) - return true; - if (msg.contains("org.slf4j.impl.StaticLoggerBinder")) - return true; - return false; - } - - private final static void bind() { - try { - Set staticLoggerBinderPathSet = null; - // skip check under android, see also - // http://jira.qos.ch/browse/SLF4J-328 - if (!isAndroid()) { - staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet(); - reportMultipleBindingAmbiguity(staticLoggerBinderPathSet); - } - // the next line does the binding - StaticLoggerBinder.getSingleton(); - INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION; - reportActualBinding(staticLoggerBinderPathSet); - fixSubstituteLoggers(); - replayEvents(); - // release all resources in SUBST_FACTORY - SUBST_FACTORY.clear(); - } catch (NoClassDefFoundError ncde) { - String msg = ncde.getMessage(); - if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) { - INITIALIZATION_STATE = NOP_FALLBACK_INITIALIZATION; - Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\"."); - Util.report("Defaulting to no-operation (NOP) logger implementation"); - Util.report("See " + NO_STATICLOGGERBINDER_URL + " for further details."); - } else { - failedBinding(ncde); - throw ncde; - } - } catch (java.lang.NoSuchMethodError nsme) { - String msg = nsme.getMessage(); - if (msg != null && msg.contains("org.slf4j.impl.StaticLoggerBinder.getSingleton()")) { - INITIALIZATION_STATE = FAILED_INITIALIZATION; - Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding."); - Util.report("Your binding is version 1.5.5 or earlier."); - Util.report("Upgrade your binding to version 1.6.x."); - } - throw nsme; - } catch (Exception e) { - failedBinding(e); - throw new IllegalStateException("Unexpected initialization failure", e); - } - } - - private static void fixSubstituteLoggers() { - synchronized (SUBST_FACTORY) { - SUBST_FACTORY.postInitialization(); - for (SubstituteLogger substLogger : SUBST_FACTORY.getLoggers()) { - Logger logger = getLogger(substLogger.getName()); - substLogger.setDelegate(logger); - } - } - - } - - static void failedBinding(Throwable t) { - INITIALIZATION_STATE = FAILED_INITIALIZATION; - Util.report("Failed to instantiate SLF4J LoggerFactory", t); - } - - private static void replayEvents() { - final LinkedBlockingQueue queue = SUBST_FACTORY.getEventQueue(); - final int queueSize = queue.size(); - int count = 0; - final int maxDrain = 128; - List eventList = new ArrayList(maxDrain); - while (true) { - int numDrained = queue.drainTo(eventList, maxDrain); - if (numDrained == 0) - break; - for (SubstituteLoggingEvent event : eventList) { - replaySingleEvent(event); - if (count++ == 0) - emitReplayOrSubstituionWarning(event, queueSize); - } - eventList.clear(); - } - } - - private static void emitReplayOrSubstituionWarning(SubstituteLoggingEvent event, int queueSize) { - if (event.getLogger().isDelegateEventAware()) { - emitReplayWarning(queueSize); - } else if (event.getLogger().isDelegateNOP()) { - // nothing to do - } else { - emitSubstitutionWarning(); - } - } - - private static void replaySingleEvent(SubstituteLoggingEvent event) { - if (event == null) - return; - - SubstituteLogger substLogger = event.getLogger(); - String loggerName = substLogger.getName(); - if (substLogger.isDelegateNull()) { - throw new IllegalStateException("Delegate logger cannot be null at this state."); - } - - if (substLogger.isDelegateNOP()) { - // nothing to do - } else if (substLogger.isDelegateEventAware()) { - substLogger.log(event); - } else { - Util.report(loggerName); - } - } - - private static void emitSubstitutionWarning() { - Util.report("The following set of substitute loggers may have been accessed"); - Util.report("during the initialization phase. Logging calls during this"); - Util.report("phase were not honored. However, subsequent logging calls to these"); - Util.report("loggers will work as normally expected."); - Util.report("See also " + SUBSTITUTE_LOGGER_URL); - } - - private static void emitReplayWarning(int eventCount) { - Util.report("A number (" + eventCount + ") of logging calls during the initialization phase have been intercepted and are"); - Util.report("now being replayed. These are subject to the filtering rules of the underlying logging system."); - Util.report("See also " + REPLAY_URL); - } - - private final static void versionSanityCheck() { - try { - String requested = StaticLoggerBinder.REQUESTED_API_VERSION; - - boolean match = false; - for (String aAPI_COMPATIBILITY_LIST : API_COMPATIBILITY_LIST) { - if (requested.startsWith(aAPI_COMPATIBILITY_LIST)) { - match = true; - } - } - if (!match) { - Util.report("The requested version " + requested + " by your slf4j binding is not compatible with " - + Arrays.asList(API_COMPATIBILITY_LIST).toString()); - Util.report("See " + VERSION_MISMATCH + " for further details."); - } - } catch (java.lang.NoSuchFieldError nsfe) { - // given our large user base and SLF4J's commitment to backward - // compatibility, we cannot cry here. Only for implementations - // which willingly declare a REQUESTED_API_VERSION field do we - // emit compatibility warnings. - } catch (Throwable e) { - // we should never reach here - Util.report("Unexpected problem occured during version sanity check", e); - } - } - - // We need to use the name of the StaticLoggerBinder class, but we can't - // reference - // the class itself. - private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class"; - - static Set findPossibleStaticLoggerBinderPathSet() { - // use Set instead of list in order to deal with bug #138 - // LinkedHashSet appropriate here because it preserves insertion order - // during iteration - Set staticLoggerBinderPathSet = new LinkedHashSet(); - try { - ClassLoader loggerFactoryClassLoader = LoggerFactory.class.getClassLoader(); - Enumeration paths; - if (loggerFactoryClassLoader == null) { - paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH); - } else { - paths = loggerFactoryClassLoader.getResources(STATIC_LOGGER_BINDER_PATH); - } - while (paths.hasMoreElements()) { - URL path = paths.nextElement(); - staticLoggerBinderPathSet.add(path); - } - } catch (IOException ioe) { - Util.report("Error getting resources from path", ioe); - } - return staticLoggerBinderPathSet; - } - - private static boolean isAmbiguousStaticLoggerBinderPathSet(Set binderPathSet) { - return binderPathSet.size() > 1; - } - - /** - * Prints a warning message on the console if multiple bindings were found - * on the class path. No reporting is done otherwise. - * - */ - private static void reportMultipleBindingAmbiguity(Set binderPathSet) { - if (isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) { - Util.report("Class path contains multiple SLF4J bindings."); - for (URL path : binderPathSet) { - Util.report("Found binding in [" + path + "]"); - } - Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation."); - } - } - - private static boolean isAndroid() { - String vendor = Util.safeGetSystemProperty(JAVA_VENDOR_PROPERTY); - if (vendor == null) - return false; - return vendor.toLowerCase().contains("android"); - } - - private static void reportActualBinding(Set binderPathSet) { - // binderPathSet can be null under Android - if (binderPathSet != null && isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) { - Util.report("Actual binding is of type [" + StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr() + "]"); - } - } - - /** - * Return a logger named according to the name parameter using the - * statically bound {@link ILoggerFactory} instance. - * - * @param name - * The name of the logger. - * @return logger - */ - public static Logger getLogger(String name) { - ILoggerFactory iLoggerFactory = getILoggerFactory(); - return iLoggerFactory.getLogger(name); - } - - /** - * Return a logger named corresponding to the class passed as parameter, - * using the statically bound {@link ILoggerFactory} instance. - * - *

- * In case the the clazz parameter differs from the name of the - * caller as computed internally by SLF4J, a logger name mismatch warning - * will be printed but only if the - * slf4j.detectLoggerNameMismatch system property is set to - * true. By default, this property is not set and no warnings will be - * printed even in case of a logger name mismatch. - * - * @param clazz - * the returned logger will be named after clazz - * @return logger - * - * - * @see Detected - * logger name mismatch - */ - public static Logger getLogger(Class clazz) { - Logger logger = getLogger(clazz.getName()); - if (DETECT_LOGGER_NAME_MISMATCH) { - Class autoComputedCallingClass = Util.getCallingClass(); - if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) { - Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(), - autoComputedCallingClass.getName())); - Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation"); - } - } - return logger; - } - - private static boolean nonMatchingClasses(Class clazz, Class autoComputedCallingClass) { - return !autoComputedCallingClass.isAssignableFrom(clazz); - } - - /** - * Return the {@link ILoggerFactory} instance in use. - *

- *

- * ILoggerFactory instance is bound with this class at compile time. - * - * @return the ILoggerFactory instance in use - */ - public static ILoggerFactory getILoggerFactory() { - if (INITIALIZATION_STATE == UNINITIALIZED) { - synchronized (LoggerFactory.class) { - if (INITIALIZATION_STATE == UNINITIALIZED) { - INITIALIZATION_STATE = ONGOING_INITIALIZATION; - performInitialization(); - } - } - } - switch (INITIALIZATION_STATE) { - case SUCCESSFUL_INITIALIZATION: - return StaticLoggerBinder.getSingleton().getLoggerFactory(); - case NOP_FALLBACK_INITIALIZATION: - return NOP_FALLBACK_FACTORY; - case FAILED_INITIALIZATION: - throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG); - case ONGOING_INITIALIZATION: - // support re-entrant behavior. - // See also http://jira.qos.ch/browse/SLF4J-97 - return SUBST_FACTORY; - } - throw new IllegalStateException("Unreachable code"); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.LinkedBlockingQueue; + +import org.slf4j.event.SubstituteLoggingEvent; +import org.slf4j.helpers.NOPLoggerFactory; +import org.slf4j.helpers.SubstituteLogger; +import org.slf4j.helpers.SubstituteLoggerFactory; +import org.slf4j.helpers.Util; +import org.slf4j.impl.StaticLoggerBinder; + +/** + * The LoggerFactory is a utility class producing Loggers for + * various logging APIs, most notably for log4j, logback and JDK 1.4 logging. + * Other implementations such as {@link org.slf4j.impl.NOPLogger NOPLogger} and + * {@link org.slf4j.impl.SimpleLogger SimpleLogger} are also supported. + *

+ *

+ * LoggerFactory is essentially a wrapper around an + * {@link ILoggerFactory} instance bound with LoggerFactory at + * compile time. + *

+ *

+ * Please note that all methods in LoggerFactory are static. + * + * + * @author Alexander Dorokhine + * @author Robert Elliot + * @author Ceki Gülcü + * + */ +public final class LoggerFactory { + + static final String CODES_PREFIX = "http://www.slf4j.org/codes.html"; + + static final String NO_STATICLOGGERBINDER_URL = CODES_PREFIX + "#StaticLoggerBinder"; + static final String MULTIPLE_BINDINGS_URL = CODES_PREFIX + "#multiple_bindings"; + static final String NULL_LF_URL = CODES_PREFIX + "#null_LF"; + static final String VERSION_MISMATCH = CODES_PREFIX + "#version_mismatch"; + static final String SUBSTITUTE_LOGGER_URL = CODES_PREFIX + "#substituteLogger"; + static final String LOGGER_NAME_MISMATCH_URL = CODES_PREFIX + "#loggerNameMismatch"; + static final String REPLAY_URL = CODES_PREFIX + "#replay"; + + static final String UNSUCCESSFUL_INIT_URL = CODES_PREFIX + "#unsuccessfulInit"; + static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory in failed state. Original exception was thrown EARLIER. See also " + UNSUCCESSFUL_INIT_URL; + + static final int UNINITIALIZED = 0; + static final int ONGOING_INITIALIZATION = 1; + static final int FAILED_INITIALIZATION = 2; + static final int SUCCESSFUL_INITIALIZATION = 3; + static final int NOP_FALLBACK_INITIALIZATION = 4; + + static volatile int INITIALIZATION_STATE = UNINITIALIZED; + static final SubstituteLoggerFactory SUBST_FACTORY = new SubstituteLoggerFactory(); + static final NOPLoggerFactory NOP_FALLBACK_FACTORY = new NOPLoggerFactory(); + + // Support for detecting mismatched logger names. + static final String DETECT_LOGGER_NAME_MISMATCH_PROPERTY = "slf4j.detectLoggerNameMismatch"; + static final String JAVA_VENDOR_PROPERTY = "java.vendor.url"; + + static boolean DETECT_LOGGER_NAME_MISMATCH = Util.safeGetBooleanSystemProperty(DETECT_LOGGER_NAME_MISMATCH_PROPERTY); + + /** + * It is LoggerFactory's responsibility to track version changes and manage + * the compatibility list. + *

+ *

+ * It is assumed that all versions in the 1.6 are mutually compatible. + */ + static private final String[] API_COMPATIBILITY_LIST = new String[] { "1.6", "1.7" }; + + // private constructor prevents instantiation + private LoggerFactory() { + } + + /** + * Force LoggerFactory to consider itself uninitialized. + *

+ *

+ * This method is intended to be called by classes (in the same package) for + * testing purposes. This method is internal. It can be modified, renamed or + * removed at any time without notice. + *

+ *

+ * You are strongly discouraged from calling this method in production code. + */ + static void reset() { + INITIALIZATION_STATE = UNINITIALIZED; + } + + private final static void performInitialization() { + bind(); + if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) { + versionSanityCheck(); + } + } + + private static boolean messageContainsOrgSlf4jImplStaticLoggerBinder(String msg) { + if (msg == null) + return false; + if (msg.contains("org/slf4j/impl/StaticLoggerBinder")) + return true; + if (msg.contains("org.slf4j.impl.StaticLoggerBinder")) + return true; + return false; + } + + private final static void bind() { + try { + Set staticLoggerBinderPathSet = null; + // skip check under android, see also + // http://jira.qos.ch/browse/SLF4J-328 + if (!isAndroid()) { + staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet(); + reportMultipleBindingAmbiguity(staticLoggerBinderPathSet); + } + // the next line does the binding + StaticLoggerBinder.getSingleton(); + INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION; + reportActualBinding(staticLoggerBinderPathSet); + fixSubstituteLoggers(); + replayEvents(); + // release all resources in SUBST_FACTORY + SUBST_FACTORY.clear(); + } catch (NoClassDefFoundError ncde) { + String msg = ncde.getMessage(); + if (messageContainsOrgSlf4jImplStaticLoggerBinder(msg)) { + INITIALIZATION_STATE = NOP_FALLBACK_INITIALIZATION; + Util.report("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\"."); + Util.report("Defaulting to no-operation (NOP) logger implementation"); + Util.report("See " + NO_STATICLOGGERBINDER_URL + " for further details."); + } else { + failedBinding(ncde); + throw ncde; + } + } catch (java.lang.NoSuchMethodError nsme) { + String msg = nsme.getMessage(); + if (msg != null && msg.contains("org.slf4j.impl.StaticLoggerBinder.getSingleton()")) { + INITIALIZATION_STATE = FAILED_INITIALIZATION; + Util.report("slf4j-api 1.6.x (or later) is incompatible with this binding."); + Util.report("Your binding is version 1.5.5 or earlier."); + Util.report("Upgrade your binding to version 1.6.x."); + } + throw nsme; + } catch (Exception e) { + failedBinding(e); + throw new IllegalStateException("Unexpected initialization failure", e); + } + } + + private static void fixSubstituteLoggers() { + synchronized (SUBST_FACTORY) { + SUBST_FACTORY.postInitialization(); + for (SubstituteLogger substLogger : SUBST_FACTORY.getLoggers()) { + Logger logger = getLogger(substLogger.getName()); + substLogger.setDelegate(logger); + } + } + + } + + static void failedBinding(Throwable t) { + INITIALIZATION_STATE = FAILED_INITIALIZATION; + Util.report("Failed to instantiate SLF4J LoggerFactory", t); + } + + private static void replayEvents() { + final LinkedBlockingQueue queue = SUBST_FACTORY.getEventQueue(); + final int queueSize = queue.size(); + int count = 0; + final int maxDrain = 128; + List eventList = new ArrayList(maxDrain); + while (true) { + int numDrained = queue.drainTo(eventList, maxDrain); + if (numDrained == 0) + break; + for (SubstituteLoggingEvent event : eventList) { + replaySingleEvent(event); + if (count++ == 0) + emitReplayOrSubstituionWarning(event, queueSize); + } + eventList.clear(); + } + } + + private static void emitReplayOrSubstituionWarning(SubstituteLoggingEvent event, int queueSize) { + if (event.getLogger().isDelegateEventAware()) { + emitReplayWarning(queueSize); + } else if (event.getLogger().isDelegateNOP()) { + // nothing to do + } else { + emitSubstitutionWarning(); + } + } + + private static void replaySingleEvent(SubstituteLoggingEvent event) { + if (event == null) + return; + + SubstituteLogger substLogger = event.getLogger(); + String loggerName = substLogger.getName(); + if (substLogger.isDelegateNull()) { + throw new IllegalStateException("Delegate logger cannot be null at this state."); + } + + if (substLogger.isDelegateNOP()) { + // nothing to do + } else if (substLogger.isDelegateEventAware()) { + substLogger.log(event); + } else { + Util.report(loggerName); + } + } + + private static void emitSubstitutionWarning() { + Util.report("The following set of substitute loggers may have been accessed"); + Util.report("during the initialization phase. Logging calls during this"); + Util.report("phase were not honored. However, subsequent logging calls to these"); + Util.report("loggers will work as normally expected."); + Util.report("See also " + SUBSTITUTE_LOGGER_URL); + } + + private static void emitReplayWarning(int eventCount) { + Util.report("A number (" + eventCount + ") of logging calls during the initialization phase have been intercepted and are"); + Util.report("now being replayed. These are subject to the filtering rules of the underlying logging system."); + Util.report("See also " + REPLAY_URL); + } + + private final static void versionSanityCheck() { + try { + String requested = StaticLoggerBinder.REQUESTED_API_VERSION; + + boolean match = false; + for (String aAPI_COMPATIBILITY_LIST : API_COMPATIBILITY_LIST) { + if (requested.startsWith(aAPI_COMPATIBILITY_LIST)) { + match = true; + } + } + if (!match) { + Util.report("The requested version " + requested + " by your slf4j binding is not compatible with " + + Arrays.asList(API_COMPATIBILITY_LIST).toString()); + Util.report("See " + VERSION_MISMATCH + " for further details."); + } + } catch (java.lang.NoSuchFieldError nsfe) { + // given our large user base and SLF4J's commitment to backward + // compatibility, we cannot cry here. Only for implementations + // which willingly declare a REQUESTED_API_VERSION field do we + // emit compatibility warnings. + } catch (Throwable e) { + // we should never reach here + Util.report("Unexpected problem occured during version sanity check", e); + } + } + + // We need to use the name of the StaticLoggerBinder class, but we can't + // reference + // the class itself. + private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class"; + + static Set findPossibleStaticLoggerBinderPathSet() { + // use Set instead of list in order to deal with bug #138 + // LinkedHashSet appropriate here because it preserves insertion order + // during iteration + Set staticLoggerBinderPathSet = new LinkedHashSet(); + try { + ClassLoader loggerFactoryClassLoader = LoggerFactory.class.getClassLoader(); + Enumeration paths; + if (loggerFactoryClassLoader == null) { + paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH); + } else { + paths = loggerFactoryClassLoader.getResources(STATIC_LOGGER_BINDER_PATH); + } + while (paths.hasMoreElements()) { + URL path = paths.nextElement(); + staticLoggerBinderPathSet.add(path); + } + } catch (IOException ioe) { + Util.report("Error getting resources from path", ioe); + } + return staticLoggerBinderPathSet; + } + + private static boolean isAmbiguousStaticLoggerBinderPathSet(Set binderPathSet) { + return binderPathSet.size() > 1; + } + + /** + * Prints a warning message on the console if multiple bindings were found + * on the class path. No reporting is done otherwise. + * + */ + private static void reportMultipleBindingAmbiguity(Set binderPathSet) { + if (isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) { + Util.report("Class path contains multiple SLF4J bindings."); + for (URL path : binderPathSet) { + Util.report("Found binding in [" + path + "]"); + } + Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation."); + } + } + + private static boolean isAndroid() { + String vendor = Util.safeGetSystemProperty(JAVA_VENDOR_PROPERTY); + if (vendor == null) + return false; + return vendor.toLowerCase().contains("android"); + } + + private static void reportActualBinding(Set binderPathSet) { + // binderPathSet can be null under Android + if (binderPathSet != null && isAmbiguousStaticLoggerBinderPathSet(binderPathSet)) { + Util.report("Actual binding is of type [" + StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr() + "]"); + } + } + + /** + * Return a logger named according to the name parameter using the + * statically bound {@link ILoggerFactory} instance. + * + * @param name + * The name of the logger. + * @return logger + */ + public static Logger getLogger(String name) { + ILoggerFactory iLoggerFactory = getILoggerFactory(); + return iLoggerFactory.getLogger(name); + } + + /** + * Return a logger named corresponding to the class passed as parameter, + * using the statically bound {@link ILoggerFactory} instance. + * + *

+ * In case the the clazz parameter differs from the name of the + * caller as computed internally by SLF4J, a logger name mismatch warning + * will be printed but only if the + * slf4j.detectLoggerNameMismatch system property is set to + * true. By default, this property is not set and no warnings will be + * printed even in case of a logger name mismatch. + * + * @param clazz + * the returned logger will be named after clazz + * @return logger + * + * + * @see Detected + * logger name mismatch + */ + public static Logger getLogger(Class clazz) { + Logger logger = getLogger(clazz.getName()); + if (DETECT_LOGGER_NAME_MISMATCH) { + Class autoComputedCallingClass = Util.getCallingClass(); + if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) { + Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(), + autoComputedCallingClass.getName())); + Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation"); + } + } + return logger; + } + + private static boolean nonMatchingClasses(Class clazz, Class autoComputedCallingClass) { + return !autoComputedCallingClass.isAssignableFrom(clazz); + } + + /** + * Return the {@link ILoggerFactory} instance in use. + *

+ *

+ * ILoggerFactory instance is bound with this class at compile time. + * + * @return the ILoggerFactory instance in use + */ + public static ILoggerFactory getILoggerFactory() { + if (INITIALIZATION_STATE == UNINITIALIZED) { + synchronized (LoggerFactory.class) { + if (INITIALIZATION_STATE == UNINITIALIZED) { + INITIALIZATION_STATE = ONGOING_INITIALIZATION; + performInitialization(); + } + } + } + switch (INITIALIZATION_STATE) { + case SUCCESSFUL_INITIALIZATION: + return StaticLoggerBinder.getSingleton().getLoggerFactory(); + case NOP_FALLBACK_INITIALIZATION: + return NOP_FALLBACK_FACTORY; + case FAILED_INITIALIZATION: + throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG); + case ONGOING_INITIALIZATION: + // support re-entrant behavior. + // See also http://jira.qos.ch/browse/SLF4J-97 + return SUBST_FACTORY; + } + throw new IllegalStateException("Unreachable code"); + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/MDC.java b/slf4j-api/src/main/java/org/slf4j/MDC.java index 3136f4d..71d761d 100644 --- a/slf4j-api/src/main/java/org/slf4j/MDC.java +++ b/slf4j-api/src/main/java/org/slf4j/MDC.java @@ -1,277 +1,277 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.io.Closeable; -import java.util.Map; - -import org.slf4j.helpers.NOPMDCAdapter; -import org.slf4j.helpers.BasicMDCAdapter; -import org.slf4j.helpers.Util; -import org.slf4j.impl.StaticMDCBinder; -import org.slf4j.spi.MDCAdapter; - -/** - * This class hides and serves as a substitute for the underlying logging - * system's MDC implementation. - * - *

- * If the underlying logging system offers MDC functionality, then SLF4J's MDC, - * i.e. this class, will delegate to the underlying system's MDC. Note that at - * this time, only two logging systems, namely log4j and logback, offer MDC - * functionality. For java.util.logging which does not support MDC, - * {@link BasicMDCAdapter} will be used. For other systems, i.e. slf4j-simple - * and slf4j-nop, {@link NOPMDCAdapter} will be used. - * - *

- * Thus, as a SLF4J user, you can take advantage of MDC in the presence of log4j, - * logback, or java.util.logging, but without forcing these systems as - * dependencies upon your users. - * - *

- * For more information on MDC please see the chapter on MDC in the - * logback manual. - * - *

- * Please note that all methods in this class are static. - * - * @author Ceki Gülcü - * @since 1.4.1 - */ -public class MDC { - - static final String NULL_MDCA_URL = "http://www.slf4j.org/codes.html#null_MDCA"; - static final String NO_STATIC_MDC_BINDER_URL = "http://www.slf4j.org/codes.html#no_static_mdc_binder"; - static MDCAdapter mdcAdapter; - - /** - * An adapter to remove the key when done. - */ - public static class MDCCloseable implements Closeable { - private final String key; - - private MDCCloseable(String key) { - this.key = key; - } - - public void close() { - MDC.remove(this.key); - } - } - - private MDC() { - } - - /** - * As of SLF4J version 1.7.14, StaticMDCBinder classes shipping in various bindings - * come with a getSingleton() method. Previously only a public field called SINGLETON - * was available. - * - * @return MDCAdapter - * @throws NoClassDefFoundError in case no binding is available - * @since 1.7.14 - */ - private static MDCAdapter bwCompatibleGetMDCAdapterFromBinder() throws NoClassDefFoundError { - try { - return StaticMDCBinder.getSingleton().getMDCA(); - } catch (NoSuchMethodError nsme) { - // binding is probably a version of SLF4J older than 1.7.14 - return StaticMDCBinder.SINGLETON.getMDCA(); - } - } - - static { - try { - mdcAdapter = bwCompatibleGetMDCAdapterFromBinder(); - } catch (NoClassDefFoundError ncde) { - mdcAdapter = new NOPMDCAdapter(); - String msg = ncde.getMessage(); - if (msg != null && msg.contains("StaticMDCBinder")) { - Util.report("Failed to load class \"org.slf4j.impl.StaticMDCBinder\"."); - Util.report("Defaulting to no-operation MDCAdapter implementation."); - Util.report("See " + NO_STATIC_MDC_BINDER_URL + " for further details."); - } else { - throw ncde; - } - } catch (Exception e) { - // we should never get here - Util.report("MDC binding unsuccessful.", e); - } - } - - /** - * Put a diagnostic context value (the val parameter) as identified with the - * key parameter into the current thread's diagnostic context map. The - * key parameter cannot be null. The val parameter - * can be null only if the underlying implementation supports it. - * - *

- * This method delegates all work to the MDC of the underlying logging system. - * - * @param key non-null key - * @param val value to put in the map - * - * @throws IllegalArgumentException - * in case the "key" parameter is null - */ - public static void put(String key, String val) throws IllegalArgumentException { - if (key == null) { - throw new IllegalArgumentException("key parameter cannot be null"); - } - if (mdcAdapter == null) { - throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); - } - mdcAdapter.put(key, val); - } - - /** - * Put a diagnostic context value (the val parameter) as identified with the - * key parameter into the current thread's diagnostic context map. The - * key parameter cannot be null. The val parameter - * can be null only if the underlying implementation supports it. - * - *

- * This method delegates all work to the MDC of the underlying logging system. - *

- * This method return a Closeable object who can remove key when - * close is called. - * - *

- * Useful with Java 7 for example : - * - * try(MDC.MDCCloseable closeable = MDC.putCloseable(key, value)) { - * .... - * } - * - * - * @param key non-null key - * @param val value to put in the map - * @return a Closeable who can remove key when close - * is called. - * - * @throws IllegalArgumentException - * in case the "key" parameter is null - */ - public static MDCCloseable putCloseable(String key, String val) throws IllegalArgumentException { - put(key, val); - return new MDCCloseable(key); - } - - /** - * Get the diagnostic context identified by the key parameter. The - * key parameter cannot be null. - * - *

- * This method delegates all work to the MDC of the underlying logging system. - * - * @param key - * @return the string value identified by the key parameter. - * @throws IllegalArgumentException - * in case the "key" parameter is null - */ - public static String get(String key) throws IllegalArgumentException { - if (key == null) { - throw new IllegalArgumentException("key parameter cannot be null"); - } - - if (mdcAdapter == null) { - throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); - } - return mdcAdapter.get(key); - } - - /** - * Remove the diagnostic context identified by the key parameter using - * the underlying system's MDC implementation. The key parameter - * cannot be null. This method does nothing if there is no previous value - * associated with key. - * - * @param key - * @throws IllegalArgumentException - * in case the "key" parameter is null - */ - public static void remove(String key) throws IllegalArgumentException { - if (key == null) { - throw new IllegalArgumentException("key parameter cannot be null"); - } - - if (mdcAdapter == null) { - throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); - } - mdcAdapter.remove(key); - } - - /** - * Clear all entries in the MDC of the underlying implementation. - */ - public static void clear() { - if (mdcAdapter == null) { - throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); - } - mdcAdapter.clear(); - } - - /** - * Return a copy of the current thread's context map, with keys and values of - * type String. Returned value may be null. - * - * @return A copy of the current thread's context map. May be null. - * @since 1.5.1 - */ - public static Map getCopyOfContextMap() { - if (mdcAdapter == null) { - throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); - } - return mdcAdapter.getCopyOfContextMap(); - } - - /** - * Set the current thread's context map by first clearing any existing map and - * then copying the map passed as parameter. The context map passed as - * parameter must only contain keys and values of type String. - * - * @param contextMap - * must contain only keys and values of type String - * @since 1.5.1 - */ - public static void setContextMap(Map contextMap) { - if (mdcAdapter == null) { - throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); - } - mdcAdapter.setContextMap(contextMap); - } - - /** - * Returns the MDCAdapter instance currently in use. - * - * @return the MDcAdapter instance currently in use. - * @since 1.4.2 - */ - public static MDCAdapter getMDCAdapter() { - return mdcAdapter; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.io.Closeable; +import java.util.Map; + +import org.slf4j.helpers.NOPMDCAdapter; +import org.slf4j.helpers.BasicMDCAdapter; +import org.slf4j.helpers.Util; +import org.slf4j.impl.StaticMDCBinder; +import org.slf4j.spi.MDCAdapter; + +/** + * This class hides and serves as a substitute for the underlying logging + * system's MDC implementation. + * + *

+ * If the underlying logging system offers MDC functionality, then SLF4J's MDC, + * i.e. this class, will delegate to the underlying system's MDC. Note that at + * this time, only two logging systems, namely log4j and logback, offer MDC + * functionality. For java.util.logging which does not support MDC, + * {@link BasicMDCAdapter} will be used. For other systems, i.e. slf4j-simple + * and slf4j-nop, {@link NOPMDCAdapter} will be used. + * + *

+ * Thus, as a SLF4J user, you can take advantage of MDC in the presence of log4j, + * logback, or java.util.logging, but without forcing these systems as + * dependencies upon your users. + * + *

+ * For more information on MDC please see the chapter on MDC in the + * logback manual. + * + *

+ * Please note that all methods in this class are static. + * + * @author Ceki Gülcü + * @since 1.4.1 + */ +public class MDC { + + static final String NULL_MDCA_URL = "http://www.slf4j.org/codes.html#null_MDCA"; + static final String NO_STATIC_MDC_BINDER_URL = "http://www.slf4j.org/codes.html#no_static_mdc_binder"; + static MDCAdapter mdcAdapter; + + /** + * An adapter to remove the key when done. + */ + public static class MDCCloseable implements Closeable { + private final String key; + + private MDCCloseable(String key) { + this.key = key; + } + + public void close() { + MDC.remove(this.key); + } + } + + private MDC() { + } + + /** + * As of SLF4J version 1.7.14, StaticMDCBinder classes shipping in various bindings + * come with a getSingleton() method. Previously only a public field called SINGLETON + * was available. + * + * @return MDCAdapter + * @throws NoClassDefFoundError in case no binding is available + * @since 1.7.14 + */ + private static MDCAdapter bwCompatibleGetMDCAdapterFromBinder() throws NoClassDefFoundError { + try { + return StaticMDCBinder.getSingleton().getMDCA(); + } catch (NoSuchMethodError nsme) { + // binding is probably a version of SLF4J older than 1.7.14 + return StaticMDCBinder.SINGLETON.getMDCA(); + } + } + + static { + try { + mdcAdapter = bwCompatibleGetMDCAdapterFromBinder(); + } catch (NoClassDefFoundError ncde) { + mdcAdapter = new NOPMDCAdapter(); + String msg = ncde.getMessage(); + if (msg != null && msg.contains("StaticMDCBinder")) { + Util.report("Failed to load class \"org.slf4j.impl.StaticMDCBinder\"."); + Util.report("Defaulting to no-operation MDCAdapter implementation."); + Util.report("See " + NO_STATIC_MDC_BINDER_URL + " for further details."); + } else { + throw ncde; + } + } catch (Exception e) { + // we should never get here + Util.report("MDC binding unsuccessful.", e); + } + } + + /** + * Put a diagnostic context value (the val parameter) as identified with the + * key parameter into the current thread's diagnostic context map. The + * key parameter cannot be null. The val parameter + * can be null only if the underlying implementation supports it. + * + *

+ * This method delegates all work to the MDC of the underlying logging system. + * + * @param key non-null key + * @param val value to put in the map + * + * @throws IllegalArgumentException + * in case the "key" parameter is null + */ + public static void put(String key, String val) throws IllegalArgumentException { + if (key == null) { + throw new IllegalArgumentException("key parameter cannot be null"); + } + if (mdcAdapter == null) { + throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); + } + mdcAdapter.put(key, val); + } + + /** + * Put a diagnostic context value (the val parameter) as identified with the + * key parameter into the current thread's diagnostic context map. The + * key parameter cannot be null. The val parameter + * can be null only if the underlying implementation supports it. + * + *

+ * This method delegates all work to the MDC of the underlying logging system. + *

+ * This method return a Closeable object who can remove key when + * close is called. + * + *

+ * Useful with Java 7 for example : + * + * try(MDC.MDCCloseable closeable = MDC.putCloseable(key, value)) { + * .... + * } + * + * + * @param key non-null key + * @param val value to put in the map + * @return a Closeable who can remove key when close + * is called. + * + * @throws IllegalArgumentException + * in case the "key" parameter is null + */ + public static MDCCloseable putCloseable(String key, String val) throws IllegalArgumentException { + put(key, val); + return new MDCCloseable(key); + } + + /** + * Get the diagnostic context identified by the key parameter. The + * key parameter cannot be null. + * + *

+ * This method delegates all work to the MDC of the underlying logging system. + * + * @param key + * @return the string value identified by the key parameter. + * @throws IllegalArgumentException + * in case the "key" parameter is null + */ + public static String get(String key) throws IllegalArgumentException { + if (key == null) { + throw new IllegalArgumentException("key parameter cannot be null"); + } + + if (mdcAdapter == null) { + throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); + } + return mdcAdapter.get(key); + } + + /** + * Remove the diagnostic context identified by the key parameter using + * the underlying system's MDC implementation. The key parameter + * cannot be null. This method does nothing if there is no previous value + * associated with key. + * + * @param key + * @throws IllegalArgumentException + * in case the "key" parameter is null + */ + public static void remove(String key) throws IllegalArgumentException { + if (key == null) { + throw new IllegalArgumentException("key parameter cannot be null"); + } + + if (mdcAdapter == null) { + throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); + } + mdcAdapter.remove(key); + } + + /** + * Clear all entries in the MDC of the underlying implementation. + */ + public static void clear() { + if (mdcAdapter == null) { + throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); + } + mdcAdapter.clear(); + } + + /** + * Return a copy of the current thread's context map, with keys and values of + * type String. Returned value may be null. + * + * @return A copy of the current thread's context map. May be null. + * @since 1.5.1 + */ + public static Map getCopyOfContextMap() { + if (mdcAdapter == null) { + throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); + } + return mdcAdapter.getCopyOfContextMap(); + } + + /** + * Set the current thread's context map by first clearing any existing map and + * then copying the map passed as parameter. The context map passed as + * parameter must only contain keys and values of type String. + * + * @param contextMap + * must contain only keys and values of type String + * @since 1.5.1 + */ + public static void setContextMap(Map contextMap) { + if (mdcAdapter == null) { + throw new IllegalStateException("MDCAdapter cannot be null. See also " + NULL_MDCA_URL); + } + mdcAdapter.setContextMap(contextMap); + } + + /** + * Returns the MDCAdapter instance currently in use. + * + * @return the MDcAdapter instance currently in use. + * @since 1.4.2 + */ + public static MDCAdapter getMDCAdapter() { + return mdcAdapter; + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/Marker.java b/slf4j-api/src/main/java/org/slf4j/Marker.java index a6bd514..c6bfd5e 100644 --- a/slf4j-api/src/main/java/org/slf4j/Marker.java +++ b/slf4j-api/src/main/java/org/slf4j/Marker.java @@ -1,142 +1,142 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.io.Serializable; -import java.util.Iterator; - -/** - * Markers are named objects used to enrich log statements. Conforming logging - * system Implementations of SLF4J determine how information conveyed by markers - * are used, if at all. In particular, many conforming logging systems ignore - * marker data. - * - *

- * Markers can contain references to other markers, which in turn may contain - * references of their own. - * - * @author Ceki Gülcü - */ -public interface Marker extends Serializable { - - /** - * This constant represents any marker, including a null marker. - */ - public final String ANY_MARKER = "*"; - - /** - * This constant represents any non-null marker. - */ - public final String ANY_NON_NULL_MARKER = "+"; - - /** - * Get the name of this Marker. - * - * @return name of marker - */ - public String getName(); - - /** - * Add a reference to another Marker. - * - * @param reference - * a reference to another marker - * @throws IllegalArgumentException - * if 'reference' is null - */ - public void add(Marker reference); - - /** - * Remove a marker reference. - * - * @param reference - * the marker reference to remove - * @return true if reference could be found and removed, false otherwise. - */ - public boolean remove(Marker reference); - - /** - * @deprecated Replaced by {@link #hasReferences()}. - */ - public boolean hasChildren(); - - /** - * Does this marker have any references? - * - * @return true if this marker has one or more references, false otherwise. - */ - public boolean hasReferences(); - - /** - * Returns an Iterator which can be used to iterate over the references of this - * marker. An empty iterator is returned when this marker has no references. - * - * @return Iterator over the references of this marker - */ - public Iterator iterator(); - - /** - * Does this marker contain a reference to the 'other' marker? Marker A is defined - * to contain marker B, if A == B or if B is referenced by A, or if B is referenced - * by any one of A's references (recursively). - * - * @param other - * The marker to test for inclusion. - * @throws IllegalArgumentException - * if 'other' is null - * @return Whether this marker contains the other marker. - */ - public boolean contains(Marker other); - - /** - * Does this marker contain the marker named 'name'? - * - * If 'name' is null the returned value is always false. - * - * @param name The marker name to test for inclusion. - * @return Whether this marker contains the other marker. - */ - public boolean contains(String name); - - /** - * Markers are considered equal if they have the same name. - * - * @param o - * @return true, if this.name equals o.name - * - * @since 1.5.1 - */ - public boolean equals(Object o); - - /** - * Compute the hash code based on the name of this marker. - * Note that markers are considered equal if they have the same name. - * - * @return the computed hashCode - * @since 1.5.1 - */ - public int hashCode(); - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.io.Serializable; +import java.util.Iterator; + +/** + * Markers are named objects used to enrich log statements. Conforming logging + * system Implementations of SLF4J determine how information conveyed by markers + * are used, if at all. In particular, many conforming logging systems ignore + * marker data. + * + *

+ * Markers can contain references to other markers, which in turn may contain + * references of their own. + * + * @author Ceki Gülcü + */ +public interface Marker extends Serializable { + + /** + * This constant represents any marker, including a null marker. + */ + public final String ANY_MARKER = "*"; + + /** + * This constant represents any non-null marker. + */ + public final String ANY_NON_NULL_MARKER = "+"; + + /** + * Get the name of this Marker. + * + * @return name of marker + */ + public String getName(); + + /** + * Add a reference to another Marker. + * + * @param reference + * a reference to another marker + * @throws IllegalArgumentException + * if 'reference' is null + */ + public void add(Marker reference); + + /** + * Remove a marker reference. + * + * @param reference + * the marker reference to remove + * @return true if reference could be found and removed, false otherwise. + */ + public boolean remove(Marker reference); + + /** + * @deprecated Replaced by {@link #hasReferences()}. + */ + public boolean hasChildren(); + + /** + * Does this marker have any references? + * + * @return true if this marker has one or more references, false otherwise. + */ + public boolean hasReferences(); + + /** + * Returns an Iterator which can be used to iterate over the references of this + * marker. An empty iterator is returned when this marker has no references. + * + * @return Iterator over the references of this marker + */ + public Iterator iterator(); + + /** + * Does this marker contain a reference to the 'other' marker? Marker A is defined + * to contain marker B, if A == B or if B is referenced by A, or if B is referenced + * by any one of A's references (recursively). + * + * @param other + * The marker to test for inclusion. + * @throws IllegalArgumentException + * if 'other' is null + * @return Whether this marker contains the other marker. + */ + public boolean contains(Marker other); + + /** + * Does this marker contain the marker named 'name'? + * + * If 'name' is null the returned value is always false. + * + * @param name The marker name to test for inclusion. + * @return Whether this marker contains the other marker. + */ + public boolean contains(String name); + + /** + * Markers are considered equal if they have the same name. + * + * @param o + * @return true, if this.name equals o.name + * + * @since 1.5.1 + */ + public boolean equals(Object o); + + /** + * Compute the hash code based on the name of this marker. + * Note that markers are considered equal if they have the same name. + * + * @return the computed hashCode + * @since 1.5.1 + */ + public int hashCode(); + +} diff --git a/slf4j-api/src/main/java/org/slf4j/MarkerFactory.java b/slf4j-api/src/main/java/org/slf4j/MarkerFactory.java index 8c309a1..7eff41f 100644 --- a/slf4j-api/src/main/java/org/slf4j/MarkerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/MarkerFactory.java @@ -1,114 +1,114 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.helpers.Util; -import org.slf4j.impl.StaticMarkerBinder; - -/** - * MarkerFactory is a utility class producing {@link Marker} instances as - * appropriate for the logging system currently in use. - * - *

- * This class is essentially implemented as a wrapper around an - * {@link IMarkerFactory} instance bound at compile time. - * - *

- * Please note that all methods in this class are static. - * - * @author Ceki Gülcü - */ -public class MarkerFactory { - static IMarkerFactory MARKER_FACTORY; - - private MarkerFactory() { - } - - /** - * As of SLF4J version 1.7.14, StaticMarkerBinder classes shipping in various bindings - * come with a getSingleton() method. Previously only a public field called SINGLETON - * was available. - * - * @return IMarkerFactory - * @throws NoClassDefFoundError in case no binding is available - * @since 1.7.14 - */ - private static IMarkerFactory bwCompatibleGetMarkerFactoryFromBinder() throws NoClassDefFoundError { - try { - return StaticMarkerBinder.getSingleton().getMarkerFactory(); - } catch (NoSuchMethodError nsme) { - // binding is probably a version of SLF4J older than 1.7.14 - return StaticMarkerBinder.SINGLETON.getMarkerFactory(); - } - } - - // this is where the binding happens - static { - try { - MARKER_FACTORY = bwCompatibleGetMarkerFactoryFromBinder(); - } catch (NoClassDefFoundError e) { - MARKER_FACTORY = new BasicMarkerFactory(); - } catch (Exception e) { - // we should never get here - Util.report("Unexpected failure while binding MarkerFactory", e); - } - } - - /** - * Return a Marker instance as specified by the name parameter using the - * previously bound {@link IMarkerFactory}instance. - * - * @param name - * The name of the {@link Marker} object to return. - * @return marker - */ - public static Marker getMarker(String name) { - return MARKER_FACTORY.getMarker(name); - } - - /** - * Create a marker which is detached (even at birth) from the MarkerFactory. - * - * @param name the name of the marker - * @return a dangling marker - * @since 1.5.1 - */ - public static Marker getDetachedMarker(String name) { - return MARKER_FACTORY.getDetachedMarker(name); - } - - /** - * Return the {@link IMarkerFactory}instance in use. - * - *

The IMarkerFactory instance is usually bound with this class at - * compile time. - * - * @return the IMarkerFactory instance in use - */ - public static IMarkerFactory getIMarkerFactory() { - return MARKER_FACTORY; - } +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.helpers.Util; +import org.slf4j.impl.StaticMarkerBinder; + +/** + * MarkerFactory is a utility class producing {@link Marker} instances as + * appropriate for the logging system currently in use. + * + *

+ * This class is essentially implemented as a wrapper around an + * {@link IMarkerFactory} instance bound at compile time. + * + *

+ * Please note that all methods in this class are static. + * + * @author Ceki Gülcü + */ +public class MarkerFactory { + static IMarkerFactory MARKER_FACTORY; + + private MarkerFactory() { + } + + /** + * As of SLF4J version 1.7.14, StaticMarkerBinder classes shipping in various bindings + * come with a getSingleton() method. Previously only a public field called SINGLETON + * was available. + * + * @return IMarkerFactory + * @throws NoClassDefFoundError in case no binding is available + * @since 1.7.14 + */ + private static IMarkerFactory bwCompatibleGetMarkerFactoryFromBinder() throws NoClassDefFoundError { + try { + return StaticMarkerBinder.getSingleton().getMarkerFactory(); + } catch (NoSuchMethodError nsme) { + // binding is probably a version of SLF4J older than 1.7.14 + return StaticMarkerBinder.SINGLETON.getMarkerFactory(); + } + } + + // this is where the binding happens + static { + try { + MARKER_FACTORY = bwCompatibleGetMarkerFactoryFromBinder(); + } catch (NoClassDefFoundError e) { + MARKER_FACTORY = new BasicMarkerFactory(); + } catch (Exception e) { + // we should never get here + Util.report("Unexpected failure while binding MarkerFactory", e); + } + } + + /** + * Return a Marker instance as specified by the name parameter using the + * previously bound {@link IMarkerFactory}instance. + * + * @param name + * The name of the {@link Marker} object to return. + * @return marker + */ + public static Marker getMarker(String name) { + return MARKER_FACTORY.getMarker(name); + } + + /** + * Create a marker which is detached (even at birth) from the MarkerFactory. + * + * @param name the name of the marker + * @return a dangling marker + * @since 1.5.1 + */ + public static Marker getDetachedMarker(String name) { + return MARKER_FACTORY.getDetachedMarker(name); + } + + /** + * Return the {@link IMarkerFactory}instance in use. + * + *

The IMarkerFactory instance is usually bound with this class at + * compile time. + * + * @return the IMarkerFactory instance in use + */ + public static IMarkerFactory getIMarkerFactory() { + return MARKER_FACTORY; + } }diff --git a/slf4j-api/src/main/java/org/slf4j/event/EventConstants.java b/slf4j-api/src/main/java/org/slf4j/event/EventConstants.java old file mode 100644 new file mode 100755 index 8a7e733..00975da 100755 --- a/slf4j-api/src/main/java/org/slf4j/event/EventConstants.java +++ b/slf4j-api/src/main/java/org/slf4j/event/EventConstants.java @@ -1,13 +1,13 @@ -package org.slf4j.event; - -import org.slf4j.spi.LocationAwareLogger; - -public class EventConstants { - public static final int ERROR_INT = LocationAwareLogger.ERROR_INT; - public static final int WARN_INT = LocationAwareLogger.WARN_INT; - public static final int INFO_INT = LocationAwareLogger.INFO_INT; - public static final int DEBUG_INT = LocationAwareLogger.DEBUG_INT; - public static final int TRACE_INT = LocationAwareLogger.TRACE_INT; - public static final String NA_SUBST = "NA/SubstituteLogger"; - -} +package org.slf4j.event; + +import org.slf4j.spi.LocationAwareLogger; + +public class EventConstants { + public static final int ERROR_INT = LocationAwareLogger.ERROR_INT; + public static final int WARN_INT = LocationAwareLogger.WARN_INT; + public static final int INFO_INT = LocationAwareLogger.INFO_INT; + public static final int DEBUG_INT = LocationAwareLogger.DEBUG_INT; + public static final int TRACE_INT = LocationAwareLogger.TRACE_INT; + public static final String NA_SUBST = "NA/SubstituteLogger"; + +} diff --git a/slf4j-api/src/main/java/org/slf4j/event/EventRecodingLogger.java b/slf4j-api/src/main/java/org/slf4j/event/EventRecodingLogger.java old file mode 100644 new file mode 100755 index 112dc33..b43a32d 100755 --- a/slf4j-api/src/main/java/org/slf4j/event/EventRecodingLogger.java +++ b/slf4j-api/src/main/java/org/slf4j/event/EventRecodingLogger.java @@ -1,296 +1,296 @@ -package org.slf4j.event; - -import java.util.Queue; - -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.helpers.SubstituteLogger; - -public class EventRecodingLogger implements Logger { - - String name; - SubstituteLogger logger; - Queue eventQueue; - - public EventRecodingLogger(SubstituteLogger logger, Queue eventQueue) { - this.logger = logger; - this.name = logger.getName(); - this.eventQueue = eventQueue; - } - - public String getName() { - return name; - } - - private void recordEvent(Level level, String msg, Object[] args, Throwable throwable) { - recordEvent(level, null, msg, args, throwable); - } - - private void recordEvent(Level level, Marker marker, String msg, Object[] args, Throwable throwable) { - // System.out.println("recording logger:"+name+", msg:"+msg); - SubstituteLoggingEvent loggingEvent = new SubstituteLoggingEvent(); - loggingEvent.setTimeStamp(System.currentTimeMillis()); - loggingEvent.setLevel(level); - loggingEvent.setLogger(logger); - loggingEvent.setLoggerName(name); - loggingEvent.setMarker(marker); - loggingEvent.setMessage(msg); - loggingEvent.setArgumentArray(args); - loggingEvent.setThrowable(throwable); - loggingEvent.setThreadName(Thread.currentThread().getName()); - eventQueue.add(loggingEvent); - } - - public boolean isTraceEnabled() { - return true; - } - - public void trace(String msg) { - recordEvent(Level.TRACE, msg, null, null); - } - - public void trace(String format, Object arg) { - recordEvent(Level.TRACE, format, new Object[] { arg }, null); - } - - public void trace(String format, Object arg1, Object arg2) { - recordEvent(Level.TRACE, format, new Object[] { arg1, arg2 }, null); - } - - public void trace(String format, Object... arguments) { - recordEvent(Level.TRACE, format, arguments, null); - } - - public void trace(String msg, Throwable t) { - recordEvent(Level.TRACE, msg, null, t); - } - - public boolean isTraceEnabled(Marker marker) { - return true; - } - - public void trace(Marker marker, String msg) { - recordEvent(Level.TRACE, marker, msg, null, null); - - } - - public void trace(Marker marker, String format, Object arg) { - recordEvent(Level.TRACE, marker, format, new Object[] { arg }, null); - } - - public void trace(Marker marker, String format, Object arg1, Object arg2) { - recordEvent(Level.TRACE, marker, format, new Object[] { arg1, arg2 }, null); - } - - public void trace(Marker marker, String format, Object... argArray) { - recordEvent(Level.TRACE, marker, format, argArray, null); - - } - - public void trace(Marker marker, String msg, Throwable t) { - recordEvent(Level.TRACE, marker, msg, null, t); - } - - public boolean isDebugEnabled() { - return true; - } - - public void debug(String msg) { - recordEvent(Level.TRACE, msg, null, null); - } - - public void debug(String format, Object arg) { - recordEvent(Level.DEBUG, format, new Object[] { arg }, null); - - } - - public void debug(String format, Object arg1, Object arg2) { - recordEvent(Level.DEBUG, format, new Object[] { arg1, arg2 }, null); - - } - - public void debug(String format, Object... arguments) { - recordEvent(Level.DEBUG, format, arguments, null); - } - - public void debug(String msg, Throwable t) { - recordEvent(Level.DEBUG, msg, null, t); - } - - public boolean isDebugEnabled(Marker marker) { - return true; - } - - public void debug(Marker marker, String msg) { - recordEvent(Level.DEBUG, marker, msg, null, null); - } - - public void debug(Marker marker, String format, Object arg) { - recordEvent(Level.DEBUG, marker, format, new Object[] { arg }, null); - } - - public void debug(Marker marker, String format, Object arg1, Object arg2) { - recordEvent(Level.DEBUG, marker, format, new Object[] { arg1, arg2 }, null); - } - - public void debug(Marker marker, String format, Object... arguments) { - recordEvent(Level.DEBUG, marker, format, arguments, null); - } - - public void debug(Marker marker, String msg, Throwable t) { - recordEvent(Level.DEBUG, marker, msg, null, t); - } - - public boolean isInfoEnabled() { - return true; - } - - public void info(String msg) { - recordEvent(Level.INFO, msg, null, null); - } - - public void info(String format, Object arg) { - recordEvent(Level.INFO, format, new Object[] { arg }, null); - } - - public void info(String format, Object arg1, Object arg2) { - recordEvent(Level.INFO, format, new Object[] { arg1, arg2 }, null); - } - - public void info(String format, Object... arguments) { - recordEvent(Level.INFO, format, arguments, null); - } - - public void info(String msg, Throwable t) { - recordEvent(Level.INFO, msg, null, t); - } - - public boolean isInfoEnabled(Marker marker) { - return true; - } - - public void info(Marker marker, String msg) { - recordEvent(Level.INFO, marker, msg, null, null); - } - - public void info(Marker marker, String format, Object arg) { - recordEvent(Level.INFO, marker, format, new Object[] { arg }, null); - } - - public void info(Marker marker, String format, Object arg1, Object arg2) { - recordEvent(Level.INFO, marker, format, new Object[] { arg1, arg2 }, null); - } - - public void info(Marker marker, String format, Object... arguments) { - recordEvent(Level.INFO, marker, format, arguments, null); - } - - public void info(Marker marker, String msg, Throwable t) { - recordEvent(Level.INFO, marker, msg, null, t); - - } - - public boolean isWarnEnabled() { - return true; - } - - public void warn(String msg) { - recordEvent(Level.WARN, msg, null, null); - } - - public void warn(String format, Object arg) { - recordEvent(Level.WARN, format, new Object[] { arg }, null); - - } - - public void warn(String format, Object arg1, Object arg2) { - recordEvent(Level.WARN, format, new Object[] { arg1, arg2 }, null); - } - - public void warn(String format, Object... arguments) { - recordEvent(Level.WARN, format, arguments, null); - } - - public void warn(String msg, Throwable t) { - recordEvent(Level.WARN, msg, null, t); - } - - public boolean isWarnEnabled(Marker marker) { - return true; - } - - public void warn(Marker marker, String msg) { - recordEvent(Level.WARN, msg, null, null); - } - - public void warn(Marker marker, String format, Object arg) { - recordEvent(Level.WARN, format, new Object[] { arg }, null); - } - - public void warn(Marker marker, String format, Object arg1, Object arg2) { - recordEvent(Level.WARN, marker, format, new Object[] { arg1, arg2 }, null); - - } - - public void warn(Marker marker, String format, Object... arguments) { - recordEvent(Level.WARN, marker, format, arguments, null); - } - - public void warn(Marker marker, String msg, Throwable t) { - recordEvent(Level.WARN, marker, msg, null, t); - } - - public boolean isErrorEnabled() { - return true; - } - - public void error(String msg) { - recordEvent(Level.ERROR, msg, null, null); - } - - public void error(String format, Object arg) { - recordEvent(Level.ERROR, format, new Object[] { arg }, null); - - } - - public void error(String format, Object arg1, Object arg2) { - recordEvent(Level.ERROR, format, new Object[] { arg1, arg2 }, null); - - } - - public void error(String format, Object... arguments) { - recordEvent(Level.ERROR, format, arguments, null); - - } - - public void error(String msg, Throwable t) { - recordEvent(Level.ERROR, msg, null, t); - } - - public boolean isErrorEnabled(Marker marker) { - return true; - } - - public void error(Marker marker, String msg) { - recordEvent(Level.ERROR, marker, msg, null, null); - - } - - public void error(Marker marker, String format, Object arg) { - recordEvent(Level.ERROR, marker, format, new Object[] { arg }, null); - - } - - public void error(Marker marker, String format, Object arg1, Object arg2) { - recordEvent(Level.ERROR, marker, format, new Object[] { arg1, arg2 }, null); - } - - public void error(Marker marker, String format, Object... arguments) { - recordEvent(Level.ERROR, marker, format, arguments, null); - } - - public void error(Marker marker, String msg, Throwable t) { - recordEvent(Level.ERROR, marker, msg, null, t); - } - -} +package org.slf4j.event; + +import java.util.Queue; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.helpers.SubstituteLogger; + +public class EventRecodingLogger implements Logger { + + String name; + SubstituteLogger logger; + Queue eventQueue; + + public EventRecodingLogger(SubstituteLogger logger, Queue eventQueue) { + this.logger = logger; + this.name = logger.getName(); + this.eventQueue = eventQueue; + } + + public String getName() { + return name; + } + + private void recordEvent(Level level, String msg, Object[] args, Throwable throwable) { + recordEvent(level, null, msg, args, throwable); + } + + private void recordEvent(Level level, Marker marker, String msg, Object[] args, Throwable throwable) { + // System.out.println("recording logger:"+name+", msg:"+msg); + SubstituteLoggingEvent loggingEvent = new SubstituteLoggingEvent(); + loggingEvent.setTimeStamp(System.currentTimeMillis()); + loggingEvent.setLevel(level); + loggingEvent.setLogger(logger); + loggingEvent.setLoggerName(name); + loggingEvent.setMarker(marker); + loggingEvent.setMessage(msg); + loggingEvent.setArgumentArray(args); + loggingEvent.setThrowable(throwable); + loggingEvent.setThreadName(Thread.currentThread().getName()); + eventQueue.add(loggingEvent); + } + + public boolean isTraceEnabled() { + return true; + } + + public void trace(String msg) { + recordEvent(Level.TRACE, msg, null, null); + } + + public void trace(String format, Object arg) { + recordEvent(Level.TRACE, format, new Object[] { arg }, null); + } + + public void trace(String format, Object arg1, Object arg2) { + recordEvent(Level.TRACE, format, new Object[] { arg1, arg2 }, null); + } + + public void trace(String format, Object... arguments) { + recordEvent(Level.TRACE, format, arguments, null); + } + + public void trace(String msg, Throwable t) { + recordEvent(Level.TRACE, msg, null, t); + } + + public boolean isTraceEnabled(Marker marker) { + return true; + } + + public void trace(Marker marker, String msg) { + recordEvent(Level.TRACE, marker, msg, null, null); + + } + + public void trace(Marker marker, String format, Object arg) { + recordEvent(Level.TRACE, marker, format, new Object[] { arg }, null); + } + + public void trace(Marker marker, String format, Object arg1, Object arg2) { + recordEvent(Level.TRACE, marker, format, new Object[] { arg1, arg2 }, null); + } + + public void trace(Marker marker, String format, Object... argArray) { + recordEvent(Level.TRACE, marker, format, argArray, null); + + } + + public void trace(Marker marker, String msg, Throwable t) { + recordEvent(Level.TRACE, marker, msg, null, t); + } + + public boolean isDebugEnabled() { + return true; + } + + public void debug(String msg) { + recordEvent(Level.TRACE, msg, null, null); + } + + public void debug(String format, Object arg) { + recordEvent(Level.DEBUG, format, new Object[] { arg }, null); + + } + + public void debug(String format, Object arg1, Object arg2) { + recordEvent(Level.DEBUG, format, new Object[] { arg1, arg2 }, null); + + } + + public void debug(String format, Object... arguments) { + recordEvent(Level.DEBUG, format, arguments, null); + } + + public void debug(String msg, Throwable t) { + recordEvent(Level.DEBUG, msg, null, t); + } + + public boolean isDebugEnabled(Marker marker) { + return true; + } + + public void debug(Marker marker, String msg) { + recordEvent(Level.DEBUG, marker, msg, null, null); + } + + public void debug(Marker marker, String format, Object arg) { + recordEvent(Level.DEBUG, marker, format, new Object[] { arg }, null); + } + + public void debug(Marker marker, String format, Object arg1, Object arg2) { + recordEvent(Level.DEBUG, marker, format, new Object[] { arg1, arg2 }, null); + } + + public void debug(Marker marker, String format, Object... arguments) { + recordEvent(Level.DEBUG, marker, format, arguments, null); + } + + public void debug(Marker marker, String msg, Throwable t) { + recordEvent(Level.DEBUG, marker, msg, null, t); + } + + public boolean isInfoEnabled() { + return true; + } + + public void info(String msg) { + recordEvent(Level.INFO, msg, null, null); + } + + public void info(String format, Object arg) { + recordEvent(Level.INFO, format, new Object[] { arg }, null); + } + + public void info(String format, Object arg1, Object arg2) { + recordEvent(Level.INFO, format, new Object[] { arg1, arg2 }, null); + } + + public void info(String format, Object... arguments) { + recordEvent(Level.INFO, format, arguments, null); + } + + public void info(String msg, Throwable t) { + recordEvent(Level.INFO, msg, null, t); + } + + public boolean isInfoEnabled(Marker marker) { + return true; + } + + public void info(Marker marker, String msg) { + recordEvent(Level.INFO, marker, msg, null, null); + } + + public void info(Marker marker, String format, Object arg) { + recordEvent(Level.INFO, marker, format, new Object[] { arg }, null); + } + + public void info(Marker marker, String format, Object arg1, Object arg2) { + recordEvent(Level.INFO, marker, format, new Object[] { arg1, arg2 }, null); + } + + public void info(Marker marker, String format, Object... arguments) { + recordEvent(Level.INFO, marker, format, arguments, null); + } + + public void info(Marker marker, String msg, Throwable t) { + recordEvent(Level.INFO, marker, msg, null, t); + + } + + public boolean isWarnEnabled() { + return true; + } + + public void warn(String msg) { + recordEvent(Level.WARN, msg, null, null); + } + + public void warn(String format, Object arg) { + recordEvent(Level.WARN, format, new Object[] { arg }, null); + + } + + public void warn(String format, Object arg1, Object arg2) { + recordEvent(Level.WARN, format, new Object[] { arg1, arg2 }, null); + } + + public void warn(String format, Object... arguments) { + recordEvent(Level.WARN, format, arguments, null); + } + + public void warn(String msg, Throwable t) { + recordEvent(Level.WARN, msg, null, t); + } + + public boolean isWarnEnabled(Marker marker) { + return true; + } + + public void warn(Marker marker, String msg) { + recordEvent(Level.WARN, msg, null, null); + } + + public void warn(Marker marker, String format, Object arg) { + recordEvent(Level.WARN, format, new Object[] { arg }, null); + } + + public void warn(Marker marker, String format, Object arg1, Object arg2) { + recordEvent(Level.WARN, marker, format, new Object[] { arg1, arg2 }, null); + + } + + public void warn(Marker marker, String format, Object... arguments) { + recordEvent(Level.WARN, marker, format, arguments, null); + } + + public void warn(Marker marker, String msg, Throwable t) { + recordEvent(Level.WARN, marker, msg, null, t); + } + + public boolean isErrorEnabled() { + return true; + } + + public void error(String msg) { + recordEvent(Level.ERROR, msg, null, null); + } + + public void error(String format, Object arg) { + recordEvent(Level.ERROR, format, new Object[] { arg }, null); + + } + + public void error(String format, Object arg1, Object arg2) { + recordEvent(Level.ERROR, format, new Object[] { arg1, arg2 }, null); + + } + + public void error(String format, Object... arguments) { + recordEvent(Level.ERROR, format, arguments, null); + + } + + public void error(String msg, Throwable t) { + recordEvent(Level.ERROR, msg, null, t); + } + + public boolean isErrorEnabled(Marker marker) { + return true; + } + + public void error(Marker marker, String msg) { + recordEvent(Level.ERROR, marker, msg, null, null); + + } + + public void error(Marker marker, String format, Object arg) { + recordEvent(Level.ERROR, marker, format, new Object[] { arg }, null); + + } + + public void error(Marker marker, String format, Object arg1, Object arg2) { + recordEvent(Level.ERROR, marker, format, new Object[] { arg1, arg2 }, null); + } + + public void error(Marker marker, String format, Object... arguments) { + recordEvent(Level.ERROR, marker, format, arguments, null); + } + + public void error(Marker marker, String msg, Throwable t) { + recordEvent(Level.ERROR, marker, msg, null, t); + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/event/Level.java b/slf4j-api/src/main/java/org/slf4j/event/Level.java old file mode 100644 new file mode 100755 index ee4146c..5d4031c 100755 --- a/slf4j-api/src/main/java/org/slf4j/event/Level.java +++ b/slf4j-api/src/main/java/org/slf4j/event/Level.java @@ -1,37 +1,37 @@ -package org.slf4j.event; - -import static org.slf4j.event.EventConstants.DEBUG_INT; -import static org.slf4j.event.EventConstants.ERROR_INT; -import static org.slf4j.event.EventConstants.INFO_INT; -import static org.slf4j.event.EventConstants.TRACE_INT; -import static org.slf4j.event.EventConstants.WARN_INT; - -/** - * - * @author ceki - * @since 1.7.15 - */ -public enum Level { - - ERROR(ERROR_INT, "ERROR"), WARN(WARN_INT, "WARN"), INFO(INFO_INT, "INFO"), DEBUG(DEBUG_INT, "DEBUG"), TRACE(TRACE_INT, "TRACE"); - - private int levelInt; - private String levelStr; - - Level(int i, String s) { - levelInt = i; - levelStr = s; - } - - public int toInt() { - return levelInt; - } - - /** - * Returns the string representation of this Level. - */ - public String toString() { - return levelStr; - } - -} +package org.slf4j.event; + +import static org.slf4j.event.EventConstants.DEBUG_INT; +import static org.slf4j.event.EventConstants.ERROR_INT; +import static org.slf4j.event.EventConstants.INFO_INT; +import static org.slf4j.event.EventConstants.TRACE_INT; +import static org.slf4j.event.EventConstants.WARN_INT; + +/** + * + * @author ceki + * @since 1.7.15 + */ +public enum Level { + + ERROR(ERROR_INT, "ERROR"), WARN(WARN_INT, "WARN"), INFO(INFO_INT, "INFO"), DEBUG(DEBUG_INT, "DEBUG"), TRACE(TRACE_INT, "TRACE"); + + private int levelInt; + private String levelStr; + + Level(int i, String s) { + levelInt = i; + levelStr = s; + } + + public int toInt() { + return levelInt; + } + + /** + * Returns the string representation of this Level. + */ + public String toString() { + return levelStr; + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/event/LoggingEvent.java b/slf4j-api/src/main/java/org/slf4j/event/LoggingEvent.java old file mode 100644 new file mode 100755 index d9eabed..1e26c2d 100755 --- a/slf4j-api/src/main/java/org/slf4j/event/LoggingEvent.java +++ b/slf4j-api/src/main/java/org/slf4j/event/LoggingEvent.java @@ -1,28 +1,28 @@ -package org.slf4j.event; - -import org.slf4j.Marker; - -/** - * - * @author ceki - * @since 1.7.15 - */ -public interface LoggingEvent { - - Level getLevel(); - - Marker getMarker(); - - String getLoggerName(); - - String getMessage(); - - String getThreadName(); - - Object[] getArgumentArray(); - - long getTimeStamp(); - - Throwable getThrowable(); - -} +package org.slf4j.event; + +import org.slf4j.Marker; + +/** + * + * @author ceki + * @since 1.7.15 + */ +public interface LoggingEvent { + + Level getLevel(); + + Marker getMarker(); + + String getLoggerName(); + + String getMessage(); + + String getThreadName(); + + Object[] getArgumentArray(); + + long getTimeStamp(); + + Throwable getThrowable(); + +} diff --git a/slf4j-api/src/main/java/org/slf4j/event/SubstituteLoggingEvent.java b/slf4j-api/src/main/java/org/slf4j/event/SubstituteLoggingEvent.java old file mode 100644 new file mode 100755 index d352c65..8c7acbc 100755 --- a/slf4j-api/src/main/java/org/slf4j/event/SubstituteLoggingEvent.java +++ b/slf4j-api/src/main/java/org/slf4j/event/SubstituteLoggingEvent.java @@ -1,89 +1,89 @@ -package org.slf4j.event; - -import org.slf4j.Marker; -import org.slf4j.helpers.SubstituteLogger; - -public class SubstituteLoggingEvent implements LoggingEvent { - - Level level; - Marker marker; - String loggerName; - SubstituteLogger logger; - String threadName; - String message; - Object[] argArray; - long timeStamp; - Throwable throwable; - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public Marker getMarker() { - return marker; - } - - public void setMarker(Marker marker) { - this.marker = marker; - } - - public String getLoggerName() { - return loggerName; - } - - public void setLoggerName(String loggerName) { - this.loggerName = loggerName; - } - - public SubstituteLogger getLogger() { - return logger; - } - - public void setLogger(SubstituteLogger logger) { - this.logger = logger; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Object[] getArgumentArray() { - return argArray; - } - - public void setArgumentArray(Object[] argArray) { - this.argArray = argArray; - } - - public long getTimeStamp() { - return timeStamp; - } - - public void setTimeStamp(long timeStamp) { - this.timeStamp = timeStamp; - } - - public String getThreadName() { - return threadName; - } - - public void setThreadName(String threadName) { - this.threadName = threadName; - } - - public Throwable getThrowable() { - return throwable; - } - - public void setThrowable(Throwable throwable) { - this.throwable = throwable; - } -} +package org.slf4j.event; + +import org.slf4j.Marker; +import org.slf4j.helpers.SubstituteLogger; + +public class SubstituteLoggingEvent implements LoggingEvent { + + Level level; + Marker marker; + String loggerName; + SubstituteLogger logger; + String threadName; + String message; + Object[] argArray; + long timeStamp; + Throwable throwable; + + public Level getLevel() { + return level; + } + + public void setLevel(Level level) { + this.level = level; + } + + public Marker getMarker() { + return marker; + } + + public void setMarker(Marker marker) { + this.marker = marker; + } + + public String getLoggerName() { + return loggerName; + } + + public void setLoggerName(String loggerName) { + this.loggerName = loggerName; + } + + public SubstituteLogger getLogger() { + return logger; + } + + public void setLogger(SubstituteLogger logger) { + this.logger = logger; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Object[] getArgumentArray() { + return argArray; + } + + public void setArgumentArray(Object[] argArray) { + this.argArray = argArray; + } + + public long getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(long timeStamp) { + this.timeStamp = timeStamp; + } + + public String getThreadName() { + return threadName; + } + + public void setThreadName(String threadName) { + this.threadName = threadName; + } + + public Throwable getThrowable() { + return throwable; + } + + public void setThrowable(Throwable throwable) { + this.throwable = throwable; + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMDCAdapter.java b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMDCAdapter.java index 2269f5c..027938d 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMDCAdapter.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMDCAdapter.java @@ -1,146 +1,146 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import org.slf4j.spi.MDCAdapter; - -import java.util.*; -import java.util.Map; - -/** - * Basic MDC implementation, which can be used with logging systems that lack - * out-of-the-box MDC support. - * - * This code was initially inspired by logback's LogbackMDCAdapter. However, - * LogbackMDCAdapter has evolved and is now considerably more sophisticated. - * - * @author Ceki Gulcu - * @author Maarten Bosteels - * @author Lukasz Cwik - * - * @since 1.5.0 - */ -public class BasicMDCAdapter implements MDCAdapter { - - private InheritableThreadLocal> inheritableThreadLocal = new InheritableThreadLocal>() { - @Override - protected Map childValue(Map parentValue) { - if (parentValue == null) { - return null; - } - return new HashMap(parentValue); - } - }; - - /** - * Put a context value (the val parameter) as identified with - * the key parameter into the current thread's context map. - * Note that contrary to log4j, the val parameter can be null. - * - *

- * If the current thread does not have a context map it is created as a side - * effect of this call. - * - * @throws IllegalArgumentException - * in case the "key" parameter is null - */ - public void put(String key, String val) { - if (key == null) { - throw new IllegalArgumentException("key cannot be null"); - } - Map map = inheritableThreadLocal.get(); - if (map == null) { - map = new HashMap(); - inheritableThreadLocal.set(map); - } - map.put(key, val); - } - - /** - * Get the context identified by the key parameter. - */ - public String get(String key) { - Map map = inheritableThreadLocal.get(); - if ((map != null) && (key != null)) { - return map.get(key); - } else { - return null; - } - } - - /** - * Remove the the context identified by the key parameter. - */ - public void remove(String key) { - Map map = inheritableThreadLocal.get(); - if (map != null) { - map.remove(key); - } - } - - /** - * Clear all entries in the MDC. - */ - public void clear() { - Map map = inheritableThreadLocal.get(); - if (map != null) { - map.clear(); - inheritableThreadLocal.remove(); - } - } - - /** - * Returns the keys in the MDC as a {@link Set} of {@link String}s The - * returned value can be null. - * - * @return the keys in the MDC - */ - public Set getKeys() { - Map map = inheritableThreadLocal.get(); - if (map != null) { - return map.keySet(); - } else { - return null; - } - } - - /** - * Return a copy of the current thread's context map. - * Returned value may be null. - * - */ - public Map getCopyOfContextMap() { - Map oldMap = inheritableThreadLocal.get(); - if (oldMap != null) { - return new HashMap(oldMap); - } else { - return null; - } - } - - public void setContextMap(Map contextMap) { - inheritableThreadLocal.set(new HashMap(contextMap)); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import org.slf4j.spi.MDCAdapter; + +import java.util.*; +import java.util.Map; + +/** + * Basic MDC implementation, which can be used with logging systems that lack + * out-of-the-box MDC support. + * + * This code was initially inspired by logback's LogbackMDCAdapter. However, + * LogbackMDCAdapter has evolved and is now considerably more sophisticated. + * + * @author Ceki Gulcu + * @author Maarten Bosteels + * @author Lukasz Cwik + * + * @since 1.5.0 + */ +public class BasicMDCAdapter implements MDCAdapter { + + private InheritableThreadLocal> inheritableThreadLocal = new InheritableThreadLocal>() { + @Override + protected Map childValue(Map parentValue) { + if (parentValue == null) { + return null; + } + return new HashMap(parentValue); + } + }; + + /** + * Put a context value (the val parameter) as identified with + * the key parameter into the current thread's context map. + * Note that contrary to log4j, the val parameter can be null. + * + *

+ * If the current thread does not have a context map it is created as a side + * effect of this call. + * + * @throws IllegalArgumentException + * in case the "key" parameter is null + */ + public void put(String key, String val) { + if (key == null) { + throw new IllegalArgumentException("key cannot be null"); + } + Map map = inheritableThreadLocal.get(); + if (map == null) { + map = new HashMap(); + inheritableThreadLocal.set(map); + } + map.put(key, val); + } + + /** + * Get the context identified by the key parameter. + */ + public String get(String key) { + Map map = inheritableThreadLocal.get(); + if ((map != null) && (key != null)) { + return map.get(key); + } else { + return null; + } + } + + /** + * Remove the the context identified by the key parameter. + */ + public void remove(String key) { + Map map = inheritableThreadLocal.get(); + if (map != null) { + map.remove(key); + } + } + + /** + * Clear all entries in the MDC. + */ + public void clear() { + Map map = inheritableThreadLocal.get(); + if (map != null) { + map.clear(); + inheritableThreadLocal.remove(); + } + } + + /** + * Returns the keys in the MDC as a {@link Set} of {@link String}s The + * returned value can be null. + * + * @return the keys in the MDC + */ + public Set getKeys() { + Map map = inheritableThreadLocal.get(); + if (map != null) { + return map.keySet(); + } else { + return null; + } + } + + /** + * Return a copy of the current thread's context map. + * Returned value may be null. + * + */ + public Map getCopyOfContextMap() { + Map oldMap = inheritableThreadLocal.get(); + if (oldMap != null) { + return new HashMap(oldMap); + } else { + return null; + } + } + + public void setContextMap(Map contextMap) { + inheritableThreadLocal.set(new HashMap(contextMap)); + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarker.java b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarker.java old file mode 100644 new file mode 100755 index bda9fd9..4daf640 100755 --- a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarker.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarker.java @@ -1,169 +1,169 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.slf4j.Marker; - -/** - * A simple implementation of the {@link Marker} interface. - * - * @author Ceki Gülcü - * @author Joern Huxhorn - */ -public class BasicMarker implements Marker { - - private static final long serialVersionUID = -2849567615646933777L; - private final String name; - private List referenceList = new CopyOnWriteArrayList(); - - BasicMarker(String name) { - if (name == null) { - throw new IllegalArgumentException("A marker name cannot be null"); - } - this.name = name; - } - - public String getName() { - return name; - } - - public void add(Marker reference) { - if (reference == null) { - throw new IllegalArgumentException("A null value cannot be added to a Marker as reference."); - } - - // no point in adding the reference multiple times - if (this.contains(reference)) { - return; - - } else if (reference.contains(this)) { // avoid recursion - // a potential reference should not hold its future "parent" as a reference - return; - } else { - referenceList.add(reference); - } - } - - public boolean hasReferences() { - return (referenceList.size() > 0); - } - - public boolean hasChildren() { - return hasReferences(); - } - - public Iterator iterator() { - return referenceList.iterator(); - } - - public boolean remove(Marker referenceToRemove) { - return referenceList.remove(referenceToRemove); - } - - public boolean contains(Marker other) { - if (other == null) { - throw new IllegalArgumentException("Other cannot be null"); - } - - if (this.equals(other)) { - return true; - } - - if (hasReferences()) { - for (Marker ref : referenceList) { - if (ref.contains(other)) { - return true; - } - } - } - return false; - } - - /** - * This method is mainly used with Expression Evaluators. - */ - public boolean contains(String name) { - if (name == null) { - throw new IllegalArgumentException("Other cannot be null"); - } - - if (this.name.equals(name)) { - return true; - } - - if (hasReferences()) { - for (Marker ref : referenceList) { - if (ref.contains(name)) { - return true; - } - } - } - return false; - } - - private static String OPEN = "[ "; - private static String CLOSE = " ]"; - private static String SEP = ", "; - - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof Marker)) - return false; - - final Marker other = (Marker) obj; - return name.equals(other.getName()); - } - - public int hashCode() { - return name.hashCode(); - } - - public String toString() { - if (!this.hasReferences()) { - return this.getName(); - } - Iterator it = this.iterator(); - Marker reference; - StringBuilder sb = new StringBuilder(this.getName()); - sb.append(' ').append(OPEN); - while (it.hasNext()) { - reference = it.next(); - sb.append(reference.getName()); - if (it.hasNext()) { - sb.append(SEP); - } - } - sb.append(CLOSE); - - return sb.toString(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.slf4j.Marker; + +/** + * A simple implementation of the {@link Marker} interface. + * + * @author Ceki Gülcü + * @author Joern Huxhorn + */ +public class BasicMarker implements Marker { + + private static final long serialVersionUID = -2849567615646933777L; + private final String name; + private List referenceList = new CopyOnWriteArrayList(); + + BasicMarker(String name) { + if (name == null) { + throw new IllegalArgumentException("A marker name cannot be null"); + } + this.name = name; + } + + public String getName() { + return name; + } + + public void add(Marker reference) { + if (reference == null) { + throw new IllegalArgumentException("A null value cannot be added to a Marker as reference."); + } + + // no point in adding the reference multiple times + if (this.contains(reference)) { + return; + + } else if (reference.contains(this)) { // avoid recursion + // a potential reference should not hold its future "parent" as a reference + return; + } else { + referenceList.add(reference); + } + } + + public boolean hasReferences() { + return (referenceList.size() > 0); + } + + public boolean hasChildren() { + return hasReferences(); + } + + public Iterator iterator() { + return referenceList.iterator(); + } + + public boolean remove(Marker referenceToRemove) { + return referenceList.remove(referenceToRemove); + } + + public boolean contains(Marker other) { + if (other == null) { + throw new IllegalArgumentException("Other cannot be null"); + } + + if (this.equals(other)) { + return true; + } + + if (hasReferences()) { + for (Marker ref : referenceList) { + if (ref.contains(other)) { + return true; + } + } + } + return false; + } + + /** + * This method is mainly used with Expression Evaluators. + */ + public boolean contains(String name) { + if (name == null) { + throw new IllegalArgumentException("Other cannot be null"); + } + + if (this.name.equals(name)) { + return true; + } + + if (hasReferences()) { + for (Marker ref : referenceList) { + if (ref.contains(name)) { + return true; + } + } + } + return false; + } + + private static String OPEN = "[ "; + private static String CLOSE = " ]"; + private static String SEP = ", "; + + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (!(obj instanceof Marker)) + return false; + + final Marker other = (Marker) obj; + return name.equals(other.getName()); + } + + public int hashCode() { + return name.hashCode(); + } + + public String toString() { + if (!this.hasReferences()) { + return this.getName(); + } + Iterator it = this.iterator(); + Marker reference; + StringBuilder sb = new StringBuilder(this.getName()); + sb.append(' ').append(OPEN); + while (it.hasNext()) { + reference = it.next(); + sb.append(reference.getName()); + if (it.hasNext()) { + sb.append(SEP); + } + } + sb.append(CLOSE); + + return sb.toString(); + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarkerFactory.java b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarkerFactory.java index 1d26047..5139bb6 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarkerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarkerFactory.java @@ -1,99 +1,99 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.slf4j.IMarkerFactory; -import org.slf4j.Marker; - -/** - * An almost trivial implementation of the {@link IMarkerFactory} - * interface which creates {@link BasicMarker} instances. - * - *

Simple logging systems can conform to the SLF4J API by binding - * {@link org.slf4j.MarkerFactory} with an instance of this class. - * - * @author Ceki Gülcü - */ -public class BasicMarkerFactory implements IMarkerFactory { - - private final ConcurrentMap markerMap = new ConcurrentHashMap(); - - /** - * Regular users should not create - * BasicMarkerFactory instances. Marker - * instances can be obtained using the static {@link - * org.slf4j.MarkerFactory#getMarker} method. - */ - public BasicMarkerFactory() { - } - - /** - * Manufacture a {@link BasicMarker} instance by name. If the instance has been - * created earlier, return the previously created instance. - * - * @param name the name of the marker to be created - * @return a Marker instance - */ - public Marker getMarker(String name) { - if (name == null) { - throw new IllegalArgumentException("Marker name cannot be null"); - } - - Marker marker = markerMap.get(name); - if (marker == null) { - marker = new BasicMarker(name); - Marker oldMarker = markerMap.putIfAbsent(name, marker); - if (oldMarker != null) { - marker = oldMarker; - } - } - return marker; - } - - /** - * Does the name marked already exist? - */ - public boolean exists(String name) { - if (name == null) { - return false; - } - return markerMap.containsKey(name); - } - - public boolean detachMarker(String name) { - if (name == null) { - return false; - } - return (markerMap.remove(name) != null); - } - - public Marker getDetachedMarker(String name) { - return new BasicMarker(name); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.slf4j.IMarkerFactory; +import org.slf4j.Marker; + +/** + * An almost trivial implementation of the {@link IMarkerFactory} + * interface which creates {@link BasicMarker} instances. + * + *

Simple logging systems can conform to the SLF4J API by binding + * {@link org.slf4j.MarkerFactory} with an instance of this class. + * + * @author Ceki Gülcü + */ +public class BasicMarkerFactory implements IMarkerFactory { + + private final ConcurrentMap markerMap = new ConcurrentHashMap(); + + /** + * Regular users should not create + * BasicMarkerFactory instances. Marker + * instances can be obtained using the static {@link + * org.slf4j.MarkerFactory#getMarker} method. + */ + public BasicMarkerFactory() { + } + + /** + * Manufacture a {@link BasicMarker} instance by name. If the instance has been + * created earlier, return the previously created instance. + * + * @param name the name of the marker to be created + * @return a Marker instance + */ + public Marker getMarker(String name) { + if (name == null) { + throw new IllegalArgumentException("Marker name cannot be null"); + } + + Marker marker = markerMap.get(name); + if (marker == null) { + marker = new BasicMarker(name); + Marker oldMarker = markerMap.putIfAbsent(name, marker); + if (oldMarker != null) { + marker = oldMarker; + } + } + return marker; + } + + /** + * Does the name marked already exist? + */ + public boolean exists(String name) { + if (name == null) { + return false; + } + return markerMap.containsKey(name); + } + + public boolean detachMarker(String name) { + if (name == null) { + return false; + } + return (markerMap.remove(name) != null); + } + + public Marker getDetachedMarker(String name) { + return new BasicMarker(name); + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/FormattingTuple.java b/slf4j-api/src/main/java/org/slf4j/helpers/FormattingTuple.java index 8d34f73..6792b11 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/FormattingTuple.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/FormattingTuple.java @@ -1,62 +1,62 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -/** - * Holds the results of formatting done by {@link MessageFormatter}. - * - * @author Joern Huxhorn - */ -public class FormattingTuple { - - static public FormattingTuple NULL = new FormattingTuple(null); - - private String message; - private Throwable throwable; - private Object[] argArray; - - public FormattingTuple(String message) { - this(message, null, null); - } - - public FormattingTuple(String message, Object[] argArray, Throwable throwable) { - this.message = message; - this.throwable = throwable; - this.argArray = argArray; - } - - public String getMessage() { - return message; - } - - public Object[] getArgArray() { - return argArray; - } - - public Throwable getThrowable() { - return throwable; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +/** + * Holds the results of formatting done by {@link MessageFormatter}. + * + * @author Joern Huxhorn + */ +public class FormattingTuple { + + static public FormattingTuple NULL = new FormattingTuple(null); + + private String message; + private Throwable throwable; + private Object[] argArray; + + public FormattingTuple(String message) { + this(message, null, null); + } + + public FormattingTuple(String message, Object[] argArray, Throwable throwable) { + this.message = message; + this.throwable = throwable; + this.argArray = argArray; + } + + public String getMessage() { + return message; + } + + public Object[] getArgArray() { + return argArray; + } + + public Throwable getThrowable() { + return throwable; + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/MarkerIgnoringBase.java b/slf4j-api/src/main/java/org/slf4j/helpers/MarkerIgnoringBase.java index ccce9fd..dd76538 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/MarkerIgnoringBase.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/MarkerIgnoringBase.java @@ -1,166 +1,166 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import org.slf4j.Logger; -import org.slf4j.Marker; - -/** - * This class serves as base for adapters or native implementations of logging systems - * lacking Marker support. In this implementation, methods taking marker data - * simply invoke the corresponding method without the Marker argument, discarding - * any marker data passed as argument. - * - * @author Ceki Gulcu - */ -public abstract class MarkerIgnoringBase extends NamedLoggerBase implements Logger { - - private static final long serialVersionUID = 9044267456635152283L; - - public boolean isTraceEnabled(Marker marker) { - return isTraceEnabled(); - } - - public void trace(Marker marker, String msg) { - trace(msg); - } - - public void trace(Marker marker, String format, Object arg) { - trace(format, arg); - } - - public void trace(Marker marker, String format, Object arg1, Object arg2) { - trace(format, arg1, arg2); - } - - public void trace(Marker marker, String format, Object... arguments) { - trace(format, arguments); - } - - public void trace(Marker marker, String msg, Throwable t) { - trace(msg, t); - } - - public boolean isDebugEnabled(Marker marker) { - return isDebugEnabled(); - } - - public void debug(Marker marker, String msg) { - debug(msg); - } - - public void debug(Marker marker, String format, Object arg) { - debug(format, arg); - } - - public void debug(Marker marker, String format, Object arg1, Object arg2) { - debug(format, arg1, arg2); - } - - public void debug(Marker marker, String format, Object... arguments) { - debug(format, arguments); - } - - public void debug(Marker marker, String msg, Throwable t) { - debug(msg, t); - } - - public boolean isInfoEnabled(Marker marker) { - return isInfoEnabled(); - } - - public void info(Marker marker, String msg) { - info(msg); - } - - public void info(Marker marker, String format, Object arg) { - info(format, arg); - } - - public void info(Marker marker, String format, Object arg1, Object arg2) { - info(format, arg1, arg2); - } - - public void info(Marker marker, String format, Object... arguments) { - info(format, arguments); - } - - public void info(Marker marker, String msg, Throwable t) { - info(msg, t); - } - - public boolean isWarnEnabled(Marker marker) { - return isWarnEnabled(); - } - - public void warn(Marker marker, String msg) { - warn(msg); - } - - public void warn(Marker marker, String format, Object arg) { - warn(format, arg); - } - - public void warn(Marker marker, String format, Object arg1, Object arg2) { - warn(format, arg1, arg2); - } - - public void warn(Marker marker, String format, Object... arguments) { - warn(format, arguments); - } - - public void warn(Marker marker, String msg, Throwable t) { - warn(msg, t); - } - - public boolean isErrorEnabled(Marker marker) { - return isErrorEnabled(); - } - - public void error(Marker marker, String msg) { - error(msg); - } - - public void error(Marker marker, String format, Object arg) { - error(format, arg); - } - - public void error(Marker marker, String format, Object arg1, Object arg2) { - error(format, arg1, arg2); - } - - public void error(Marker marker, String format, Object... arguments) { - error(format, arguments); - } - - public void error(Marker marker, String msg, Throwable t) { - error(msg, t); - } - - public String toString() { - return this.getClass().getName() + "(" + getName() + ")"; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import org.slf4j.Logger; +import org.slf4j.Marker; + +/** + * This class serves as base for adapters or native implementations of logging systems + * lacking Marker support. In this implementation, methods taking marker data + * simply invoke the corresponding method without the Marker argument, discarding + * any marker data passed as argument. + * + * @author Ceki Gulcu + */ +public abstract class MarkerIgnoringBase extends NamedLoggerBase implements Logger { + + private static final long serialVersionUID = 9044267456635152283L; + + public boolean isTraceEnabled(Marker marker) { + return isTraceEnabled(); + } + + public void trace(Marker marker, String msg) { + trace(msg); + } + + public void trace(Marker marker, String format, Object arg) { + trace(format, arg); + } + + public void trace(Marker marker, String format, Object arg1, Object arg2) { + trace(format, arg1, arg2); + } + + public void trace(Marker marker, String format, Object... arguments) { + trace(format, arguments); + } + + public void trace(Marker marker, String msg, Throwable t) { + trace(msg, t); + } + + public boolean isDebugEnabled(Marker marker) { + return isDebugEnabled(); + } + + public void debug(Marker marker, String msg) { + debug(msg); + } + + public void debug(Marker marker, String format, Object arg) { + debug(format, arg); + } + + public void debug(Marker marker, String format, Object arg1, Object arg2) { + debug(format, arg1, arg2); + } + + public void debug(Marker marker, String format, Object... arguments) { + debug(format, arguments); + } + + public void debug(Marker marker, String msg, Throwable t) { + debug(msg, t); + } + + public boolean isInfoEnabled(Marker marker) { + return isInfoEnabled(); + } + + public void info(Marker marker, String msg) { + info(msg); + } + + public void info(Marker marker, String format, Object arg) { + info(format, arg); + } + + public void info(Marker marker, String format, Object arg1, Object arg2) { + info(format, arg1, arg2); + } + + public void info(Marker marker, String format, Object... arguments) { + info(format, arguments); + } + + public void info(Marker marker, String msg, Throwable t) { + info(msg, t); + } + + public boolean isWarnEnabled(Marker marker) { + return isWarnEnabled(); + } + + public void warn(Marker marker, String msg) { + warn(msg); + } + + public void warn(Marker marker, String format, Object arg) { + warn(format, arg); + } + + public void warn(Marker marker, String format, Object arg1, Object arg2) { + warn(format, arg1, arg2); + } + + public void warn(Marker marker, String format, Object... arguments) { + warn(format, arguments); + } + + public void warn(Marker marker, String msg, Throwable t) { + warn(msg, t); + } + + public boolean isErrorEnabled(Marker marker) { + return isErrorEnabled(); + } + + public void error(Marker marker, String msg) { + error(msg); + } + + public void error(Marker marker, String format, Object arg) { + error(format, arg); + } + + public void error(Marker marker, String format, Object arg1, Object arg2) { + error(format, arg1, arg2); + } + + public void error(Marker marker, String format, Object... arguments) { + error(format, arguments); + } + + public void error(Marker marker, String msg, Throwable t) { + error(msg, t); + } + + public String toString() { + return this.getClass().getName() + "(" + getName() + ")"; + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/MessageFormatter.java b/slf4j-api/src/main/java/org/slf4j/helpers/MessageFormatter.java old file mode 100644 new file mode 100755 index 3b7557b..bdbfb19 100755 --- a/slf4j-api/src/main/java/org/slf4j/helpers/MessageFormatter.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/MessageFormatter.java @@ -1,414 +1,414 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; - -// contributors: lizongbo: proposed special treatment of array parameter values -// Joern Huxhorn: pointed out double[] omission, suggested deep array copy -/** - * Formats messages according to very simple substitution rules. Substitutions - * can be made 1, 2 or more arguments. - * - *

- * For example, - * - *

- * MessageFormatter.format("Hi {}.", "there")
- * 
- * - * will return the string "Hi there.". - *

- * The {} pair is called the formatting anchor. It serves to designate - * the location where arguments need to be substituted within the message - * pattern. - *

- * In case your message contains the '{' or the '}' character, you do not have - * to do anything special unless the '}' character immediately follows '{'. For - * example, - * - *

- * MessageFormatter.format("Set {1,2,3} is not equal to {}.", "1,2");
- * 
- * - * will return the string "Set {1,2,3} is not equal to 1,2.". - * - *

- * If for whatever reason you need to place the string "{}" in the message - * without its formatting anchor meaning, then you need to escape the - * '{' character with '\', that is the backslash character. Only the '{' - * character should be escaped. There is no need to escape the '}' character. - * For example, - * - *

- * MessageFormatter.format("Set \\{} is not equal to {}.", "1,2");
- * 
- * - * will return the string "Set {} is not equal to 1,2.". - * - *

- * The escaping behavior just described can be overridden by escaping the escape - * character '\'. Calling - * - *

- * MessageFormatter.format("File name is C:\\\\{}.", "file.zip");
- * 
- * - * will return the string "File name is C:\file.zip". - * - *

- * The formatting conventions are different than those of {@link MessageFormat} - * which ships with the Java platform. This is justified by the fact that - * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}. - * This local performance difference is both measurable and significant in the - * larger context of the complete logging processing chain. - * - *

- * See also {@link #format(String, Object)}, - * {@link #format(String, Object, Object)} and - * {@link #arrayFormat(String, Object[])} methods for more details. - * - * @author Ceki Gülcü - * @author Joern Huxhorn - */ -final public class MessageFormatter { - static final char DELIM_START = '{'; - static final char DELIM_STOP = '}'; - static final String DELIM_STR = "{}"; - private static final char ESCAPE_CHAR = '\\'; - - /** - * Performs single argument substitution for the 'messagePattern' passed as - * parameter. - *

- * For example, - * - *

-     * MessageFormatter.format("Hi {}.", "there");
-     * 
- * - * will return the string "Hi there.". - *

- * - * @param messagePattern - * The message pattern which will be parsed and formatted - * @param arg - * The argument to be substituted in place of the formatting anchor - * @return The formatted message - */ - final public static FormattingTuple format(String messagePattern, Object arg) { - return arrayFormat(messagePattern, new Object[] { arg }); - } - - /** - * - * Performs a two argument substitution for the 'messagePattern' passed as - * parameter. - *

- * For example, - * - *

-     * MessageFormatter.format("Hi {}. My name is {}.", "Alice", "Bob");
-     * 
- * - * will return the string "Hi Alice. My name is Bob.". - * - * @param messagePattern - * The message pattern which will be parsed and formatted - * @param arg1 - * The argument to be substituted in place of the first formatting - * anchor - * @param arg2 - * The argument to be substituted in place of the second formatting - * anchor - * @return The formatted message - */ - final public static FormattingTuple format(final String messagePattern, Object arg1, Object arg2) { - return arrayFormat(messagePattern, new Object[] { arg1, arg2 }); - } - - - static final Throwable getThrowableCandidate(Object[] argArray) { - if (argArray == null || argArray.length == 0) { - return null; - } - - final Object lastEntry = argArray[argArray.length - 1]; - if (lastEntry instanceof Throwable) { - return (Throwable) lastEntry; - } - return null; - } - - final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) { - Throwable throwableCandidate = getThrowableCandidate(argArray); - Object[] args = argArray; - if (throwableCandidate != null) { - args = trimmedCopy(argArray); - } - return arrayFormat(messagePattern, args, throwableCandidate); - } - - private static Object[] trimmedCopy(Object[] argArray) { - if (argArray == null || argArray.length == 0) { - throw new IllegalStateException("non-sensical empty or null argument array"); - } - final int trimemdLen = argArray.length - 1; - Object[] trimmed = new Object[trimemdLen]; - System.arraycopy(argArray, 0, trimmed, 0, trimemdLen); - return trimmed; - } - - final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray, Throwable throwable) { - - if (messagePattern == null) { - return new FormattingTuple(null, argArray, throwable); - } - - if (argArray == null) { - return new FormattingTuple(messagePattern); - } - - int i = 0; - int j; - // use string builder for better multicore performance - StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50); - - int L; - for (L = 0; L < argArray.length; L++) { - - j = messagePattern.indexOf(DELIM_STR, i); - - if (j == -1) { - // no more variables - if (i == 0) { // this is a simple string - return new FormattingTuple(messagePattern, argArray, throwable); - } else { // add the tail string which contains no variables and return - // the result. - sbuf.append(messagePattern, i, messagePattern.length()); - return new FormattingTuple(sbuf.toString(), argArray, throwable); - } - } else { - if (isEscapedDelimeter(messagePattern, j)) { - if (!isDoubleEscaped(messagePattern, j)) { - L--; // DELIM_START was escaped, thus should not be incremented - sbuf.append(messagePattern, i, j - 1); - sbuf.append(DELIM_START); - i = j + 1; - } else { - // The escape character preceding the delimiter start is - // itself escaped: "abc x:\\{}" - // we have to consume one backward slash - sbuf.append(messagePattern, i, j - 1); - deeplyAppendParameter(sbuf, argArray[L], new HashMap()); - i = j + 2; - } - } else { - // normal case - sbuf.append(messagePattern, i, j); - deeplyAppendParameter(sbuf, argArray[L], new HashMap()); - i = j + 2; - } - } - } - // append the characters following the last {} pair. - sbuf.append(messagePattern, i, messagePattern.length()); - return new FormattingTuple(sbuf.toString(), argArray, throwable); - } - - final static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { - - if (delimeterStartIndex == 0) { - return false; - } - char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1); - if (potentialEscape == ESCAPE_CHAR) { - return true; - } else { - return false; - } - } - - final static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { - if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) { - return true; - } else { - return false; - } - } - - // special treatment of array values was suggested by 'lizongbo' - private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map seenMap) { - if (o == null) { - sbuf.append("null"); - return; - } - if (!o.getClass().isArray()) { - safeObjectAppend(sbuf, o); - } else { - // check for primitive array types because they - // unfortunately cannot be cast to Object[] - if (o instanceof boolean[]) { - booleanArrayAppend(sbuf, (boolean[]) o); - } else if (o instanceof byte[]) { - byteArrayAppend(sbuf, (byte[]) o); - } else if (o instanceof char[]) { - charArrayAppend(sbuf, (char[]) o); - } else if (o instanceof short[]) { - shortArrayAppend(sbuf, (short[]) o); - } else if (o instanceof int[]) { - intArrayAppend(sbuf, (int[]) o); - } else if (o instanceof long[]) { - longArrayAppend(sbuf, (long[]) o); - } else if (o instanceof float[]) { - floatArrayAppend(sbuf, (float[]) o); - } else if (o instanceof double[]) { - doubleArrayAppend(sbuf, (double[]) o); - } else { - objectArrayAppend(sbuf, (Object[]) o, seenMap); - } - } - } - - private static void safeObjectAppend(StringBuilder sbuf, Object o) { - try { - String oAsString = o.toString(); - sbuf.append(oAsString); - } catch (Throwable t) { - Util.report("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]", t); - sbuf.append("[FAILED toString()]"); - } - - } - - private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map seenMap) { - sbuf.append('['); - if (!seenMap.containsKey(a)) { - seenMap.put(a, null); - final int len = a.length; - for (int i = 0; i < len; i++) { - deeplyAppendParameter(sbuf, a[i], seenMap); - if (i != len - 1) - sbuf.append(", "); - } - // allow repeats in siblings - seenMap.remove(a); - } else { - sbuf.append("..."); - } - sbuf.append(']'); - } - - private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } - - private static void byteArrayAppend(StringBuilder sbuf, byte[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } - - private static void charArrayAppend(StringBuilder sbuf, char[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } - - private static void shortArrayAppend(StringBuilder sbuf, short[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } - - private static void intArrayAppend(StringBuilder sbuf, int[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } - - private static void longArrayAppend(StringBuilder sbuf, long[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } - - private static void floatArrayAppend(StringBuilder sbuf, float[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } - - private static void doubleArrayAppend(StringBuilder sbuf, double[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; + +// contributors: lizongbo: proposed special treatment of array parameter values +// Joern Huxhorn: pointed out double[] omission, suggested deep array copy +/** + * Formats messages according to very simple substitution rules. Substitutions + * can be made 1, 2 or more arguments. + * + *

+ * For example, + * + *

+ * MessageFormatter.format("Hi {}.", "there")
+ * 
+ * + * will return the string "Hi there.". + *

+ * The {} pair is called the formatting anchor. It serves to designate + * the location where arguments need to be substituted within the message + * pattern. + *

+ * In case your message contains the '{' or the '}' character, you do not have + * to do anything special unless the '}' character immediately follows '{'. For + * example, + * + *

+ * MessageFormatter.format("Set {1,2,3} is not equal to {}.", "1,2");
+ * 
+ * + * will return the string "Set {1,2,3} is not equal to 1,2.". + * + *

+ * If for whatever reason you need to place the string "{}" in the message + * without its formatting anchor meaning, then you need to escape the + * '{' character with '\', that is the backslash character. Only the '{' + * character should be escaped. There is no need to escape the '}' character. + * For example, + * + *

+ * MessageFormatter.format("Set \\{} is not equal to {}.", "1,2");
+ * 
+ * + * will return the string "Set {} is not equal to 1,2.". + * + *

+ * The escaping behavior just described can be overridden by escaping the escape + * character '\'. Calling + * + *

+ * MessageFormatter.format("File name is C:\\\\{}.", "file.zip");
+ * 
+ * + * will return the string "File name is C:\file.zip". + * + *

+ * The formatting conventions are different than those of {@link MessageFormat} + * which ships with the Java platform. This is justified by the fact that + * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}. + * This local performance difference is both measurable and significant in the + * larger context of the complete logging processing chain. + * + *

+ * See also {@link #format(String, Object)}, + * {@link #format(String, Object, Object)} and + * {@link #arrayFormat(String, Object[])} methods for more details. + * + * @author Ceki Gülcü + * @author Joern Huxhorn + */ +final public class MessageFormatter { + static final char DELIM_START = '{'; + static final char DELIM_STOP = '}'; + static final String DELIM_STR = "{}"; + private static final char ESCAPE_CHAR = '\\'; + + /** + * Performs single argument substitution for the 'messagePattern' passed as + * parameter. + *

+ * For example, + * + *

+     * MessageFormatter.format("Hi {}.", "there");
+     * 
+ * + * will return the string "Hi there.". + *

+ * + * @param messagePattern + * The message pattern which will be parsed and formatted + * @param arg + * The argument to be substituted in place of the formatting anchor + * @return The formatted message + */ + final public static FormattingTuple format(String messagePattern, Object arg) { + return arrayFormat(messagePattern, new Object[] { arg }); + } + + /** + * + * Performs a two argument substitution for the 'messagePattern' passed as + * parameter. + *

+ * For example, + * + *

+     * MessageFormatter.format("Hi {}. My name is {}.", "Alice", "Bob");
+     * 
+ * + * will return the string "Hi Alice. My name is Bob.". + * + * @param messagePattern + * The message pattern which will be parsed and formatted + * @param arg1 + * The argument to be substituted in place of the first formatting + * anchor + * @param arg2 + * The argument to be substituted in place of the second formatting + * anchor + * @return The formatted message + */ + final public static FormattingTuple format(final String messagePattern, Object arg1, Object arg2) { + return arrayFormat(messagePattern, new Object[] { arg1, arg2 }); + } + + + static final Throwable getThrowableCandidate(Object[] argArray) { + if (argArray == null || argArray.length == 0) { + return null; + } + + final Object lastEntry = argArray[argArray.length - 1]; + if (lastEntry instanceof Throwable) { + return (Throwable) lastEntry; + } + return null; + } + + final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) { + Throwable throwableCandidate = getThrowableCandidate(argArray); + Object[] args = argArray; + if (throwableCandidate != null) { + args = trimmedCopy(argArray); + } + return arrayFormat(messagePattern, args, throwableCandidate); + } + + private static Object[] trimmedCopy(Object[] argArray) { + if (argArray == null || argArray.length == 0) { + throw new IllegalStateException("non-sensical empty or null argument array"); + } + final int trimemdLen = argArray.length - 1; + Object[] trimmed = new Object[trimemdLen]; + System.arraycopy(argArray, 0, trimmed, 0, trimemdLen); + return trimmed; + } + + final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray, Throwable throwable) { + + if (messagePattern == null) { + return new FormattingTuple(null, argArray, throwable); + } + + if (argArray == null) { + return new FormattingTuple(messagePattern); + } + + int i = 0; + int j; + // use string builder for better multicore performance + StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50); + + int L; + for (L = 0; L < argArray.length; L++) { + + j = messagePattern.indexOf(DELIM_STR, i); + + if (j == -1) { + // no more variables + if (i == 0) { // this is a simple string + return new FormattingTuple(messagePattern, argArray, throwable); + } else { // add the tail string which contains no variables and return + // the result. + sbuf.append(messagePattern, i, messagePattern.length()); + return new FormattingTuple(sbuf.toString(), argArray, throwable); + } + } else { + if (isEscapedDelimeter(messagePattern, j)) { + if (!isDoubleEscaped(messagePattern, j)) { + L--; // DELIM_START was escaped, thus should not be incremented + sbuf.append(messagePattern, i, j - 1); + sbuf.append(DELIM_START); + i = j + 1; + } else { + // The escape character preceding the delimiter start is + // itself escaped: "abc x:\\{}" + // we have to consume one backward slash + sbuf.append(messagePattern, i, j - 1); + deeplyAppendParameter(sbuf, argArray[L], new HashMap()); + i = j + 2; + } + } else { + // normal case + sbuf.append(messagePattern, i, j); + deeplyAppendParameter(sbuf, argArray[L], new HashMap()); + i = j + 2; + } + } + } + // append the characters following the last {} pair. + sbuf.append(messagePattern, i, messagePattern.length()); + return new FormattingTuple(sbuf.toString(), argArray, throwable); + } + + final static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { + + if (delimeterStartIndex == 0) { + return false; + } + char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1); + if (potentialEscape == ESCAPE_CHAR) { + return true; + } else { + return false; + } + } + + final static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { + if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) { + return true; + } else { + return false; + } + } + + // special treatment of array values was suggested by 'lizongbo' + private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map seenMap) { + if (o == null) { + sbuf.append("null"); + return; + } + if (!o.getClass().isArray()) { + safeObjectAppend(sbuf, o); + } else { + // check for primitive array types because they + // unfortunately cannot be cast to Object[] + if (o instanceof boolean[]) { + booleanArrayAppend(sbuf, (boolean[]) o); + } else if (o instanceof byte[]) { + byteArrayAppend(sbuf, (byte[]) o); + } else if (o instanceof char[]) { + charArrayAppend(sbuf, (char[]) o); + } else if (o instanceof short[]) { + shortArrayAppend(sbuf, (short[]) o); + } else if (o instanceof int[]) { + intArrayAppend(sbuf, (int[]) o); + } else if (o instanceof long[]) { + longArrayAppend(sbuf, (long[]) o); + } else if (o instanceof float[]) { + floatArrayAppend(sbuf, (float[]) o); + } else if (o instanceof double[]) { + doubleArrayAppend(sbuf, (double[]) o); + } else { + objectArrayAppend(sbuf, (Object[]) o, seenMap); + } + } + } + + private static void safeObjectAppend(StringBuilder sbuf, Object o) { + try { + String oAsString = o.toString(); + sbuf.append(oAsString); + } catch (Throwable t) { + Util.report("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]", t); + sbuf.append("[FAILED toString()]"); + } + + } + + private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map seenMap) { + sbuf.append('['); + if (!seenMap.containsKey(a)) { + seenMap.put(a, null); + final int len = a.length; + for (int i = 0; i < len; i++) { + deeplyAppendParameter(sbuf, a[i], seenMap); + if (i != len - 1) + sbuf.append(", "); + } + // allow repeats in siblings + seenMap.remove(a); + } else { + sbuf.append("..."); + } + sbuf.append(']'); + } + + private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void byteArrayAppend(StringBuilder sbuf, byte[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void charArrayAppend(StringBuilder sbuf, char[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void shortArrayAppend(StringBuilder sbuf, short[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void intArrayAppend(StringBuilder sbuf, int[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void longArrayAppend(StringBuilder sbuf, long[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void floatArrayAppend(StringBuilder sbuf, float[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void doubleArrayAppend(StringBuilder sbuf, double[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/NOPLogger.java b/slf4j-api/src/main/java/org/slf4j/helpers/NOPLogger.java index 38bf567..b98435f 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NOPLogger.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NOPLogger.java @@ -1,220 +1,220 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import org.slf4j.Logger; -import org.slf4j.helpers.MarkerIgnoringBase; - -/** - * A direct NOP (no operation) implementation of {@link Logger}. - * - * @author Ceki Gülcü - */ -public class NOPLogger extends MarkerIgnoringBase { - - private static final long serialVersionUID = -517220405410904473L; - - /** - * The unique instance of NOPLogger. - */ - public static final NOPLogger NOP_LOGGER = new NOPLogger(); - - /** - * There is no point in creating multiple instances of NOPLogger, - * except by derived classes, hence the protected access for the constructor. - */ - protected NOPLogger() { - } - - /** - * Always returns the string value "NOP". - */ - public String getName() { - return "NOP"; - } - - /** - * Always returns false. - * @return always false - */ - final public boolean isTraceEnabled() { - return false; - } - - /** A NOP implementation. */ - final public void trace(String msg) { - // NOP - } - - /** A NOP implementation. */ - final public void trace(String format, Object arg) { - // NOP - } - - /** A NOP implementation. */ - public final void trace(String format, Object arg1, Object arg2) { - // NOP - } - - /** A NOP implementation. */ - public final void trace(String format, Object... argArray) { - // NOP - } - - /** A NOP implementation. */ - final public void trace(String msg, Throwable t) { - // NOP - } - - /** - * Always returns false. - * @return always false - */ - final public boolean isDebugEnabled() { - return false; - } - - /** A NOP implementation. */ - final public void debug(String msg) { - // NOP - } - - /** A NOP implementation. */ - final public void debug(String format, Object arg) { - // NOP - } - - /** A NOP implementation. */ - public final void debug(String format, Object arg1, Object arg2) { - // NOP - } - - /** A NOP implementation. */ - public final void debug(String format, Object... argArray) { - // NOP - } - - /** A NOP implementation. */ - final public void debug(String msg, Throwable t) { - // NOP - } - - /** - * Always returns false. - * @return always false - */ - final public boolean isInfoEnabled() { - // NOP - return false; - } - - /** A NOP implementation. */ - final public void info(String msg) { - // NOP - } - - /** A NOP implementation. */ - final public void info(String format, Object arg1) { - // NOP - } - - /** A NOP implementation. */ - final public void info(String format, Object arg1, Object arg2) { - // NOP - } - - /** A NOP implementation. */ - public final void info(String format, Object... argArray) { - // NOP - } - - /** A NOP implementation. */ - final public void info(String msg, Throwable t) { - // NOP - } - - /** - * Always returns false. - * @return always false - */ - final public boolean isWarnEnabled() { - return false; - } - - /** A NOP implementation. */ - final public void warn(String msg) { - // NOP - } - - /** A NOP implementation. */ - final public void warn(String format, Object arg1) { - // NOP - } - - /** A NOP implementation. */ - final public void warn(String format, Object arg1, Object arg2) { - // NOP - } - - /** A NOP implementation. */ - public final void warn(String format, Object... argArray) { - // NOP - } - - /** A NOP implementation. */ - final public void warn(String msg, Throwable t) { - // NOP - } - - /** A NOP implementation. */ - final public boolean isErrorEnabled() { - return false; - } - - /** A NOP implementation. */ - final public void error(String msg) { - // NOP - } - - /** A NOP implementation. */ - final public void error(String format, Object arg1) { - // NOP - } - - /** A NOP implementation. */ - final public void error(String format, Object arg1, Object arg2) { - // NOP - } - - /** A NOP implementation. */ - public final void error(String format, Object... argArray) { - // NOP - } - - /** A NOP implementation. */ - final public void error(String msg, Throwable t) { - // NOP - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import org.slf4j.Logger; +import org.slf4j.helpers.MarkerIgnoringBase; + +/** + * A direct NOP (no operation) implementation of {@link Logger}. + * + * @author Ceki Gülcü + */ +public class NOPLogger extends MarkerIgnoringBase { + + private static final long serialVersionUID = -517220405410904473L; + + /** + * The unique instance of NOPLogger. + */ + public static final NOPLogger NOP_LOGGER = new NOPLogger(); + + /** + * There is no point in creating multiple instances of NOPLogger, + * except by derived classes, hence the protected access for the constructor. + */ + protected NOPLogger() { + } + + /** + * Always returns the string value "NOP". + */ + public String getName() { + return "NOP"; + } + + /** + * Always returns false. + * @return always false + */ + final public boolean isTraceEnabled() { + return false; + } + + /** A NOP implementation. */ + final public void trace(String msg) { + // NOP + } + + /** A NOP implementation. */ + final public void trace(String format, Object arg) { + // NOP + } + + /** A NOP implementation. */ + public final void trace(String format, Object arg1, Object arg2) { + // NOP + } + + /** A NOP implementation. */ + public final void trace(String format, Object... argArray) { + // NOP + } + + /** A NOP implementation. */ + final public void trace(String msg, Throwable t) { + // NOP + } + + /** + * Always returns false. + * @return always false + */ + final public boolean isDebugEnabled() { + return false; + } + + /** A NOP implementation. */ + final public void debug(String msg) { + // NOP + } + + /** A NOP implementation. */ + final public void debug(String format, Object arg) { + // NOP + } + + /** A NOP implementation. */ + public final void debug(String format, Object arg1, Object arg2) { + // NOP + } + + /** A NOP implementation. */ + public final void debug(String format, Object... argArray) { + // NOP + } + + /** A NOP implementation. */ + final public void debug(String msg, Throwable t) { + // NOP + } + + /** + * Always returns false. + * @return always false + */ + final public boolean isInfoEnabled() { + // NOP + return false; + } + + /** A NOP implementation. */ + final public void info(String msg) { + // NOP + } + + /** A NOP implementation. */ + final public void info(String format, Object arg1) { + // NOP + } + + /** A NOP implementation. */ + final public void info(String format, Object arg1, Object arg2) { + // NOP + } + + /** A NOP implementation. */ + public final void info(String format, Object... argArray) { + // NOP + } + + /** A NOP implementation. */ + final public void info(String msg, Throwable t) { + // NOP + } + + /** + * Always returns false. + * @return always false + */ + final public boolean isWarnEnabled() { + return false; + } + + /** A NOP implementation. */ + final public void warn(String msg) { + // NOP + } + + /** A NOP implementation. */ + final public void warn(String format, Object arg1) { + // NOP + } + + /** A NOP implementation. */ + final public void warn(String format, Object arg1, Object arg2) { + // NOP + } + + /** A NOP implementation. */ + public final void warn(String format, Object... argArray) { + // NOP + } + + /** A NOP implementation. */ + final public void warn(String msg, Throwable t) { + // NOP + } + + /** A NOP implementation. */ + final public boolean isErrorEnabled() { + return false; + } + + /** A NOP implementation. */ + final public void error(String msg) { + // NOP + } + + /** A NOP implementation. */ + final public void error(String format, Object arg1) { + // NOP + } + + /** A NOP implementation. */ + final public void error(String format, Object arg1, Object arg2) { + // NOP + } + + /** A NOP implementation. */ + public final void error(String format, Object... argArray) { + // NOP + } + + /** A NOP implementation. */ + final public void error(String msg, Throwable t) { + // NOP + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/NOPLoggerFactory.java b/slf4j-api/src/main/java/org/slf4j/helpers/NOPLoggerFactory.java index 491e40a..b8a55dc 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NOPLoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NOPLoggerFactory.java @@ -1,48 +1,48 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import org.slf4j.ILoggerFactory; -import org.slf4j.Logger; -import org.slf4j.helpers.NOPLogger; - -/** - * NOPLoggerFactory is an trivial implementation of {@link - * ILoggerFactory} which always returns the unique instance of - * NOPLogger. - * - * @author Ceki Gülcü - */ -public class NOPLoggerFactory implements ILoggerFactory { - - public NOPLoggerFactory() { - // nothing to do - } - - public Logger getLogger(String name) { - return NOPLogger.NOP_LOGGER; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import org.slf4j.ILoggerFactory; +import org.slf4j.Logger; +import org.slf4j.helpers.NOPLogger; + +/** + * NOPLoggerFactory is an trivial implementation of {@link + * ILoggerFactory} which always returns the unique instance of + * NOPLogger. + * + * @author Ceki Gülcü + */ +public class NOPLoggerFactory implements ILoggerFactory { + + public NOPLoggerFactory() { + // nothing to do + } + + public Logger getLogger(String name) { + return NOPLogger.NOP_LOGGER; + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/NOPMDCAdapter.java b/slf4j-api/src/main/java/org/slf4j/helpers/NOPMDCAdapter.java index c307d27..22f3ea4 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NOPMDCAdapter.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NOPMDCAdapter.java @@ -1,63 +1,63 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import java.util.Map; - -import org.slf4j.spi.MDCAdapter; - -/** - * This adapter is an empty implementation of the {@link MDCAdapter} interface. - * It is used for all logging systems which do not support mapped - * diagnostic contexts such as JDK14, simple and NOP. - * - * @author Ceki Gülcü - * - * @since 1.4.1 - */ -public class NOPMDCAdapter implements MDCAdapter { - - public void clear() { - } - - public String get(String key) { - return null; - } - - public void put(String key, String val) { - } - - public void remove(String key) { - } - - public Map getCopyOfContextMap() { - return null; - } - - public void setContextMap(Map contextMap) { - // NOP - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import java.util.Map; + +import org.slf4j.spi.MDCAdapter; + +/** + * This adapter is an empty implementation of the {@link MDCAdapter} interface. + * It is used for all logging systems which do not support mapped + * diagnostic contexts such as JDK14, simple and NOP. + * + * @author Ceki Gülcü + * + * @since 1.4.1 + */ +public class NOPMDCAdapter implements MDCAdapter { + + public void clear() { + } + + public String get(String key) { + return null; + } + + public void put(String key, String val) { + } + + public void remove(String key) { + } + + public Map getCopyOfContextMap() { + return null; + } + + public void setContextMap(Map contextMap) { + // NOP + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/NamedLoggerBase.java b/slf4j-api/src/main/java/org/slf4j/helpers/NamedLoggerBase.java index 6e1cce1..e2a1d06 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NamedLoggerBase.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NamedLoggerBase.java @@ -1,71 +1,71 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import java.io.ObjectStreamException; -import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Serves as base class for named logger implementation. More significantly, this - * class establishes deserialization behavior. - * - * @author Ceki Gulcu - * @see #readResolve - * @since 1.5.3 - */ -abstract class NamedLoggerBase implements Logger, Serializable { - - private static final long serialVersionUID = 7535258609338176893L; - - protected String name; - - public String getName() { - return name; - } - - /** - * Replace this instance with a homonymous (same name) logger returned - * by LoggerFactory. Note that this method is only called during - * deserialization. - * - *

- * This approach will work well if the desired ILoggerFactory is the one - * references by LoggerFactory. However, if the user manages its logger hierarchy - * through a different (non-static) mechanism, e.g. dependency injection, then - * this approach would be mostly counterproductive. - * - * @return logger with same name as returned by LoggerFactory - * @throws ObjectStreamException - */ - protected Object readResolve() throws ObjectStreamException { - // using getName() instead of this.name works even for - // NOPLogger - return LoggerFactory.getLogger(getName()); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Serves as base class for named logger implementation. More significantly, this + * class establishes deserialization behavior. + * + * @author Ceki Gulcu + * @see #readResolve + * @since 1.5.3 + */ +abstract class NamedLoggerBase implements Logger, Serializable { + + private static final long serialVersionUID = 7535258609338176893L; + + protected String name; + + public String getName() { + return name; + } + + /** + * Replace this instance with a homonymous (same name) logger returned + * by LoggerFactory. Note that this method is only called during + * deserialization. + * + *

+ * This approach will work well if the desired ILoggerFactory is the one + * references by LoggerFactory. However, if the user manages its logger hierarchy + * through a different (non-static) mechanism, e.g. dependency injection, then + * this approach would be mostly counterproductive. + * + * @return logger with same name as returned by LoggerFactory + * @throws ObjectStreamException + */ + protected Object readResolve() throws ObjectStreamException { + // using getName() instead of this.name works even for + // NOPLogger + return LoggerFactory.getLogger(getName()); + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLogger.java b/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLogger.java index ec0d768..3ac0d32 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLogger.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLogger.java @@ -1,390 +1,390 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Queue; - -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.event.EventRecodingLogger; -import org.slf4j.event.LoggingEvent; -import org.slf4j.event.SubstituteLoggingEvent; - -/** - * A logger implementation which logs via a delegate logger. By default, the delegate is a - * {@link NOPLogger}. However, a different delegate can be set at any time. - *

- * See also the relevant - * error code documentation. - * - * @author Chetan Mehrotra - * @author Ceki Gulcu - */ -public class SubstituteLogger implements Logger { - - private final String name; - private volatile Logger _delegate; - private Boolean delegateEventAware; - private Method logMethodCache; - private EventRecodingLogger eventRecodingLogger; - private Queue eventQueue; - - private final boolean createdPostInitialization; - - public SubstituteLogger(String name, Queue eventQueue, boolean createdPostInitialization) { - this.name = name; - this.eventQueue = eventQueue; - this.createdPostInitialization = createdPostInitialization; - } - - public String getName() { - return name; - } - - public boolean isTraceEnabled() { - return delegate().isTraceEnabled(); - } - - public void trace(String msg) { - delegate().trace(msg); - } - - public void trace(String format, Object arg) { - delegate().trace(format, arg); - } - - public void trace(String format, Object arg1, Object arg2) { - delegate().trace(format, arg1, arg2); - } - - public void trace(String format, Object... arguments) { - delegate().trace(format, arguments); - } - - public void trace(String msg, Throwable t) { - delegate().trace(msg, t); - } - - public boolean isTraceEnabled(Marker marker) { - return delegate().isTraceEnabled(marker); - } - - public void trace(Marker marker, String msg) { - delegate().trace(marker, msg); - } - - public void trace(Marker marker, String format, Object arg) { - delegate().trace(marker, format, arg); - } - - public void trace(Marker marker, String format, Object arg1, Object arg2) { - delegate().trace(marker, format, arg1, arg2); - } - - public void trace(Marker marker, String format, Object... arguments) { - delegate().trace(marker, format, arguments); - } - - public void trace(Marker marker, String msg, Throwable t) { - delegate().trace(marker, msg, t); - } - - public boolean isDebugEnabled() { - return delegate().isDebugEnabled(); - } - - public void debug(String msg) { - delegate().debug(msg); - } - - public void debug(String format, Object arg) { - delegate().debug(format, arg); - } - - public void debug(String format, Object arg1, Object arg2) { - delegate().debug(format, arg1, arg2); - } - - public void debug(String format, Object... arguments) { - delegate().debug(format, arguments); - } - - public void debug(String msg, Throwable t) { - delegate().debug(msg, t); - } - - public boolean isDebugEnabled(Marker marker) { - return delegate().isDebugEnabled(marker); - } - - public void debug(Marker marker, String msg) { - delegate().debug(marker, msg); - } - - public void debug(Marker marker, String format, Object arg) { - delegate().debug(marker, format, arg); - } - - public void debug(Marker marker, String format, Object arg1, Object arg2) { - delegate().debug(marker, format, arg1, arg2); - } - - public void debug(Marker marker, String format, Object... arguments) { - delegate().debug(marker, format, arguments); - } - - public void debug(Marker marker, String msg, Throwable t) { - delegate().debug(marker, msg, t); - } - - public boolean isInfoEnabled() { - return delegate().isInfoEnabled(); - } - - public void info(String msg) { - delegate().info(msg); - } - - public void info(String format, Object arg) { - delegate().info(format, arg); - } - - public void info(String format, Object arg1, Object arg2) { - delegate().info(format, arg1, arg2); - } - - public void info(String format, Object... arguments) { - delegate().info(format, arguments); - } - - public void info(String msg, Throwable t) { - delegate().info(msg, t); - } - - public boolean isInfoEnabled(Marker marker) { - return delegate().isInfoEnabled(marker); - } - - public void info(Marker marker, String msg) { - delegate().info(marker, msg); - } - - public void info(Marker marker, String format, Object arg) { - delegate().info(marker, format, arg); - } - - public void info(Marker marker, String format, Object arg1, Object arg2) { - delegate().info(marker, format, arg1, arg2); - } - - public void info(Marker marker, String format, Object... arguments) { - delegate().info(marker, format, arguments); - } - - public void info(Marker marker, String msg, Throwable t) { - delegate().info(marker, msg, t); - } - - public boolean isWarnEnabled() { - return delegate().isWarnEnabled(); - } - - public void warn(String msg) { - delegate().warn(msg); - } - - public void warn(String format, Object arg) { - delegate().warn(format, arg); - } - - public void warn(String format, Object arg1, Object arg2) { - delegate().warn(format, arg1, arg2); - } - - public void warn(String format, Object... arguments) { - delegate().warn(format, arguments); - } - - public void warn(String msg, Throwable t) { - delegate().warn(msg, t); - } - - public boolean isWarnEnabled(Marker marker) { - return delegate().isWarnEnabled(marker); - } - - public void warn(Marker marker, String msg) { - delegate().warn(marker, msg); - } - - public void warn(Marker marker, String format, Object arg) { - delegate().warn(marker, format, arg); - } - - public void warn(Marker marker, String format, Object arg1, Object arg2) { - delegate().warn(marker, format, arg1, arg2); - } - - public void warn(Marker marker, String format, Object... arguments) { - delegate().warn(marker, format, arguments); - } - - public void warn(Marker marker, String msg, Throwable t) { - delegate().warn(marker, msg, t); - } - - public boolean isErrorEnabled() { - return delegate().isErrorEnabled(); - } - - public void error(String msg) { - delegate().error(msg); - } - - public void error(String format, Object arg) { - delegate().error(format, arg); - } - - public void error(String format, Object arg1, Object arg2) { - delegate().error(format, arg1, arg2); - } - - public void error(String format, Object... arguments) { - delegate().error(format, arguments); - } - - public void error(String msg, Throwable t) { - delegate().error(msg, t); - } - - public boolean isErrorEnabled(Marker marker) { - return delegate().isErrorEnabled(marker); - } - - public void error(Marker marker, String msg) { - delegate().error(marker, msg); - } - - public void error(Marker marker, String format, Object arg) { - delegate().error(marker, format, arg); - } - - public void error(Marker marker, String format, Object arg1, Object arg2) { - delegate().error(marker, format, arg1, arg2); - } - - public void error(Marker marker, String format, Object... arguments) { - delegate().error(marker, format, arguments); - } - - public void error(Marker marker, String msg, Throwable t) { - delegate().error(marker, msg, t); - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - - SubstituteLogger that = (SubstituteLogger) o; - - if (!name.equals(that.name)) - return false; - - return true; - } - - @Override - public int hashCode() { - return name.hashCode(); - } - - /** - * Return the delegate logger instance if set. Otherwise, return a {@link NOPLogger} - * instance. - */ - Logger delegate() { - if(_delegate != null) { - return _delegate; - } - if(createdPostInitialization) { - return NOPLogger.NOP_LOGGER; - } else { - return getEventRecordingLogger(); - } - } - - private Logger getEventRecordingLogger() { - if (eventRecodingLogger == null) { - eventRecodingLogger = new EventRecodingLogger(this, eventQueue); - } - return eventRecodingLogger; - } - - /** - * Typically called after the {@link org.slf4j.LoggerFactory} initialization phase is completed. - * @param delegate - */ - public void setDelegate(Logger delegate) { - this._delegate = delegate; - } - - public boolean isDelegateEventAware() { - if (delegateEventAware != null) - return delegateEventAware; - - try { - logMethodCache = _delegate.getClass().getMethod("log", LoggingEvent.class); - delegateEventAware = Boolean.TRUE; - } catch (NoSuchMethodException e) { - delegateEventAware = Boolean.FALSE; - } - return delegateEventAware; - } - - public void log(LoggingEvent event) { - if (isDelegateEventAware()) { - try { - logMethodCache.invoke(_delegate, event); - } catch (IllegalAccessException e) { - } catch (IllegalArgumentException e) { - } catch (InvocationTargetException e) { - } - } - } - - - public boolean isDelegateNull() { - return _delegate == null; - } - - public boolean isDelegateNOP() { - return _delegate instanceof NOPLogger; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Queue; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.event.EventRecodingLogger; +import org.slf4j.event.LoggingEvent; +import org.slf4j.event.SubstituteLoggingEvent; + +/** + * A logger implementation which logs via a delegate logger. By default, the delegate is a + * {@link NOPLogger}. However, a different delegate can be set at any time. + *

+ * See also the relevant + * error code documentation. + * + * @author Chetan Mehrotra + * @author Ceki Gulcu + */ +public class SubstituteLogger implements Logger { + + private final String name; + private volatile Logger _delegate; + private Boolean delegateEventAware; + private Method logMethodCache; + private EventRecodingLogger eventRecodingLogger; + private Queue eventQueue; + + private final boolean createdPostInitialization; + + public SubstituteLogger(String name, Queue eventQueue, boolean createdPostInitialization) { + this.name = name; + this.eventQueue = eventQueue; + this.createdPostInitialization = createdPostInitialization; + } + + public String getName() { + return name; + } + + public boolean isTraceEnabled() { + return delegate().isTraceEnabled(); + } + + public void trace(String msg) { + delegate().trace(msg); + } + + public void trace(String format, Object arg) { + delegate().trace(format, arg); + } + + public void trace(String format, Object arg1, Object arg2) { + delegate().trace(format, arg1, arg2); + } + + public void trace(String format, Object... arguments) { + delegate().trace(format, arguments); + } + + public void trace(String msg, Throwable t) { + delegate().trace(msg, t); + } + + public boolean isTraceEnabled(Marker marker) { + return delegate().isTraceEnabled(marker); + } + + public void trace(Marker marker, String msg) { + delegate().trace(marker, msg); + } + + public void trace(Marker marker, String format, Object arg) { + delegate().trace(marker, format, arg); + } + + public void trace(Marker marker, String format, Object arg1, Object arg2) { + delegate().trace(marker, format, arg1, arg2); + } + + public void trace(Marker marker, String format, Object... arguments) { + delegate().trace(marker, format, arguments); + } + + public void trace(Marker marker, String msg, Throwable t) { + delegate().trace(marker, msg, t); + } + + public boolean isDebugEnabled() { + return delegate().isDebugEnabled(); + } + + public void debug(String msg) { + delegate().debug(msg); + } + + public void debug(String format, Object arg) { + delegate().debug(format, arg); + } + + public void debug(String format, Object arg1, Object arg2) { + delegate().debug(format, arg1, arg2); + } + + public void debug(String format, Object... arguments) { + delegate().debug(format, arguments); + } + + public void debug(String msg, Throwable t) { + delegate().debug(msg, t); + } + + public boolean isDebugEnabled(Marker marker) { + return delegate().isDebugEnabled(marker); + } + + public void debug(Marker marker, String msg) { + delegate().debug(marker, msg); + } + + public void debug(Marker marker, String format, Object arg) { + delegate().debug(marker, format, arg); + } + + public void debug(Marker marker, String format, Object arg1, Object arg2) { + delegate().debug(marker, format, arg1, arg2); + } + + public void debug(Marker marker, String format, Object... arguments) { + delegate().debug(marker, format, arguments); + } + + public void debug(Marker marker, String msg, Throwable t) { + delegate().debug(marker, msg, t); + } + + public boolean isInfoEnabled() { + return delegate().isInfoEnabled(); + } + + public void info(String msg) { + delegate().info(msg); + } + + public void info(String format, Object arg) { + delegate().info(format, arg); + } + + public void info(String format, Object arg1, Object arg2) { + delegate().info(format, arg1, arg2); + } + + public void info(String format, Object... arguments) { + delegate().info(format, arguments); + } + + public void info(String msg, Throwable t) { + delegate().info(msg, t); + } + + public boolean isInfoEnabled(Marker marker) { + return delegate().isInfoEnabled(marker); + } + + public void info(Marker marker, String msg) { + delegate().info(marker, msg); + } + + public void info(Marker marker, String format, Object arg) { + delegate().info(marker, format, arg); + } + + public void info(Marker marker, String format, Object arg1, Object arg2) { + delegate().info(marker, format, arg1, arg2); + } + + public void info(Marker marker, String format, Object... arguments) { + delegate().info(marker, format, arguments); + } + + public void info(Marker marker, String msg, Throwable t) { + delegate().info(marker, msg, t); + } + + public boolean isWarnEnabled() { + return delegate().isWarnEnabled(); + } + + public void warn(String msg) { + delegate().warn(msg); + } + + public void warn(String format, Object arg) { + delegate().warn(format, arg); + } + + public void warn(String format, Object arg1, Object arg2) { + delegate().warn(format, arg1, arg2); + } + + public void warn(String format, Object... arguments) { + delegate().warn(format, arguments); + } + + public void warn(String msg, Throwable t) { + delegate().warn(msg, t); + } + + public boolean isWarnEnabled(Marker marker) { + return delegate().isWarnEnabled(marker); + } + + public void warn(Marker marker, String msg) { + delegate().warn(marker, msg); + } + + public void warn(Marker marker, String format, Object arg) { + delegate().warn(marker, format, arg); + } + + public void warn(Marker marker, String format, Object arg1, Object arg2) { + delegate().warn(marker, format, arg1, arg2); + } + + public void warn(Marker marker, String format, Object... arguments) { + delegate().warn(marker, format, arguments); + } + + public void warn(Marker marker, String msg, Throwable t) { + delegate().warn(marker, msg, t); + } + + public boolean isErrorEnabled() { + return delegate().isErrorEnabled(); + } + + public void error(String msg) { + delegate().error(msg); + } + + public void error(String format, Object arg) { + delegate().error(format, arg); + } + + public void error(String format, Object arg1, Object arg2) { + delegate().error(format, arg1, arg2); + } + + public void error(String format, Object... arguments) { + delegate().error(format, arguments); + } + + public void error(String msg, Throwable t) { + delegate().error(msg, t); + } + + public boolean isErrorEnabled(Marker marker) { + return delegate().isErrorEnabled(marker); + } + + public void error(Marker marker, String msg) { + delegate().error(marker, msg); + } + + public void error(Marker marker, String format, Object arg) { + delegate().error(marker, format, arg); + } + + public void error(Marker marker, String format, Object arg1, Object arg2) { + delegate().error(marker, format, arg1, arg2); + } + + public void error(Marker marker, String format, Object... arguments) { + delegate().error(marker, format, arguments); + } + + public void error(Marker marker, String msg, Throwable t) { + delegate().error(marker, msg, t); + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + SubstituteLogger that = (SubstituteLogger) o; + + if (!name.equals(that.name)) + return false; + + return true; + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + /** + * Return the delegate logger instance if set. Otherwise, return a {@link NOPLogger} + * instance. + */ + Logger delegate() { + if(_delegate != null) { + return _delegate; + } + if(createdPostInitialization) { + return NOPLogger.NOP_LOGGER; + } else { + return getEventRecordingLogger(); + } + } + + private Logger getEventRecordingLogger() { + if (eventRecodingLogger == null) { + eventRecodingLogger = new EventRecodingLogger(this, eventQueue); + } + return eventRecodingLogger; + } + + /** + * Typically called after the {@link org.slf4j.LoggerFactory} initialization phase is completed. + * @param delegate + */ + public void setDelegate(Logger delegate) { + this._delegate = delegate; + } + + public boolean isDelegateEventAware() { + if (delegateEventAware != null) + return delegateEventAware; + + try { + logMethodCache = _delegate.getClass().getMethod("log", LoggingEvent.class); + delegateEventAware = Boolean.TRUE; + } catch (NoSuchMethodException e) { + delegateEventAware = Boolean.FALSE; + } + return delegateEventAware; + } + + public void log(LoggingEvent event) { + if (isDelegateEventAware()) { + try { + logMethodCache.invoke(_delegate, event); + } catch (IllegalAccessException e) { + } catch (IllegalArgumentException e) { + } catch (InvocationTargetException e) { + } + } + } + + + public boolean isDelegateNull() { + return _delegate == null; + } + + public boolean isDelegateNOP() { + return _delegate instanceof NOPLogger; + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java b/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java old file mode 100644 new file mode 100755 index c5a6b0e..0fb6114 100755 --- a/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java @@ -1,80 +1,80 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.LinkedBlockingQueue; - -import org.slf4j.ILoggerFactory; -import org.slf4j.Logger; -import org.slf4j.event.SubstituteLoggingEvent; - -/** - * SubstituteLoggerFactory manages instances of {@link SubstituteLogger}. - * - * @author Ceki Gülcü - * @author Chetan Mehrotra - */ -public class SubstituteLoggerFactory implements ILoggerFactory { - - boolean postInitialization = false; - - final Map loggers = new HashMap(); - - final LinkedBlockingQueue eventQueue = new LinkedBlockingQueue(); - - synchronized public Logger getLogger(String name) { - SubstituteLogger logger = loggers.get(name); - if (logger == null) { - logger = new SubstituteLogger(name, eventQueue, postInitialization); - loggers.put(name, logger); - } - return logger; - } - - public List getLoggerNames() { - return new ArrayList(loggers.keySet()); - } - - public List getLoggers() { - return new ArrayList(loggers.values()); - } - - public LinkedBlockingQueue getEventQueue() { - return eventQueue; - } - - public void postInitialization() { - postInitialization = true; - } - - public void clear() { - loggers.clear(); - eventQueue.clear(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.LinkedBlockingQueue; + +import org.slf4j.ILoggerFactory; +import org.slf4j.Logger; +import org.slf4j.event.SubstituteLoggingEvent; + +/** + * SubstituteLoggerFactory manages instances of {@link SubstituteLogger}. + * + * @author Ceki Gülcü + * @author Chetan Mehrotra + */ +public class SubstituteLoggerFactory implements ILoggerFactory { + + boolean postInitialization = false; + + final Map loggers = new HashMap(); + + final LinkedBlockingQueue eventQueue = new LinkedBlockingQueue(); + + synchronized public Logger getLogger(String name) { + SubstituteLogger logger = loggers.get(name); + if (logger == null) { + logger = new SubstituteLogger(name, eventQueue, postInitialization); + loggers.put(name, logger); + } + return logger; + } + + public List getLoggerNames() { + return new ArrayList(loggers.keySet()); + } + + public List getLoggers() { + return new ArrayList(loggers.values()); + } + + public LinkedBlockingQueue getEventQueue() { + return eventQueue; + } + + public void postInitialization() { + postInitialization = true; + } + + public void clear() { + loggers.clear(); + eventQueue.clear(); + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/Util.java b/slf4j-api/src/main/java/org/slf4j/helpers/Util.java old file mode 100644 new file mode 100755 index 86493bf..0601784 100755 --- a/slf4j-api/src/main/java/org/slf4j/helpers/Util.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/Util.java @@ -1,133 +1,133 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -/** - * An internal utility class. - * - * @author Alexander Dorokhine - * @author Ceki Gülcü - */ -public final class Util { - - - private Util() { - } - - public static String safeGetSystemProperty(String key) { - if (key == null) - throw new IllegalArgumentException("null input"); - - String result = null; - try { - result = System.getProperty(key); - } catch (java.lang.SecurityException sm) { - ; // ignore - } - return result; - } - - public static boolean safeGetBooleanSystemProperty(String key) { - String value = safeGetSystemProperty(key); - if (value == null) - return false; - else - return value.equalsIgnoreCase("true"); - } - - /** - * In order to call {@link SecurityManager#getClassContext()}, which is a - * protected method, we add this wrapper which allows the method to be visible - * inside this package. - */ - private static final class ClassContextSecurityManager extends SecurityManager { - protected Class[] getClassContext() { - return super.getClassContext(); - } - } - - private static ClassContextSecurityManager SECURITY_MANAGER; - private static boolean SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED = false; - - private static ClassContextSecurityManager getSecurityManager() { - if (SECURITY_MANAGER != null) - return SECURITY_MANAGER; - else if (SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED) - return null; - else { - SECURITY_MANAGER = safeCreateSecurityManager(); - SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED = true; - return SECURITY_MANAGER; - } - } - - private static ClassContextSecurityManager safeCreateSecurityManager() { - try { - return new ClassContextSecurityManager(); - } catch (java.lang.SecurityException sm) { - return null; - } - } - - /** - * Returns the name of the class which called the invoking method. - * - * @return the name of the class which called the invoking method. - */ - public static Class getCallingClass() { - ClassContextSecurityManager securityManager = getSecurityManager(); - if (securityManager == null) - return null; - Class[] trace = securityManager.getClassContext(); - String thisClassName = Util.class.getName(); - - // Advance until Util is found - int i; - for (i = 0; i < trace.length; i++) { - if (thisClassName.equals(trace[i].getName())) - break; - } - - // trace[i] = Util; trace[i+1] = caller; trace[i+2] = caller's caller - if (i >= trace.length || i + 2 >= trace.length) { - throw new IllegalStateException("Failed to find org.slf4j.helpers.Util or its caller in the stack; " + "this should not happen"); - } - - return trace[i + 2]; - } - - static final public void report(String msg, Throwable t) { - System.err.println(msg); - System.err.println("Reported exception:"); - t.printStackTrace(); - } - - static final public void report(String msg) { - System.err.println("SLF4J: " + msg); - } - - - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +/** + * An internal utility class. + * + * @author Alexander Dorokhine + * @author Ceki Gülcü + */ +public final class Util { + + + private Util() { + } + + public static String safeGetSystemProperty(String key) { + if (key == null) + throw new IllegalArgumentException("null input"); + + String result = null; + try { + result = System.getProperty(key); + } catch (java.lang.SecurityException sm) { + ; // ignore + } + return result; + } + + public static boolean safeGetBooleanSystemProperty(String key) { + String value = safeGetSystemProperty(key); + if (value == null) + return false; + else + return value.equalsIgnoreCase("true"); + } + + /** + * In order to call {@link SecurityManager#getClassContext()}, which is a + * protected method, we add this wrapper which allows the method to be visible + * inside this package. + */ + private static final class ClassContextSecurityManager extends SecurityManager { + protected Class[] getClassContext() { + return super.getClassContext(); + } + } + + private static ClassContextSecurityManager SECURITY_MANAGER; + private static boolean SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED = false; + + private static ClassContextSecurityManager getSecurityManager() { + if (SECURITY_MANAGER != null) + return SECURITY_MANAGER; + else if (SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED) + return null; + else { + SECURITY_MANAGER = safeCreateSecurityManager(); + SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED = true; + return SECURITY_MANAGER; + } + } + + private static ClassContextSecurityManager safeCreateSecurityManager() { + try { + return new ClassContextSecurityManager(); + } catch (java.lang.SecurityException sm) { + return null; + } + } + + /** + * Returns the name of the class which called the invoking method. + * + * @return the name of the class which called the invoking method. + */ + public static Class getCallingClass() { + ClassContextSecurityManager securityManager = getSecurityManager(); + if (securityManager == null) + return null; + Class[] trace = securityManager.getClassContext(); + String thisClassName = Util.class.getName(); + + // Advance until Util is found + int i; + for (i = 0; i < trace.length; i++) { + if (thisClassName.equals(trace[i].getName())) + break; + } + + // trace[i] = Util; trace[i+1] = caller; trace[i+2] = caller's caller + if (i >= trace.length || i + 2 >= trace.length) { + throw new IllegalStateException("Failed to find org.slf4j.helpers.Util or its caller in the stack; " + "this should not happen"); + } + + return trace[i + 2]; + } + + static final public void report(String msg, Throwable t) { + System.err.println(msg); + System.err.println("Reported exception:"); + t.printStackTrace(); + } + + static final public void report(String msg) { + System.err.println("SLF4J: " + msg); + } + + + +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/package.html b/slf4j-api/src/main/java/org/slf4j/helpers/package.html index 9d7c8c3..f223543 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/package.html +++ b/slf4j-api/src/main/java/org/slf4j/helpers/package.html @@ -1,16 +1,16 @@ - - - - - - - - - - - -

Helper classes.

- -
- - + + + + + + + + + + + +

Helper classes.

+ +
+ + diff --git a/slf4j-api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/slf4j-api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index cadfab5..2eda15c 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,73 +1,73 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; - -/** - * The binding of {@link org.slf4j.LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * This class is meant to provide a dummy StaticLoggerBinder to the slf4j-api module. - * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop, - * slf4j-log4j12 etc. - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder { - - /** - * The unique instance of this class. - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - /** - * Declare the version of the SLF4J API this implementation is compiled against. - * The value of this field is modified with each major release. - */ - // to avoid constant folding by the compiler, this field must *not* be final - public static String REQUESTED_API_VERSION = "1.6.99"; // !final - - private StaticLoggerBinder() { - throw new UnsupportedOperationException("This code should have never made it into slf4j-api.jar"); - } - - public ILoggerFactory getLoggerFactory() { - throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar"); - } - - public String getLoggerFactoryClassStr() { - throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar"); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; + +/** + * The binding of {@link org.slf4j.LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * This class is meant to provide a dummy StaticLoggerBinder to the slf4j-api module. + * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop, + * slf4j-log4j12 etc. + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder { + + /** + * The unique instance of this class. + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is modified with each major release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; // !final + + private StaticLoggerBinder() { + throw new UnsupportedOperationException("This code should have never made it into slf4j-api.jar"); + } + + public ILoggerFactory getLoggerFactory() { + throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar"); + } + + public String getLoggerFactoryClassStr() { + throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar"); + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/slf4j-api/src/main/java/org/slf4j/impl/StaticMDCBinder.java index e837a2b..b9560d4 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,67 +1,67 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.spi.MDCAdapter; - -/** - * This class is only a stub. Real implementations are found in - * each SLF4J binding project, e.g. slf4j-nop, slf4j-log4j12 etc. - * - * @author Ceki Gülcü - */ -public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - - private StaticMDCBinder() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } - - /** - * Return the singleton of this class. - * - * @return the StaticMDCBinder singleton - * @since 1.7.14 - */ - public static final StaticMDCBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link StaticMDCBinder}. - */ - public MDCAdapter getMDCA() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } - - public String getMDCAdapterClassStr() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.spi.MDCAdapter; + +/** + * This class is only a stub. Real implementations are found in + * each SLF4J binding project, e.g. slf4j-nop, slf4j-log4j12 etc. + * + * @author Ceki Gülcü + */ +public class StaticMDCBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + + /** + * Return the singleton of this class. + * + * @return the StaticMDCBinder singleton + * @since 1.7.14 + */ + public static final StaticMDCBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link StaticMDCBinder}. + */ + public MDCAdapter getMDCA() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + + public String getMDCAdapterClassStr() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/impl/StaticMarkerBinder.java b/slf4j-api/src/main/java/org/slf4j/impl/StaticMarkerBinder.java index c19914b..6669770 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,80 +1,80 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * This class is meant to provide a *dummy* StaticMarkerBinder to the slf4j-api module. - * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop, - * slf4j-simple, slf4j-log4j12 etc. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - private StaticMarkerBinder() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } - - /** - * Return the singleton of this class. - * - * @return the StaticMarkerBinder singleton - * @since 1.7.14 - */ - public static StaticMarkerBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * This class is meant to provide a *dummy* StaticMarkerBinder to the slf4j-api module. + * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop, + * slf4j-simple, slf4j-log4j12 etc. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + private StaticMarkerBinder() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + + /** + * Return the singleton of this class. + * + * @return the StaticMarkerBinder singleton + * @since 1.7.14 + */ + public static StaticMarkerBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/impl/package.html b/slf4j-api/src/main/java/org/slf4j/impl/package.html index f4311e3..6b84bad 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/package.html +++ b/slf4j-api/src/main/java/org/slf4j/impl/package.html @@ -1,17 +1,17 @@ - - - - - - - - - - - -

Implementations of core logging interfaces defined in the {@link - org.slf4j} package.

- -
- - + + + + + + + + + + + +

Implementations of core logging interfaces defined in the {@link + org.slf4j} package.

+ +
+ + diff --git a/slf4j-api/src/main/java/org/slf4j/package.html b/slf4j-api/src/main/java/org/slf4j/package.html index 4f407d0..e50b3ee 100644 --- a/slf4j-api/src/main/java/org/slf4j/package.html +++ b/slf4j-api/src/main/java/org/slf4j/package.html @@ -1,16 +1,16 @@ - - - - - - - - - - - -

Core logging interfaces.

- -
- - + + + + + + + + + + + +

Core logging interfaces.

+ +
+ + diff --git a/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java b/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java index 925e0ea..d338787 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java @@ -1,62 +1,62 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.spi; - -import org.slf4j.Logger; -import org.slf4j.Marker; - -/** - * An optional interface helping integration with logging systems capable of - * extracting location information. This interface is mainly used by SLF4J bridges - * such as jcl-over-slf4j, jul-to-slf4j and log4j-over-slf4j or {@link Logger} wrappers - * which need to provide hints so that the underlying logging system can extract - * the correct location information (method name, line number). - * - * @author Ceki Gulcu - * @since 1.3 - */ -public interface LocationAwareLogger extends Logger { - - // these constants should be in EventContants. However, in order to preserve binary backward compatibility - // we keep these constants here - final public int TRACE_INT = 00; - final public int DEBUG_INT = 10; - final public int INFO_INT = 20; - final public int WARN_INT = 30; - final public int ERROR_INT = 40; - - /** - * Printing method with support for location information. - * - * @param marker The marker to be used for this event, may be null. - * @param fqcn The fully qualified class name of the logger instance, - * typically the logger class, logger bridge or a logger wrapper. - * @param level One of the level integers defined in this interface - * @param message The message for the log event - * @param t Throwable associated with the log event, may be null. - */ - public void log(Marker marker, String fqcn, int level, String message, Object[] argArray, Throwable t); - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.spi; + +import org.slf4j.Logger; +import org.slf4j.Marker; + +/** + * An optional interface helping integration with logging systems capable of + * extracting location information. This interface is mainly used by SLF4J bridges + * such as jcl-over-slf4j, jul-to-slf4j and log4j-over-slf4j or {@link Logger} wrappers + * which need to provide hints so that the underlying logging system can extract + * the correct location information (method name, line number). + * + * @author Ceki Gulcu + * @since 1.3 + */ +public interface LocationAwareLogger extends Logger { + + // these constants should be in EventContants. However, in order to preserve binary backward compatibility + // we keep these constants here + final public int TRACE_INT = 00; + final public int DEBUG_INT = 10; + final public int INFO_INT = 20; + final public int WARN_INT = 30; + final public int ERROR_INT = 40; + + /** + * Printing method with support for location information. + * + * @param marker The marker to be used for this event, may be null. + * @param fqcn The fully qualified class name of the logger instance, + * typically the logger class, logger bridge or a logger wrapper. + * @param level One of the level integers defined in this interface + * @param message The message for the log event + * @param t Throwable associated with the log event, may be null. + */ + public void log(Marker marker, String fqcn, int level, String message, Object[] argArray, Throwable t); + +} diff --git a/slf4j-api/src/main/java/org/slf4j/spi/LoggerFactoryBinder.java b/slf4j-api/src/main/java/org/slf4j/spi/LoggerFactoryBinder.java index 923f8a0..9316b4d 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/LoggerFactoryBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/LoggerFactoryBinder.java @@ -1,57 +1,57 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.spi; - -import org.slf4j.ILoggerFactory; - -/** - * An internal interface which helps the static {@link org.slf4j.LoggerFactory} - * class bind with the appropriate {@link ILoggerFactory} instance. - * - * @author Ceki Gülcü - */ -public interface LoggerFactoryBinder { - - /** - * Return the instance of {@link ILoggerFactory} that - * {@link org.slf4j.LoggerFactory} class should bind to. - * - * @return the instance of {@link ILoggerFactory} that - * {@link org.slf4j.LoggerFactory} class should bind to. - */ - public ILoggerFactory getLoggerFactory(); - - /** - * The String form of the {@link ILoggerFactory} object that this - * LoggerFactoryBinder instance is intended to return. - * - *

This method allows the developer to interrogate this binder's intention - * which may be different from the {@link ILoggerFactory} instance it is able to - * yield in practice. The discrepancy should only occur in case of errors. - * - * @return the class name of the intended {@link ILoggerFactory} instance - */ - public String getLoggerFactoryClassStr(); -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.spi; + +import org.slf4j.ILoggerFactory; + +/** + * An internal interface which helps the static {@link org.slf4j.LoggerFactory} + * class bind with the appropriate {@link ILoggerFactory} instance. + * + * @author Ceki Gülcü + */ +public interface LoggerFactoryBinder { + + /** + * Return the instance of {@link ILoggerFactory} that + * {@link org.slf4j.LoggerFactory} class should bind to. + * + * @return the instance of {@link ILoggerFactory} that + * {@link org.slf4j.LoggerFactory} class should bind to. + */ + public ILoggerFactory getLoggerFactory(); + + /** + * The String form of the {@link ILoggerFactory} object that this + * LoggerFactoryBinder instance is intended to return. + * + *

This method allows the developer to interrogate this binder's intention + * which may be different from the {@link ILoggerFactory} instance it is able to + * yield in practice. The discrepancy should only occur in case of errors. + * + * @return the class name of the intended {@link ILoggerFactory} instance + */ + public String getLoggerFactoryClassStr(); +} diff --git a/slf4j-api/src/main/java/org/slf4j/spi/MDCAdapter.java b/slf4j-api/src/main/java/org/slf4j/spi/MDCAdapter.java index 0ccbb87..e3bb47a 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/MDCAdapter.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/MDCAdapter.java @@ -1,91 +1,91 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.spi; - -import java.util.Map; - -/** - * This interface abstracts the service offered by various MDC - * implementations. - * - * @author Ceki Gülcü - * @since 1.4.1 - */ -public interface MDCAdapter { - - /** - * Put a context value (the val parameter) as identified with - * the key parameter into the current thread's context map. - * The key parameter cannot be null. The val parameter - * can be null only if the underlying implementation supports it. - * - *

If the current thread does not have a context map it is created as a side - * effect of this call. - */ - public void put(String key, String val); - - /** - * Get the context identified by the key parameter. - * The key parameter cannot be null. - * - * @return the string value identified by the key parameter. - */ - public String get(String key); - - /** - * Remove the the context identified by the key parameter. - * The key parameter cannot be null. - * - *

- * This method does nothing if there is no previous value - * associated with key. - */ - public void remove(String key); - - /** - * Clear all entries in the MDC. - */ - public void clear(); - - /** - * Return a copy of the current thread's context map, with keys and - * values of type String. Returned value may be null. - * - * @return A copy of the current thread's context map. May be null. - * @since 1.5.1 - */ - public Map getCopyOfContextMap(); - - /** - * Set the current thread's context map by first clearing any existing - * map and then copying the map passed as parameter. The context map - * parameter must only contain keys and values of type String. - * - * @param contextMap must contain only keys and values of type String - * - * @since 1.5.1 - */ - public void setContextMap(Map contextMap); -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.spi; + +import java.util.Map; + +/** + * This interface abstracts the service offered by various MDC + * implementations. + * + * @author Ceki Gülcü + * @since 1.4.1 + */ +public interface MDCAdapter { + + /** + * Put a context value (the val parameter) as identified with + * the key parameter into the current thread's context map. + * The key parameter cannot be null. The val parameter + * can be null only if the underlying implementation supports it. + * + *

If the current thread does not have a context map it is created as a side + * effect of this call. + */ + public void put(String key, String val); + + /** + * Get the context identified by the key parameter. + * The key parameter cannot be null. + * + * @return the string value identified by the key parameter. + */ + public String get(String key); + + /** + * Remove the the context identified by the key parameter. + * The key parameter cannot be null. + * + *

+ * This method does nothing if there is no previous value + * associated with key. + */ + public void remove(String key); + + /** + * Clear all entries in the MDC. + */ + public void clear(); + + /** + * Return a copy of the current thread's context map, with keys and + * values of type String. Returned value may be null. + * + * @return A copy of the current thread's context map. May be null. + * @since 1.5.1 + */ + public Map getCopyOfContextMap(); + + /** + * Set the current thread's context map by first clearing any existing + * map and then copying the map passed as parameter. The context map + * parameter must only contain keys and values of type String. + * + * @param contextMap must contain only keys and values of type String + * + * @since 1.5.1 + */ + public void setContextMap(Map contextMap); +} diff --git a/slf4j-api/src/main/java/org/slf4j/spi/MarkerFactoryBinder.java b/slf4j-api/src/main/java/org/slf4j/spi/MarkerFactoryBinder.java index 19e34bd..ce1cc31 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/MarkerFactoryBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/MarkerFactoryBinder.java @@ -1,57 +1,57 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.spi; - -import org.slf4j.IMarkerFactory; - -/** - * An internal interface which helps the static {@link org.slf4j.MarkerFactory} - * class bind with the appropriate {@link IMarkerFactory} instance. - * - * @author Ceki Gülcü - */ -public interface MarkerFactoryBinder { - - /** - * Return the instance of {@link IMarkerFactory} that - * {@link org.slf4j.MarkerFactory} class should bind to. - * - * @return the instance of {@link IMarkerFactory} that - * {@link org.slf4j.MarkerFactory} class should bind to. - */ - public IMarkerFactory getMarkerFactory(); - - /** - * The String form of the {@link IMarkerFactory} object that this - * MarkerFactoryBinder instance is intended to return. - * - *

This method allows the developer to interrogate this binder's intention - * which may be different from the {@link IMarkerFactory} instance it is able to - * return. Such a discrepancy should only occur in case of errors. - * - * @return the class name of the intended {@link IMarkerFactory} instance - */ - public String getMarkerFactoryClassStr(); -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.spi; + +import org.slf4j.IMarkerFactory; + +/** + * An internal interface which helps the static {@link org.slf4j.MarkerFactory} + * class bind with the appropriate {@link IMarkerFactory} instance. + * + * @author Ceki Gülcü + */ +public interface MarkerFactoryBinder { + + /** + * Return the instance of {@link IMarkerFactory} that + * {@link org.slf4j.MarkerFactory} class should bind to. + * + * @return the instance of {@link IMarkerFactory} that + * {@link org.slf4j.MarkerFactory} class should bind to. + */ + public IMarkerFactory getMarkerFactory(); + + /** + * The String form of the {@link IMarkerFactory} object that this + * MarkerFactoryBinder instance is intended to return. + * + *

This method allows the developer to interrogate this binder's intention + * which may be different from the {@link IMarkerFactory} instance it is able to + * return. Such a discrepancy should only occur in case of errors. + * + * @return the class name of the intended {@link IMarkerFactory} instance + */ + public String getMarkerFactoryClassStr(); +} diff --git a/slf4j-api/src/main/java/org/slf4j/spi/package.html b/slf4j-api/src/main/java/org/slf4j/spi/package.html index 242f19d..13ea892 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/package.html +++ b/slf4j-api/src/main/java/org/slf4j/spi/package.html @@ -1,8 +1,8 @@ - - - - -Classes and interfaces which are internal to SLF4J. Under most -circumstances SLF4J users should be oblivious even to the existence of -this package. + + + + +Classes and interfaces which are internal to SLF4J. Under most +circumstances SLF4J users should be oblivious even to the existence of +this package. diff --git a/slf4j-api/src/main/resources/META-INF/MANIFEST.MF b/slf4j-api/src/main/resources/META-INF/MANIFEST.MF old file mode 100644 new file mode 100755 index def3812..bd79f8b 100755 --- a/slf4j-api/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-api/src/main/resources/META-INF/MANIFEST.MF @@ -1,11 +1,11 @@ -Implementation-Title: slf4j-api -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.api -Bundle-Name: slf4j-api -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.slf4j;version=${parsedVersion.osgiVersion}, - org.slf4j.spi;version=${parsedVersion.osgiVersion}, - org.slf4j.helpers;version=${parsedVersion.osgiVersion}, - org.slf4j.event;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j.impl;version=${slf4j.api.minimum.compatible.version} +Implementation-Title: slf4j-api +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.api +Bundle-Name: slf4j-api +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.slf4j;version=${parsedVersion.osgiVersion}, + org.slf4j.spi;version=${parsedVersion.osgiVersion}, + org.slf4j.helpers;version=${parsedVersion.osgiVersion}, + org.slf4j.event;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j.impl;version=${slf4j.api.minimum.compatible.version} diff --git a/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java b/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java index 218262b..473b574 100644 --- a/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java +++ b/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java @@ -1,208 +1,208 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import static org.junit.Assert.*; - -import java.util.Iterator; - -import org.junit.Test; -import org.slf4j.helpers.BasicMarkerFactory; - -/** - * Unit test BasicMarker - * - * @author Ceki Gülcü - * @author Joern Huxhorn - */ -public class BasicMarkerTest { - static final String BLUE_STR = "BLUE"; - static final String RED_STR = "RED"; - static final String GREEN_STR = "GREEN"; - static final String COMP_STR = "COMP"; - static final String MULTI_COMP_STR = "MULTI_COMP"; - static final String PARENT_MARKER_STR = "PARENT_MARKER"; - static final String CHILD_MARKER_STR = "CHILD_MARKER"; - static final String NOT_CONTAINED_MARKER_STR = "NOT_CONTAINED"; - - final IMarkerFactory factory; - final Marker blue; - final Marker red; - final Marker green; - final Marker comp; - final Marker multiComp; - - short diff = Differentiator.getDiffentiator(); - - public BasicMarkerTest() { - factory = new BasicMarkerFactory(); - - blue = factory.getMarker(BLUE_STR); - red = factory.getMarker(RED_STR); - green = factory.getMarker(GREEN_STR); - comp = factory.getMarker(COMP_STR); - comp.add(blue); - - multiComp = factory.getMarker(MULTI_COMP_STR); - multiComp.add(green); - multiComp.add(comp); - } - - @Test - public void testPrimitive() { - assertEquals(BLUE_STR, blue.getName()); - assertTrue(blue.contains(blue)); - - Marker blue2 = factory.getMarker(BLUE_STR); - assertEquals(BLUE_STR, blue2.getName()); - assertEquals(blue, blue2); - assertTrue(blue.contains(blue2)); - assertTrue(blue2.contains(blue)); - } - - @Test - public void testPrimitiveByName() { - assertTrue(blue.contains(BLUE_STR)); - } - - @Test - public void testComposite() { - assertTrue(comp.contains(comp)); - assertTrue(comp.contains(blue)); - } - - @Test - public void testCompositeByName() { - assertTrue(comp.contains(COMP_STR)); - assertTrue(comp.contains(BLUE_STR)); - } - - @Test - public void testMultiComposite() { - assertTrue(multiComp.contains(comp)); - assertTrue(multiComp.contains(blue)); - assertTrue(multiComp.contains(green)); - assertFalse(multiComp.contains(red)); - } - - @Test - public void testMultiCompositeByName() { - assertTrue(multiComp.contains(COMP_STR)); - assertTrue(multiComp.contains(BLUE_STR)); - assertTrue(multiComp.contains(GREEN_STR)); - assertFalse(multiComp.contains(RED_STR)); - } - - @Test - public void testMultiAdd() { - Marker parent = factory.getMarker(PARENT_MARKER_STR); - Marker child = factory.getMarker(CHILD_MARKER_STR); - for (int i = 0; i < 10; i++) { - parent.add(child); - } - - // check that the child was added once and only once - Iterator iterator = parent.iterator(); - assertTrue(iterator.hasNext()); - assertEquals(CHILD_MARKER_STR, iterator.next().toString()); - assertFalse(iterator.hasNext()); - } - - @Test - public void testAddRemove() { - final String NEW_PREFIX = "NEW_"; - Marker parent = factory.getMarker(NEW_PREFIX + PARENT_MARKER_STR); - Marker child = factory.getMarker(NEW_PREFIX + CHILD_MARKER_STR); - assertFalse(parent.contains(child)); - assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR)); - assertFalse(parent.remove(child)); - - parent.add(child); - - assertTrue(parent.contains(child)); - assertTrue(parent.contains(NEW_PREFIX + CHILD_MARKER_STR)); - - assertTrue(parent.remove(child)); - - assertFalse(parent.contains(child)); - assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR)); - assertFalse(parent.remove(child)); - } - - @Test - public void testSelfRecursion() { - final String diffPrefix = "NEW_" + diff; - final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR; - final String NOT_CONTAINED_NAME = diffPrefix + NOT_CONTAINED_MARKER_STR; - Marker parent = factory.getMarker(PARENT_NAME); - Marker notContained = factory.getMarker(NOT_CONTAINED_NAME); - parent.add(parent); - assertTrue(parent.contains(parent)); - assertTrue(parent.contains(PARENT_NAME)); - assertFalse(parent.contains(notContained)); - assertFalse(parent.contains(NOT_CONTAINED_MARKER_STR)); - } - - @Test - public void testIndirectRecursion() { - final String diffPrefix = "NEW_" + diff; - final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR; - final String CHILD_NAME = diffPrefix + CHILD_MARKER_STR; - final String NOT_CONTAINED_NAME = diffPrefix + NOT_CONTAINED_MARKER_STR; - - Marker parent = factory.getMarker(PARENT_NAME); - Marker child = factory.getMarker(CHILD_NAME); - Marker notContained = factory.getMarker(NOT_CONTAINED_NAME); - - parent.add(child); - child.add(parent); - assertTrue(parent.contains(parent)); - assertTrue(parent.contains(child)); - assertTrue(parent.contains(PARENT_NAME)); - assertTrue(parent.contains(CHILD_NAME)); - assertFalse(parent.contains(notContained)); - assertFalse(parent.contains(NOT_CONTAINED_MARKER_STR)); - } - - @Test - public void testHomonyms() { - final String diffPrefix = "homonym" + diff; - final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR; - final String CHILD_NAME = diffPrefix + CHILD_MARKER_STR; - Marker parent = factory.getMarker(PARENT_NAME); - Marker child = factory.getMarker(CHILD_NAME); - parent.add(child); - - IMarkerFactory otherFactory = new BasicMarkerFactory(); - Marker otherParent = otherFactory.getMarker(PARENT_NAME); - Marker otherChild = otherFactory.getMarker(CHILD_NAME); - - assertTrue(parent.contains(otherParent)); - assertTrue(parent.contains(otherChild)); - - assertTrue(parent.remove(otherChild)); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import static org.junit.Assert.*; + +import java.util.Iterator; + +import org.junit.Test; +import org.slf4j.helpers.BasicMarkerFactory; + +/** + * Unit test BasicMarker + * + * @author Ceki Gülcü + * @author Joern Huxhorn + */ +public class BasicMarkerTest { + static final String BLUE_STR = "BLUE"; + static final String RED_STR = "RED"; + static final String GREEN_STR = "GREEN"; + static final String COMP_STR = "COMP"; + static final String MULTI_COMP_STR = "MULTI_COMP"; + static final String PARENT_MARKER_STR = "PARENT_MARKER"; + static final String CHILD_MARKER_STR = "CHILD_MARKER"; + static final String NOT_CONTAINED_MARKER_STR = "NOT_CONTAINED"; + + final IMarkerFactory factory; + final Marker blue; + final Marker red; + final Marker green; + final Marker comp; + final Marker multiComp; + + short diff = Differentiator.getDiffentiator(); + + public BasicMarkerTest() { + factory = new BasicMarkerFactory(); + + blue = factory.getMarker(BLUE_STR); + red = factory.getMarker(RED_STR); + green = factory.getMarker(GREEN_STR); + comp = factory.getMarker(COMP_STR); + comp.add(blue); + + multiComp = factory.getMarker(MULTI_COMP_STR); + multiComp.add(green); + multiComp.add(comp); + } + + @Test + public void testPrimitive() { + assertEquals(BLUE_STR, blue.getName()); + assertTrue(blue.contains(blue)); + + Marker blue2 = factory.getMarker(BLUE_STR); + assertEquals(BLUE_STR, blue2.getName()); + assertEquals(blue, blue2); + assertTrue(blue.contains(blue2)); + assertTrue(blue2.contains(blue)); + } + + @Test + public void testPrimitiveByName() { + assertTrue(blue.contains(BLUE_STR)); + } + + @Test + public void testComposite() { + assertTrue(comp.contains(comp)); + assertTrue(comp.contains(blue)); + } + + @Test + public void testCompositeByName() { + assertTrue(comp.contains(COMP_STR)); + assertTrue(comp.contains(BLUE_STR)); + } + + @Test + public void testMultiComposite() { + assertTrue(multiComp.contains(comp)); + assertTrue(multiComp.contains(blue)); + assertTrue(multiComp.contains(green)); + assertFalse(multiComp.contains(red)); + } + + @Test + public void testMultiCompositeByName() { + assertTrue(multiComp.contains(COMP_STR)); + assertTrue(multiComp.contains(BLUE_STR)); + assertTrue(multiComp.contains(GREEN_STR)); + assertFalse(multiComp.contains(RED_STR)); + } + + @Test + public void testMultiAdd() { + Marker parent = factory.getMarker(PARENT_MARKER_STR); + Marker child = factory.getMarker(CHILD_MARKER_STR); + for (int i = 0; i < 10; i++) { + parent.add(child); + } + + // check that the child was added once and only once + Iterator iterator = parent.iterator(); + assertTrue(iterator.hasNext()); + assertEquals(CHILD_MARKER_STR, iterator.next().toString()); + assertFalse(iterator.hasNext()); + } + + @Test + public void testAddRemove() { + final String NEW_PREFIX = "NEW_"; + Marker parent = factory.getMarker(NEW_PREFIX + PARENT_MARKER_STR); + Marker child = factory.getMarker(NEW_PREFIX + CHILD_MARKER_STR); + assertFalse(parent.contains(child)); + assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR)); + assertFalse(parent.remove(child)); + + parent.add(child); + + assertTrue(parent.contains(child)); + assertTrue(parent.contains(NEW_PREFIX + CHILD_MARKER_STR)); + + assertTrue(parent.remove(child)); + + assertFalse(parent.contains(child)); + assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR)); + assertFalse(parent.remove(child)); + } + + @Test + public void testSelfRecursion() { + final String diffPrefix = "NEW_" + diff; + final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR; + final String NOT_CONTAINED_NAME = diffPrefix + NOT_CONTAINED_MARKER_STR; + Marker parent = factory.getMarker(PARENT_NAME); + Marker notContained = factory.getMarker(NOT_CONTAINED_NAME); + parent.add(parent); + assertTrue(parent.contains(parent)); + assertTrue(parent.contains(PARENT_NAME)); + assertFalse(parent.contains(notContained)); + assertFalse(parent.contains(NOT_CONTAINED_MARKER_STR)); + } + + @Test + public void testIndirectRecursion() { + final String diffPrefix = "NEW_" + diff; + final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR; + final String CHILD_NAME = diffPrefix + CHILD_MARKER_STR; + final String NOT_CONTAINED_NAME = diffPrefix + NOT_CONTAINED_MARKER_STR; + + Marker parent = factory.getMarker(PARENT_NAME); + Marker child = factory.getMarker(CHILD_NAME); + Marker notContained = factory.getMarker(NOT_CONTAINED_NAME); + + parent.add(child); + child.add(parent); + assertTrue(parent.contains(parent)); + assertTrue(parent.contains(child)); + assertTrue(parent.contains(PARENT_NAME)); + assertTrue(parent.contains(CHILD_NAME)); + assertFalse(parent.contains(notContained)); + assertFalse(parent.contains(NOT_CONTAINED_MARKER_STR)); + } + + @Test + public void testHomonyms() { + final String diffPrefix = "homonym" + diff; + final String PARENT_NAME = diffPrefix + PARENT_MARKER_STR; + final String CHILD_NAME = diffPrefix + CHILD_MARKER_STR; + Marker parent = factory.getMarker(PARENT_NAME); + Marker child = factory.getMarker(CHILD_NAME); + parent.add(child); + + IMarkerFactory otherFactory = new BasicMarkerFactory(); + Marker otherParent = otherFactory.getMarker(PARENT_NAME); + Marker otherChild = otherFactory.getMarker(CHILD_NAME); + + assertTrue(parent.contains(otherParent)); + assertTrue(parent.contains(otherChild)); + + assertTrue(parent.remove(otherChild)); + } + +} diff --git a/slf4j-api/src/test/java/org/slf4j/Differentiator.java b/slf4j-api/src/test/java/org/slf4j/Differentiator.java index 205a7b4..09b9a35 100644 --- a/slf4j-api/src/test/java/org/slf4j/Differentiator.java +++ b/slf4j-api/src/test/java/org/slf4j/Differentiator.java @@ -1,37 +1,37 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -package org.slf4j; - -import java.util.Random; - -public class Differentiator { - - static Random random = new Random(System.currentTimeMillis()); - - static public short getDiffentiator() { - return (short) random.nextInt(Short.MAX_VALUE); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +package org.slf4j; + +import java.util.Random; + +public class Differentiator { + + static Random random = new Random(System.currentTimeMillis()); + + static public short getDiffentiator() { + return (short) random.nextInt(Short.MAX_VALUE); + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/DoubleCheckedInt.java b/slf4j-api/src/test/java/org/slf4j/DoubleCheckedInt.java old file mode 100644 new file mode 100755 index 2978ee0..9aa86b0 100755 --- a/slf4j-api/src/test/java/org/slf4j/DoubleCheckedInt.java +++ b/slf4j-api/src/test/java/org/slf4j/DoubleCheckedInt.java @@ -1,141 +1,141 @@ -package org.slf4j; - -import java.util.concurrent.BrokenBarrierException; -import java.util.concurrent.CyclicBarrier; - -/** - * This class demonstrates that threads accessing the STATE variable always see a consistent value. - * - * During ongoing initialization the observed value is either ONGOING_INITIALIZATION - * or one of {SUCCESS, FAILURE}. - * - * Post initialization the observed value is always one of {SUCCESS, FAILURE}. - * - * See also http://jira.qos.ch/browse/SLF4J-167 - * - * @author ceki - * - */ -public class DoubleCheckedInt { - - final static int THREAD_COUNT = 10 + Runtime.getRuntime().availableProcessors() * 2; - final static int UNINITIALIZED_STATE = 0; - final static int ONGOING_INITIALIZATION = 1; - final static int SUCCESS = 2; - final static int FAILURE = 3; - final static int NUMBER_OF_STATES = FAILURE + 1; - - private static int STATE = UNINITIALIZED_STATE; - - public static int getState() { - if (STATE == 0) { - synchronized (DoubleCheckedInt.class) { - if (STATE == UNINITIALIZED_STATE) { - STATE = ONGOING_INITIALIZATION; - long r = System.nanoTime(); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } - if (r % 2 == 0) { - STATE = SUCCESS; - } else { - STATE = FAILURE; - } - } - } - } - return STATE; - } - - static public void main(String[] args) throws InterruptedException, BrokenBarrierException { - StateAccessingThread[] preInitializationThreads = harness(); - check(preInitializationThreads, false); - - System.out.println("============"); - StateAccessingThread[] postInitializationThreads = harness(); - check(postInitializationThreads, true); - } - - private static StateAccessingThread[] harness() throws InterruptedException, BrokenBarrierException { - StateAccessingThread[] threads = new StateAccessingThread[THREAD_COUNT]; - final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); - for (int i = 0; i < THREAD_COUNT; i++) { - threads[i] = new StateAccessingThread(barrier); - threads[i].start(); - } - - barrier.await(); - for (int i = 0; i < THREAD_COUNT; i++) { - threads[i].join(); - } - return threads; - } - - private static void check(StateAccessingThread[] threads, boolean postInit) { - - int[] stateCount = getStateCount(threads); - printStateCount(stateCount); - - if (stateCount[UNINITIALIZED_STATE] != 0) { - throw new IllegalStateException("getState() should never return a zero value"); - } - - if (stateCount[SUCCESS] != 0 && stateCount[FAILURE] != 0) { - throw new IllegalStateException("getState() should return consistent values"); - } - - if (postInit) { - if (stateCount[SUCCESS] != THREAD_COUNT && stateCount[FAILURE] != THREAD_COUNT) { - throw new IllegalStateException("getState() should return consistent values"); - } - } - - } - - private static void printStateCount(int[] stateCount) { - for (int i = 0; i < NUMBER_OF_STATES; i++) { - switch (i) { - case UNINITIALIZED_STATE: - System.out.println("UNINITIALIZED_STATE count: " + stateCount[i]); - break; - case ONGOING_INITIALIZATION: - System.out.println("ONGOING_INITIALIZATION count: " + stateCount[i]); - break; - case SUCCESS: - System.out.println("SUCCESS count: " + stateCount[i]); - break; - case FAILURE: - System.out.println("FAILURE count: " + stateCount[i]); - break; - } - } - } - - private static int[] getStateCount(StateAccessingThread[] threads) { - int[] valCount = new int[NUMBER_OF_STATES]; - for (int i = 0; i < threads.length; i++) { - int val = threads[i].state; - valCount[val] = valCount[val] + 1; - } - return valCount; - } - - static class StateAccessingThread extends Thread { - public int state = -1; - final CyclicBarrier barrier; - - StateAccessingThread(CyclicBarrier barrier) { - this.barrier = barrier; - } - - public void run() { - try { - barrier.await(); - } catch (Exception e) { - e.printStackTrace(); - } - state = DoubleCheckedInt.getState(); - } - }; -} +package org.slf4j; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +/** + * This class demonstrates that threads accessing the STATE variable always see a consistent value. + * + * During ongoing initialization the observed value is either ONGOING_INITIALIZATION + * or one of {SUCCESS, FAILURE}. + * + * Post initialization the observed value is always one of {SUCCESS, FAILURE}. + * + * See also http://jira.qos.ch/browse/SLF4J-167 + * + * @author ceki + * + */ +public class DoubleCheckedInt { + + final static int THREAD_COUNT = 10 + Runtime.getRuntime().availableProcessors() * 2; + final static int UNINITIALIZED_STATE = 0; + final static int ONGOING_INITIALIZATION = 1; + final static int SUCCESS = 2; + final static int FAILURE = 3; + final static int NUMBER_OF_STATES = FAILURE + 1; + + private static int STATE = UNINITIALIZED_STATE; + + public static int getState() { + if (STATE == 0) { + synchronized (DoubleCheckedInt.class) { + if (STATE == UNINITIALIZED_STATE) { + STATE = ONGOING_INITIALIZATION; + long r = System.nanoTime(); + try { + Thread.sleep(10); + } catch (InterruptedException e) { + } + if (r % 2 == 0) { + STATE = SUCCESS; + } else { + STATE = FAILURE; + } + } + } + } + return STATE; + } + + static public void main(String[] args) throws InterruptedException, BrokenBarrierException { + StateAccessingThread[] preInitializationThreads = harness(); + check(preInitializationThreads, false); + + System.out.println("============"); + StateAccessingThread[] postInitializationThreads = harness(); + check(postInitializationThreads, true); + } + + private static StateAccessingThread[] harness() throws InterruptedException, BrokenBarrierException { + StateAccessingThread[] threads = new StateAccessingThread[THREAD_COUNT]; + final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); + for (int i = 0; i < THREAD_COUNT; i++) { + threads[i] = new StateAccessingThread(barrier); + threads[i].start(); + } + + barrier.await(); + for (int i = 0; i < THREAD_COUNT; i++) { + threads[i].join(); + } + return threads; + } + + private static void check(StateAccessingThread[] threads, boolean postInit) { + + int[] stateCount = getStateCount(threads); + printStateCount(stateCount); + + if (stateCount[UNINITIALIZED_STATE] != 0) { + throw new IllegalStateException("getState() should never return a zero value"); + } + + if (stateCount[SUCCESS] != 0 && stateCount[FAILURE] != 0) { + throw new IllegalStateException("getState() should return consistent values"); + } + + if (postInit) { + if (stateCount[SUCCESS] != THREAD_COUNT && stateCount[FAILURE] != THREAD_COUNT) { + throw new IllegalStateException("getState() should return consistent values"); + } + } + + } + + private static void printStateCount(int[] stateCount) { + for (int i = 0; i < NUMBER_OF_STATES; i++) { + switch (i) { + case UNINITIALIZED_STATE: + System.out.println("UNINITIALIZED_STATE count: " + stateCount[i]); + break; + case ONGOING_INITIALIZATION: + System.out.println("ONGOING_INITIALIZATION count: " + stateCount[i]); + break; + case SUCCESS: + System.out.println("SUCCESS count: " + stateCount[i]); + break; + case FAILURE: + System.out.println("FAILURE count: " + stateCount[i]); + break; + } + } + } + + private static int[] getStateCount(StateAccessingThread[] threads) { + int[] valCount = new int[NUMBER_OF_STATES]; + for (int i = 0; i < threads.length; i++) { + int val = threads[i].state; + valCount[val] = valCount[val] + 1; + } + return valCount; + } + + static class StateAccessingThread extends Thread { + public int state = -1; + final CyclicBarrier barrier; + + StateAccessingThread(CyclicBarrier barrier) { + this.barrier = barrier; + } + + public void run() { + try { + barrier.await(); + } catch (Exception e) { + e.printStackTrace(); + } + state = DoubleCheckedInt.getState(); + } + }; +} diff --git a/slf4j-api/src/test/java/org/slf4j/LoggerAccessingThread.java b/slf4j-api/src/test/java/org/slf4j/LoggerAccessingThread.java old file mode 100644 new file mode 100755 index ec611d0..5d7084a 100755 --- a/slf4j-api/src/test/java/org/slf4j/LoggerAccessingThread.java +++ b/slf4j-api/src/test/java/org/slf4j/LoggerAccessingThread.java @@ -1,62 +1,62 @@ -/** - * Copyright (c) 2004-2016 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.util.List; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.atomic.AtomicLong; - -public class LoggerAccessingThread extends Thread { - private static int LOOP_LEN = 64; - - final CyclicBarrier barrier; - final int count; - final AtomicLong eventCount; - List loggerList; - - public LoggerAccessingThread(final CyclicBarrier barrier, List loggerList, final int count, final AtomicLong eventCount) { - this.barrier = barrier; - this.loggerList = loggerList; - this.count = count; - this.eventCount = eventCount; - } - - public void run() { - try { - barrier.await(); - } catch (Exception e) { - e.printStackTrace(); - } - - String loggerNamePrefix = this.getClass().getName(); - for (int i = 0; i < LOOP_LEN; i++) { - Logger logger = LoggerFactory.getLogger(loggerNamePrefix + "-" + count + "-" + i); - loggerList.add(logger); - Thread.yield(); - logger.info("in run method"); - eventCount.getAndIncrement(); - } - } -} +/** + * Copyright (c) 2004-2016 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.util.List; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.atomic.AtomicLong; + +public class LoggerAccessingThread extends Thread { + private static int LOOP_LEN = 64; + + final CyclicBarrier barrier; + final int count; + final AtomicLong eventCount; + List loggerList; + + public LoggerAccessingThread(final CyclicBarrier barrier, List loggerList, final int count, final AtomicLong eventCount) { + this.barrier = barrier; + this.loggerList = loggerList; + this.count = count; + this.eventCount = eventCount; + } + + public void run() { + try { + barrier.await(); + } catch (Exception e) { + e.printStackTrace(); + } + + String loggerNamePrefix = this.getClass().getName(); + for (int i = 0; i < LOOP_LEN; i++) { + Logger logger = LoggerFactory.getLogger(loggerNamePrefix + "-" + count + "-" + i); + loggerList.add(logger); + Thread.yield(); + logger.info("in run method"); + eventCount.getAndIncrement(); + } + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java b/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java index 467278f..b161e7e 100644 --- a/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java +++ b/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java @@ -1,58 +1,58 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Random; - -import org.junit.Test; -import org.slf4j.helpers.BasicMarker; -import org.slf4j.helpers.NOPLogger; - -public class NoBindingTest { - - int diff = new Random().nextInt(10000); - - @Test - public void testLogger() { - Logger logger = LoggerFactory.getLogger(NoBindingTest.class); - logger.debug("hello" + diff); - assertTrue(logger instanceof NOPLogger); - } - - @Test - public void testMDC() { - MDC.put("k" + diff, "v"); - assertNull(MDC.get("k")); - } - - @Test - public void testMarker() { - Marker m = MarkerFactory.getMarker("a" + diff); - assertTrue(m instanceof BasicMarker); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Random; + +import org.junit.Test; +import org.slf4j.helpers.BasicMarker; +import org.slf4j.helpers.NOPLogger; + +public class NoBindingTest { + + int diff = new Random().nextInt(10000); + + @Test + public void testLogger() { + Logger logger = LoggerFactory.getLogger(NoBindingTest.class); + logger.debug("hello" + diff); + assertTrue(logger instanceof NOPLogger); + } + + @Test + public void testMDC() { + MDC.put("k" + diff, "v"); + assertNull(MDC.get("k")); + } + + @Test + public void testMarker() { + Marker m = MarkerFactory.getMarker("a" + diff); + assertTrue(m instanceof BasicMarker); + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/BasicMDCAdapterTest.java b/slf4j-api/src/test/java/org/slf4j/helpers/BasicMDCAdapterTest.java index 1c1d09e..1fbc823 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/BasicMDCAdapterTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/BasicMDCAdapterTest.java @@ -1,148 +1,148 @@ -/** - * Copyright (c) 2004-2013 QOS.ch, Copyright (C) 2015 Google Inc. - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.helpers; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.lang.Thread.UncaughtExceptionHandler; -import java.util.Map; - -import org.junit.After; -import org.junit.Test; -import org.slf4j.spi.MDCAdapter; - -/** - * Tests for {@link BasicMDCAdapter} - * - * @author Lukasz Cwik - */ -public class BasicMDCAdapterTest { - MDCAdapter mdc = new BasicMDCAdapter(); - - @After - public void tearDown() throws Exception { - mdc.clear(); - } - - @Test - public void testSettingAndGettingWithMDC() { - assertNull(mdc.get("testKey")); - mdc.put("testKey", "testValue"); - assertEquals(mdc.get("testKey"), "testValue"); - } - - @Test - public void testOverwritingAKeyInMDC() { - assertNull(mdc.get("testKey")); - mdc.put("testKey", "testValue"); - mdc.put("testKey", "differentTestValue"); - assertEquals(mdc.get("testKey"), "differentTestValue"); - } - - @Test - public void testClearingMDC() { - mdc.put("testKey", "testValue"); - assertFalse(mdc.getCopyOfContextMap().isEmpty()); - mdc.clear(); - assertNull(mdc.getCopyOfContextMap()); - } - - @Test - public void testGetCopyOfContextMapFromMDC() { - mdc.put("testKey", "testValue"); - Map copy = mdc.getCopyOfContextMap(); - mdc.put("anotherTestKey", "anotherTestValue"); - assertFalse(copy.size() == mdc.getCopyOfContextMap().size()); - } - - @Test - public void testMDCInheritsValuesFromParentThread() throws Exception { - mdc.put("parentKey", "parentValue"); - runAndWait(new Runnable() { - public void run() { - mdc.put("childKey", "childValue"); - assertEquals("parentValue", mdc.get("parentKey")); - } - }); - } - - @Test - public void testMDCDoesntGetValuesFromChildThread() throws Exception { - mdc.put("parentKey", "parentValue"); - runAndWait(new Runnable() { - public void run() { - mdc.put("childKey", "childValue"); - } - }); - assertEquals("parentValue", mdc.get("parentKey")); - assertNull(mdc.get("childKey")); - } - - @Test - public void testMDCChildThreadCanOverwriteParentThread() throws Exception { - mdc.put("sharedKey", "parentValue"); - runAndWait(new Runnable() { - public void run() { - assertEquals("parentValue", mdc.get("sharedKey")); - mdc.put("sharedKey", "childValue"); - assertEquals("childValue", mdc.get("sharedKey")); - } - }); - assertEquals("parentValue", mdc.get("sharedKey")); - } - - private void runAndWait(Runnable runnable) throws Exception { - RecordingExceptionHandler handler = new RecordingExceptionHandler(); - Thread thread = new Thread(runnable); - thread.setUncaughtExceptionHandler(handler); - thread.start(); - try { - thread.join(); - } catch (Throwable t) { - fail("Unexpected failure in child thread:" + t.getMessage()); - } - assertFalse(handler.getMessage(), handler.hadException()); - } - - /** A {@link UncaughtExceptionHandler} that records whether the thread threw an exception. */ - private static class RecordingExceptionHandler implements UncaughtExceptionHandler { - private Throwable exception; - - public void uncaughtException(Thread t, Throwable e) { - exception = e; - } - - boolean hadException() { - return exception != null; - } - - String getMessage() { - return exception != null ? exception.getMessage() : ""; - } - } -} +/** + * Copyright (c) 2004-2013 QOS.ch, Copyright (C) 2015 Google Inc. + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.helpers; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.lang.Thread.UncaughtExceptionHandler; +import java.util.Map; + +import org.junit.After; +import org.junit.Test; +import org.slf4j.spi.MDCAdapter; + +/** + * Tests for {@link BasicMDCAdapter} + * + * @author Lukasz Cwik + */ +public class BasicMDCAdapterTest { + MDCAdapter mdc = new BasicMDCAdapter(); + + @After + public void tearDown() throws Exception { + mdc.clear(); + } + + @Test + public void testSettingAndGettingWithMDC() { + assertNull(mdc.get("testKey")); + mdc.put("testKey", "testValue"); + assertEquals(mdc.get("testKey"), "testValue"); + } + + @Test + public void testOverwritingAKeyInMDC() { + assertNull(mdc.get("testKey")); + mdc.put("testKey", "testValue"); + mdc.put("testKey", "differentTestValue"); + assertEquals(mdc.get("testKey"), "differentTestValue"); + } + + @Test + public void testClearingMDC() { + mdc.put("testKey", "testValue"); + assertFalse(mdc.getCopyOfContextMap().isEmpty()); + mdc.clear(); + assertNull(mdc.getCopyOfContextMap()); + } + + @Test + public void testGetCopyOfContextMapFromMDC() { + mdc.put("testKey", "testValue"); + Map copy = mdc.getCopyOfContextMap(); + mdc.put("anotherTestKey", "anotherTestValue"); + assertFalse(copy.size() == mdc.getCopyOfContextMap().size()); + } + + @Test + public void testMDCInheritsValuesFromParentThread() throws Exception { + mdc.put("parentKey", "parentValue"); + runAndWait(new Runnable() { + public void run() { + mdc.put("childKey", "childValue"); + assertEquals("parentValue", mdc.get("parentKey")); + } + }); + } + + @Test + public void testMDCDoesntGetValuesFromChildThread() throws Exception { + mdc.put("parentKey", "parentValue"); + runAndWait(new Runnable() { + public void run() { + mdc.put("childKey", "childValue"); + } + }); + assertEquals("parentValue", mdc.get("parentKey")); + assertNull(mdc.get("childKey")); + } + + @Test + public void testMDCChildThreadCanOverwriteParentThread() throws Exception { + mdc.put("sharedKey", "parentValue"); + runAndWait(new Runnable() { + public void run() { + assertEquals("parentValue", mdc.get("sharedKey")); + mdc.put("sharedKey", "childValue"); + assertEquals("childValue", mdc.get("sharedKey")); + } + }); + assertEquals("parentValue", mdc.get("sharedKey")); + } + + private void runAndWait(Runnable runnable) throws Exception { + RecordingExceptionHandler handler = new RecordingExceptionHandler(); + Thread thread = new Thread(runnable); + thread.setUncaughtExceptionHandler(handler); + thread.start(); + try { + thread.join(); + } catch (Throwable t) { + fail("Unexpected failure in child thread:" + t.getMessage()); + } + assertFalse(handler.getMessage(), handler.hadException()); + } + + /** A {@link UncaughtExceptionHandler} that records whether the thread threw an exception. */ + private static class RecordingExceptionHandler implements UncaughtExceptionHandler { + private Throwable exception; + + public void uncaughtException(Thread t, Throwable e) { + exception = e; + } + + boolean hadException() { + return exception != null; + } + + String getMessage() { + return exception != null ? exception.getMessage() : ""; + } + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/BogoPerf.java b/slf4j-api/src/test/java/org/slf4j/helpers/BogoPerf.java index 587c231..86f7d67 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/BogoPerf.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/BogoPerf.java @@ -1,150 +1,150 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import junit.framework.AssertionFailedError; - -/** - * BogoPerf is used to check that the time required to perform a certain - * operation does not deteriorate over time. BogoPerf adjusts to the CPU speed - * and capabilities of the host. - * - * @author Ceki Gülcü - * - */ -public class BogoPerf { - - private static long NANOS_IN_ONE_SECOND = 1000 * 1000 * 1000; - private static int INITIAL_N = 1000; - private static int LAST_N = 100; - private static int SLACK_FACTOR = 3; - - static { - // let the JIT warm up - computeBogoIPS(INITIAL_N); - double bogo_ips = computeBogoIPS(INITIAL_N); - System.out.println("Host runs at " + bogo_ips + " BIPS"); - } - - /** - * Compute bogoInstructions per second - *

- * on a 3.2 Ghz Pentium D CPU (around 2007), we obtain about 9'000 bogoIPS. - * - * @param N - * number of bogoInstructions to average over in order to - * compute the result - * @return bogo Instructions Per Second - */ - private static double computeBogoIPS(int N) { - long begin = System.nanoTime(); - - for (int i = 0; i < N; i++) { - bogoInstruction(); - } - long end = System.nanoTime(); - - // duration - double D = end - begin; - // average duration per instruction - double avgDPIS = D / N; - // System.out.println(D + " nanos for " + N + " instructions"); - // System.out.println(avgD + " nanos per instruction"); - - double bogoIPS = NANOS_IN_ONE_SECOND / avgDPIS; - // System.out.println(bogoIPS + " bogoIPS"); - - return bogoIPS; - } - - private static void bogoInstruction() { - // use our own random number generator, independent of the host JDK - MyRandom myRandom = new MyRandom(100); - int len = 150; - int[] intArray = new int[len]; - for (int i = 0; i < len; i++) { - intArray[i] = myRandom.nextInt(); - } - // use our own sort algorithm, independent of the host JDK - BubbleSort.sort(intArray); - } - - /** - * Computed the BogoIPS for this host CPU. - * - * @return - */ - public static double currentBIPS() { - return computeBogoIPS(LAST_N); - } - - static double min(double a, double b) { - return (a <= b) ? a : b; - } - - /** - * Assertion used for values that decrease with faster CPUs, typically - * the time (duration) needed to perform a task. - * - * @param currentDuration - * @param referenceDuration - * @param referenceBIPS - * @throws AssertionFailedError - */ - public static void assertDuration(double currentDuration, long referenceDuration, double referenceBIPS) throws AssertionFailedError { - double ajustedDuration = adjustExpectedDuration(referenceDuration, referenceBIPS); - if (currentDuration > ajustedDuration * SLACK_FACTOR) { - throw new AssertionFailedError("current duration " + currentDuration + " exceeded expected " + ajustedDuration + " (adjusted reference), " - + referenceDuration + " (raw reference)"); - } - } - - /** - * Assertion used for values that increase with faster CPUs, typically - * the number of operations accomplished per unit of time. - * - * @param currentPerformance - * @param referencePerformance - * @param referenceBIPS - * @throws AssertionFailedError - */ - public static void assertPerformance(double currentPerformance, long referencePerformance, double referenceBIPS) throws AssertionFailedError { - double ajustedPerf = adjustExpectedPerformance(referencePerformance, referenceBIPS); - if (currentPerformance * SLACK_FACTOR < ajustedPerf) { - throw new AssertionFailedError(currentPerformance + " below expected " + ajustedPerf + " (adjusted), " + referencePerformance + " (raw)"); - } - } - - private static double adjustExpectedPerformance(long referenceDuration, double referenceBIPS) { - double currentBIPS = currentBIPS(); - return referenceDuration * (currentBIPS / referenceBIPS); - } - - private static double adjustExpectedDuration(long referenceDuration, double referenceBIPS) { - double currentBIPS = currentBIPS(); - System.out.println("currentBIPS=" + currentBIPS + " BIPS"); - return referenceDuration * (referenceBIPS / currentBIPS); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import junit.framework.AssertionFailedError; + +/** + * BogoPerf is used to check that the time required to perform a certain + * operation does not deteriorate over time. BogoPerf adjusts to the CPU speed + * and capabilities of the host. + * + * @author Ceki Gülcü + * + */ +public class BogoPerf { + + private static long NANOS_IN_ONE_SECOND = 1000 * 1000 * 1000; + private static int INITIAL_N = 1000; + private static int LAST_N = 100; + private static int SLACK_FACTOR = 3; + + static { + // let the JIT warm up + computeBogoIPS(INITIAL_N); + double bogo_ips = computeBogoIPS(INITIAL_N); + System.out.println("Host runs at " + bogo_ips + " BIPS"); + } + + /** + * Compute bogoInstructions per second + *

+ * on a 3.2 Ghz Pentium D CPU (around 2007), we obtain about 9'000 bogoIPS. + * + * @param N + * number of bogoInstructions to average over in order to + * compute the result + * @return bogo Instructions Per Second + */ + private static double computeBogoIPS(int N) { + long begin = System.nanoTime(); + + for (int i = 0; i < N; i++) { + bogoInstruction(); + } + long end = System.nanoTime(); + + // duration + double D = end - begin; + // average duration per instruction + double avgDPIS = D / N; + // System.out.println(D + " nanos for " + N + " instructions"); + // System.out.println(avgD + " nanos per instruction"); + + double bogoIPS = NANOS_IN_ONE_SECOND / avgDPIS; + // System.out.println(bogoIPS + " bogoIPS"); + + return bogoIPS; + } + + private static void bogoInstruction() { + // use our own random number generator, independent of the host JDK + MyRandom myRandom = new MyRandom(100); + int len = 150; + int[] intArray = new int[len]; + for (int i = 0; i < len; i++) { + intArray[i] = myRandom.nextInt(); + } + // use our own sort algorithm, independent of the host JDK + BubbleSort.sort(intArray); + } + + /** + * Computed the BogoIPS for this host CPU. + * + * @return + */ + public static double currentBIPS() { + return computeBogoIPS(LAST_N); + } + + static double min(double a, double b) { + return (a <= b) ? a : b; + } + + /** + * Assertion used for values that decrease with faster CPUs, typically + * the time (duration) needed to perform a task. + * + * @param currentDuration + * @param referenceDuration + * @param referenceBIPS + * @throws AssertionFailedError + */ + public static void assertDuration(double currentDuration, long referenceDuration, double referenceBIPS) throws AssertionFailedError { + double ajustedDuration = adjustExpectedDuration(referenceDuration, referenceBIPS); + if (currentDuration > ajustedDuration * SLACK_FACTOR) { + throw new AssertionFailedError("current duration " + currentDuration + " exceeded expected " + ajustedDuration + " (adjusted reference), " + + referenceDuration + " (raw reference)"); + } + } + + /** + * Assertion used for values that increase with faster CPUs, typically + * the number of operations accomplished per unit of time. + * + * @param currentPerformance + * @param referencePerformance + * @param referenceBIPS + * @throws AssertionFailedError + */ + public static void assertPerformance(double currentPerformance, long referencePerformance, double referenceBIPS) throws AssertionFailedError { + double ajustedPerf = adjustExpectedPerformance(referencePerformance, referenceBIPS); + if (currentPerformance * SLACK_FACTOR < ajustedPerf) { + throw new AssertionFailedError(currentPerformance + " below expected " + ajustedPerf + " (adjusted), " + referencePerformance + " (raw)"); + } + } + + private static double adjustExpectedPerformance(long referenceDuration, double referenceBIPS) { + double currentBIPS = currentBIPS(); + return referenceDuration * (currentBIPS / referenceBIPS); + } + + private static double adjustExpectedDuration(long referenceDuration, double referenceBIPS) { + double currentBIPS = currentBIPS(); + System.out.println("currentBIPS=" + currentBIPS + " BIPS"); + return referenceDuration * (referenceBIPS / currentBIPS); + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSort.java b/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSort.java index 5bd27fd..e8f7bcf 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSort.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSort.java @@ -1,51 +1,51 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -/** - * This class is used internally by BogoPerf, hence the package private - * (default) access. - * - * @author Ceki - */ -class BubbleSort { - - static void sort(int[] a) { - int len = a.length; - for (int i = 0; i < len - 1; i++) { - for (int j = 0; j < len - 1 - i; j++) { - if (a[j] > a[j + 1]) { - swap(a, j, j + 1); - } - } - } - } - - static void swap(int[] a, int i, int j) { - int t = a[i]; - a[i] = a[j]; - a[j] = t; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +/** + * This class is used internally by BogoPerf, hence the package private + * (default) access. + * + * @author Ceki + */ +class BubbleSort { + + static void sort(int[] a) { + int len = a.length; + for (int i = 0; i < len - 1; i++) { + for (int j = 0; j < len - 1 - i; j++) { + if (a[j] > a[j + 1]) { + swap(a, j, j + 1); + } + } + } + } + + static void swap(int[] a, int i, int j) { + int t = a[i]; + a[i] = a[j]; + a[j] = t; + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSortTest.java b/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSortTest.java index 403ecd6..204fdfb 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSortTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSortTest.java @@ -1,109 +1,109 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Random; - -import org.junit.Test; - -/** - * Test that our BubbleSort algorithm is correctly implemented. - * - * @author Ceki - * - */ -public class BubbleSortTest { - - @Test - public void testSmoke() { - int[] a = new int[] { 5, 3, 2, 7 }; - BubbleSort.sort(a); - int i = 0; - assertEquals(2, a[i++]); - assertEquals(3, a[i++]); - assertEquals(5, a[i++]); - assertEquals(7, a[i++]); - } - - @Test - public void testEmpty() { - int[] a = new int[] {}; - BubbleSort.sort(a); - } - - @Test - public void testSorted() { - int[] a = new int[] { 3, 30, 300, 3000 }; - BubbleSort.sort(a); - int i = 0; - assertEquals(3, a[i++]); - assertEquals(30, a[i++]); - assertEquals(300, a[i++]); - assertEquals(3000, a[i++]); - } - - @Test - public void testInverted() { - int[] a = new int[] { 3000, 300, 30, 3 }; - BubbleSort.sort(a); - int i = 0; - assertEquals(3, a[i++]); - assertEquals(30, a[i++]); - assertEquals(300, a[i++]); - assertEquals(3000, a[i++]); - } - - @Test - public void testWithSameEntry() { - int[] a = new int[] { 10, 20, 10, 20 }; - BubbleSort.sort(a); - int i = 0; - assertEquals(10, a[i++]); - assertEquals(10, a[i++]); - assertEquals(20, a[i++]); - assertEquals(20, a[i++]); - } - - @Test - public void testRandom() { - int len = 100; - Random random = new Random(156); - int[] a = new int[len]; - int[] witness = new int[len]; - for (int i = 0; i < len; i++) { - int r = random.nextInt(); - a[i] = r; - witness[i] = r; - } - BubbleSort.sort(a); - Arrays.sort(witness); - assertTrue(Arrays.equals(witness, a)); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Random; + +import org.junit.Test; + +/** + * Test that our BubbleSort algorithm is correctly implemented. + * + * @author Ceki + * + */ +public class BubbleSortTest { + + @Test + public void testSmoke() { + int[] a = new int[] { 5, 3, 2, 7 }; + BubbleSort.sort(a); + int i = 0; + assertEquals(2, a[i++]); + assertEquals(3, a[i++]); + assertEquals(5, a[i++]); + assertEquals(7, a[i++]); + } + + @Test + public void testEmpty() { + int[] a = new int[] {}; + BubbleSort.sort(a); + } + + @Test + public void testSorted() { + int[] a = new int[] { 3, 30, 300, 3000 }; + BubbleSort.sort(a); + int i = 0; + assertEquals(3, a[i++]); + assertEquals(30, a[i++]); + assertEquals(300, a[i++]); + assertEquals(3000, a[i++]); + } + + @Test + public void testInverted() { + int[] a = new int[] { 3000, 300, 30, 3 }; + BubbleSort.sort(a); + int i = 0; + assertEquals(3, a[i++]); + assertEquals(30, a[i++]); + assertEquals(300, a[i++]); + assertEquals(3000, a[i++]); + } + + @Test + public void testWithSameEntry() { + int[] a = new int[] { 10, 20, 10, 20 }; + BubbleSort.sort(a); + int i = 0; + assertEquals(10, a[i++]); + assertEquals(10, a[i++]); + assertEquals(20, a[i++]); + assertEquals(20, a[i++]); + } + + @Test + public void testRandom() { + int len = 100; + Random random = new Random(156); + int[] a = new int[len]; + int[] witness = new int[len]; + for (int i = 0; i < len; i++) { + int r = random.nextInt(); + a[i] = r; + witness[i] = r; + } + BubbleSort.sort(a); + Arrays.sort(witness); + assertTrue(Arrays.equals(witness, a)); + } + +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterPerfTest.java b/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterPerfTest.java old file mode 100644 new file mode 100755 index 7e8b057..bbdd07b 100755 --- a/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterPerfTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterPerfTest.java @@ -1,103 +1,103 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import java.text.MessageFormat; - -import org.junit.Ignore; -import org.junit.Test; - -@Ignore -public class MessageFormatterPerfTest { // extends TestCase { - - Integer i1 = new Integer(1); - Integer i2 = new Integer(2); - static long RUN_LENGTH = 100 * 1000; - // - static long REFERENCE_BIPS = 48416; - - public void XtestJDKFormatterPerf() { - jdkMessageFormatter(RUN_LENGTH); - double duration = jdkMessageFormatter(RUN_LENGTH); - System.out.println("jdk duration = " + duration + " nanos"); - } - - @Test - public void testSLF4JPerf_OneArg() { - slf4jMessageFormatter_OneArg(RUN_LENGTH); - double duration = slf4jMessageFormatter_OneArg(RUN_LENGTH); - System.out.println("duration=" + duration); - long referencePerf = 36; - BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS); - } - - @Test - public void testSLF4JPerf_TwoArg() { - slf4jMessageFormatter_TwoArg(RUN_LENGTH); - double duration = slf4jMessageFormatter_TwoArg(RUN_LENGTH); - long referencePerf = 60; - BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS); - } - - public double slf4jMessageFormatter_OneArg(long len) { - long start = System.nanoTime(); - for (int i = 0; i < len; i++) { - final FormattingTuple tp = MessageFormatter.format("This is some rather short message {} ", i1); - tp.getMessage(); - tp.getArgArray(); - tp.getThrowable(); - - MessageFormatter.format("This is some rather short message {} ", i1); - } - long end = System.nanoTime(); - return (end - start) / (1000 * 1000.0); - } - - public double slf4jMessageFormatter_TwoArg(long len) { - long start = System.nanoTime(); - for (int i = 0; i < len; i++) { - final FormattingTuple tp = MessageFormatter.format("This is some {} short message {} ", i1, i2); - tp.getMessage(); - tp.getArgArray(); - tp.getThrowable(); - } - long end = System.nanoTime(); - return (end - start) / (1000 * 1000.0); - } - - public double jdkMessageFormatter(long len) { - @SuppressWarnings("unused") - String s = ""; - s += ""; // keep compiler happy - long start = System.currentTimeMillis(); - Object[] oa = new Object[] { i1 }; - for (int i = 0; i < len; i++) { - s = MessageFormat.format("This is some rather short message {0}", oa); - } - long end = System.currentTimeMillis(); - return (1.0 * end - start); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import java.text.MessageFormat; + +import org.junit.Ignore; +import org.junit.Test; + +@Ignore +public class MessageFormatterPerfTest { // extends TestCase { + + Integer i1 = new Integer(1); + Integer i2 = new Integer(2); + static long RUN_LENGTH = 100 * 1000; + // + static long REFERENCE_BIPS = 48416; + + public void XtestJDKFormatterPerf() { + jdkMessageFormatter(RUN_LENGTH); + double duration = jdkMessageFormatter(RUN_LENGTH); + System.out.println("jdk duration = " + duration + " nanos"); + } + + @Test + public void testSLF4JPerf_OneArg() { + slf4jMessageFormatter_OneArg(RUN_LENGTH); + double duration = slf4jMessageFormatter_OneArg(RUN_LENGTH); + System.out.println("duration=" + duration); + long referencePerf = 36; + BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS); + } + + @Test + public void testSLF4JPerf_TwoArg() { + slf4jMessageFormatter_TwoArg(RUN_LENGTH); + double duration = slf4jMessageFormatter_TwoArg(RUN_LENGTH); + long referencePerf = 60; + BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS); + } + + public double slf4jMessageFormatter_OneArg(long len) { + long start = System.nanoTime(); + for (int i = 0; i < len; i++) { + final FormattingTuple tp = MessageFormatter.format("This is some rather short message {} ", i1); + tp.getMessage(); + tp.getArgArray(); + tp.getThrowable(); + + MessageFormatter.format("This is some rather short message {} ", i1); + } + long end = System.nanoTime(); + return (end - start) / (1000 * 1000.0); + } + + public double slf4jMessageFormatter_TwoArg(long len) { + long start = System.nanoTime(); + for (int i = 0; i < len; i++) { + final FormattingTuple tp = MessageFormatter.format("This is some {} short message {} ", i1, i2); + tp.getMessage(); + tp.getArgArray(); + tp.getThrowable(); + } + long end = System.nanoTime(); + return (end - start) / (1000 * 1000.0); + } + + public double jdkMessageFormatter(long len) { + @SuppressWarnings("unused") + String s = ""; + s += ""; // keep compiler happy + long start = System.currentTimeMillis(); + Object[] oa = new Object[] { i1 }; + for (int i = 0; i < len; i++) { + s = MessageFormat.format("This is some rather short message {0}", oa); + } + long end = System.currentTimeMillis(); + return (1.0 * end - start); + } + +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java b/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java old file mode 100644 new file mode 100755 index 76a1d19..37f98a1 100755 --- a/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java @@ -1,330 +1,330 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import java.util.Arrays; - -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * @author Ceki Gulcu - */ -public class MessageFormatterTest { - - Integer i1 = new Integer(1); - Integer i2 = new Integer(2); - Integer i3 = new Integer(3); - Integer[] ia0 = new Integer[] { i1, i2, i3 }; - Integer[] ia1 = new Integer[] { new Integer(10), new Integer(20), new Integer(30) }; - - String result; - - @Test - public void testNull() { - result = MessageFormatter.format(null, i1).getMessage(); - assertEquals(null, result); - } - - @Test - public void nullParametersShouldBeHandledWithoutBarfing() { - result = MessageFormatter.format("Value is {}.", null).getMessage(); - assertEquals("Value is null.", result); - - result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, null).getMessage(); - assertEquals("Val1 is null, val2 is null.", result); - - result = MessageFormatter.format("Val1 is {}, val2 is {}.", i1, null).getMessage(); - assertEquals("Val1 is 1, val2 is null.", result); - - result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, i2).getMessage(); - assertEquals("Val1 is null, val2 is 2.", result); - - result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, null }).getMessage(); - assertEquals("Val1 is null, val2 is null, val3 is null", result); - - result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, i2, i3 }).getMessage(); - assertEquals("Val1 is null, val2 is 2, val3 is 3", result); - - result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, i3 }).getMessage(); - assertEquals("Val1 is null, val2 is null, val3 is 3", result); - } - - @Test - public void verifyOneParameterIsHandledCorrectly() { - result = MessageFormatter.format("Value is {}.", i3).getMessage(); - assertEquals("Value is 3.", result); - - result = MessageFormatter.format("Value is {", i3).getMessage(); - assertEquals("Value is {", result); - - result = MessageFormatter.format("{} is larger than 2.", i3).getMessage(); - assertEquals("3 is larger than 2.", result); - - result = MessageFormatter.format("No subst", i3).getMessage(); - assertEquals("No subst", result); - - result = MessageFormatter.format("Incorrect {subst", i3).getMessage(); - assertEquals("Incorrect {subst", result); - - result = MessageFormatter.format("Value is {bla} {}", i3).getMessage(); - assertEquals("Value is {bla} 3", result); - - result = MessageFormatter.format("Escaped \\{} subst", i3).getMessage(); - assertEquals("Escaped {} subst", result); - - result = MessageFormatter.format("{Escaped", i3).getMessage(); - assertEquals("{Escaped", result); - - result = MessageFormatter.format("\\{}Escaped", i3).getMessage(); - assertEquals("{}Escaped", result); - - result = MessageFormatter.format("File name is {{}}.", "App folder.zip").getMessage(); - assertEquals("File name is {App folder.zip}.", result); - - // escaping the escape character - result = MessageFormatter.format("File name is C:\\\\{}.", "App folder.zip").getMessage(); - assertEquals("File name is C:\\App folder.zip.", result); - } - - @Test - public void testTwoParameters() { - result = MessageFormatter.format("Value {} is smaller than {}.", i1, i2).getMessage(); - assertEquals("Value 1 is smaller than 2.", result); - - result = MessageFormatter.format("Value {} is smaller than {}", i1, i2).getMessage(); - assertEquals("Value 1 is smaller than 2", result); - - result = MessageFormatter.format("{}{}", i1, i2).getMessage(); - assertEquals("12", result); - - result = MessageFormatter.format("Val1={}, Val2={", i1, i2).getMessage(); - assertEquals("Val1=1, Val2={", result); - - result = MessageFormatter.format("Value {} is smaller than \\{}", i1, i2).getMessage(); - assertEquals("Value 1 is smaller than {}", result); - - result = MessageFormatter.format("Value {} is smaller than \\{} tail", i1, i2).getMessage(); - assertEquals("Value 1 is smaller than {} tail", result); - - result = MessageFormatter.format("Value {} is smaller than \\{", i1, i2).getMessage(); - assertEquals("Value 1 is smaller than \\{", result); - - result = MessageFormatter.format("Value {} is smaller than {tail", i1, i2).getMessage(); - assertEquals("Value 1 is smaller than {tail", result); - - result = MessageFormatter.format("Value \\{} is smaller than {}", i1, i2).getMessage(); - assertEquals("Value {} is smaller than 1", result); - } - - @Test - public void testExceptionIn_toString() { - Object o = new Object() { - public String toString() { - throw new IllegalStateException("a"); - } - }; - result = MessageFormatter.format("Troublesome object {}", o).getMessage(); - assertEquals("Troublesome object [FAILED toString()]", result); - - } - - @Test - public void testNullArray() { - String msg0 = "msg0"; - String msg1 = "msg1 {}"; - String msg2 = "msg2 {} {}"; - String msg3 = "msg3 {} {} {}"; - - Object[] args = null; - - result = MessageFormatter.arrayFormat(msg0, args).getMessage(); - assertEquals(msg0, result); - - result = MessageFormatter.arrayFormat(msg1, args).getMessage(); - assertEquals(msg1, result); - - result = MessageFormatter.arrayFormat(msg2, args).getMessage(); - assertEquals(msg2, result); - - result = MessageFormatter.arrayFormat(msg3, args).getMessage(); - assertEquals(msg3, result); - } - - // tests the case when the parameters are supplied in a single array - @Test - public void testArrayFormat() { - result = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia0).getMessage(); - assertEquals("Value 1 is smaller than 2 and 3.", result); - - result = MessageFormatter.arrayFormat("{}{}{}", ia0).getMessage(); - assertEquals("123", result); - - result = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia0).getMessage(); - assertEquals("Value 1 is smaller than 2.", result); - - result = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia0).getMessage(); - assertEquals("Value 1 is smaller than 2", result); - - result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage(); - assertEquals("Val=1, {, Val=2", result); - - result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage(); - assertEquals("Val=1, {, Val=2", result); - - result = MessageFormatter.arrayFormat("Val1={}, Val2={", ia0).getMessage(); - assertEquals("Val1=1, Val2={", result); - } - - @Test - public void testArrayValues() { - Integer p0 = i1; - Integer[] p1 = new Integer[] { i2, i3 }; - - result = MessageFormatter.format("{}{}", p0, p1).getMessage(); - assertEquals("1[2, 3]", result); - - // Integer[] - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", p1 }).getMessage(); - assertEquals("a[2, 3]", result); - - // byte[] - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new byte[] { 1, 2 } }).getMessage(); - assertEquals("a[1, 2]", result); - - // int[] - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new int[] { 1, 2 } }).getMessage(); - assertEquals("a[1, 2]", result); - - // float[] - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new float[] { 1, 2 } }).getMessage(); - assertEquals("a[1.0, 2.0]", result); - - // double[] - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new double[] { 1, 2 } }).getMessage(); - assertEquals("a[1.0, 2.0]", result); - - } - - @Test - public void testMultiDimensionalArrayValues() { - Integer[][] multiIntegerA = new Integer[][] { ia0, ia1 }; - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntegerA }).getMessage(); - assertEquals("a[[1, 2, 3], [10, 20, 30]]", result); - - int[][] multiIntA = new int[][] { { 1, 2 }, { 10, 20 } }; - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntA }).getMessage(); - assertEquals("a[[1, 2], [10, 20]]", result); - - float[][] multiFloatA = new float[][] { { 1, 2 }, { 10, 20 } }; - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiFloatA }).getMessage(); - assertEquals("a[[1.0, 2.0], [10.0, 20.0]]", result); - - Object[][] multiOA = new Object[][] { ia0, ia1 }; - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiOA }).getMessage(); - assertEquals("a[[1, 2, 3], [10, 20, 30]]", result); - - Object[][][] _3DOA = new Object[][][] { multiOA, multiOA }; - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", _3DOA }).getMessage(); - assertEquals("a[[[1, 2, 3], [10, 20, 30]], [[1, 2, 3], [10, 20, 30]]]", result); - } - - @Test - public void testCyclicArrays() { - { - Object[] cyclicA = new Object[1]; - cyclicA[0] = cyclicA; - assertEquals("[[...]]", MessageFormatter.arrayFormat("{}", cyclicA).getMessage()); - } - { - Object[] a = new Object[2]; - a[0] = i1; - Object[] c = new Object[] { i3, a }; - Object[] b = new Object[] { i2, c }; - a[1] = b; - assertEquals("1[2, [3, [1, [...]]]]", MessageFormatter.arrayFormat("{}{}", a).getMessage()); - } - } - - @Test - public void testArrayThrowable() { - FormattingTuple ft; - Throwable t = new Throwable(); - Object[] ia = new Object[] { i1, i2, i3, t }; - Object[] iaWitness = new Object[] { i1, i2, i3 }; - - ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia); - assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); - - ft = MessageFormatter.arrayFormat("{}{}{}", ia); - assertEquals("123", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); - - ft = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia); - assertEquals("Value 1 is smaller than 2.", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); - - ft = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia); - assertEquals("Value 1 is smaller than 2", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); - - ft = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia); - assertEquals("Val=1, {, Val=2", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); - - ft = MessageFormatter.arrayFormat("Val={}, \\{, Val={}", ia); - assertEquals("Val=1, \\{, Val=2", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); - - ft = MessageFormatter.arrayFormat("Val1={}, Val2={", ia); - assertEquals("Val1=1, Val2={", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); - - ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia); - assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); - - ft = MessageFormatter.arrayFormat("{}{}{}{}", ia); - assertEquals("123{}", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); - - ft = MessageFormatter.arrayFormat("1={}", new Object[] { i1 }, t); - assertEquals("1=1", ft.getMessage()); - assertTrue(Arrays.equals(new Object[] { i1 }, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); - - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import java.util.Arrays; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * @author Ceki Gulcu + */ +public class MessageFormatterTest { + + Integer i1 = new Integer(1); + Integer i2 = new Integer(2); + Integer i3 = new Integer(3); + Integer[] ia0 = new Integer[] { i1, i2, i3 }; + Integer[] ia1 = new Integer[] { new Integer(10), new Integer(20), new Integer(30) }; + + String result; + + @Test + public void testNull() { + result = MessageFormatter.format(null, i1).getMessage(); + assertEquals(null, result); + } + + @Test + public void nullParametersShouldBeHandledWithoutBarfing() { + result = MessageFormatter.format("Value is {}.", null).getMessage(); + assertEquals("Value is null.", result); + + result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, null).getMessage(); + assertEquals("Val1 is null, val2 is null.", result); + + result = MessageFormatter.format("Val1 is {}, val2 is {}.", i1, null).getMessage(); + assertEquals("Val1 is 1, val2 is null.", result); + + result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, i2).getMessage(); + assertEquals("Val1 is null, val2 is 2.", result); + + result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, null }).getMessage(); + assertEquals("Val1 is null, val2 is null, val3 is null", result); + + result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, i2, i3 }).getMessage(); + assertEquals("Val1 is null, val2 is 2, val3 is 3", result); + + result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", new Integer[] { null, null, i3 }).getMessage(); + assertEquals("Val1 is null, val2 is null, val3 is 3", result); + } + + @Test + public void verifyOneParameterIsHandledCorrectly() { + result = MessageFormatter.format("Value is {}.", i3).getMessage(); + assertEquals("Value is 3.", result); + + result = MessageFormatter.format("Value is {", i3).getMessage(); + assertEquals("Value is {", result); + + result = MessageFormatter.format("{} is larger than 2.", i3).getMessage(); + assertEquals("3 is larger than 2.", result); + + result = MessageFormatter.format("No subst", i3).getMessage(); + assertEquals("No subst", result); + + result = MessageFormatter.format("Incorrect {subst", i3).getMessage(); + assertEquals("Incorrect {subst", result); + + result = MessageFormatter.format("Value is {bla} {}", i3).getMessage(); + assertEquals("Value is {bla} 3", result); + + result = MessageFormatter.format("Escaped \\{} subst", i3).getMessage(); + assertEquals("Escaped {} subst", result); + + result = MessageFormatter.format("{Escaped", i3).getMessage(); + assertEquals("{Escaped", result); + + result = MessageFormatter.format("\\{}Escaped", i3).getMessage(); + assertEquals("{}Escaped", result); + + result = MessageFormatter.format("File name is {{}}.", "App folder.zip").getMessage(); + assertEquals("File name is {App folder.zip}.", result); + + // escaping the escape character + result = MessageFormatter.format("File name is C:\\\\{}.", "App folder.zip").getMessage(); + assertEquals("File name is C:\\App folder.zip.", result); + } + + @Test + public void testTwoParameters() { + result = MessageFormatter.format("Value {} is smaller than {}.", i1, i2).getMessage(); + assertEquals("Value 1 is smaller than 2.", result); + + result = MessageFormatter.format("Value {} is smaller than {}", i1, i2).getMessage(); + assertEquals("Value 1 is smaller than 2", result); + + result = MessageFormatter.format("{}{}", i1, i2).getMessage(); + assertEquals("12", result); + + result = MessageFormatter.format("Val1={}, Val2={", i1, i2).getMessage(); + assertEquals("Val1=1, Val2={", result); + + result = MessageFormatter.format("Value {} is smaller than \\{}", i1, i2).getMessage(); + assertEquals("Value 1 is smaller than {}", result); + + result = MessageFormatter.format("Value {} is smaller than \\{} tail", i1, i2).getMessage(); + assertEquals("Value 1 is smaller than {} tail", result); + + result = MessageFormatter.format("Value {} is smaller than \\{", i1, i2).getMessage(); + assertEquals("Value 1 is smaller than \\{", result); + + result = MessageFormatter.format("Value {} is smaller than {tail", i1, i2).getMessage(); + assertEquals("Value 1 is smaller than {tail", result); + + result = MessageFormatter.format("Value \\{} is smaller than {}", i1, i2).getMessage(); + assertEquals("Value {} is smaller than 1", result); + } + + @Test + public void testExceptionIn_toString() { + Object o = new Object() { + public String toString() { + throw new IllegalStateException("a"); + } + }; + result = MessageFormatter.format("Troublesome object {}", o).getMessage(); + assertEquals("Troublesome object [FAILED toString()]", result); + + } + + @Test + public void testNullArray() { + String msg0 = "msg0"; + String msg1 = "msg1 {}"; + String msg2 = "msg2 {} {}"; + String msg3 = "msg3 {} {} {}"; + + Object[] args = null; + + result = MessageFormatter.arrayFormat(msg0, args).getMessage(); + assertEquals(msg0, result); + + result = MessageFormatter.arrayFormat(msg1, args).getMessage(); + assertEquals(msg1, result); + + result = MessageFormatter.arrayFormat(msg2, args).getMessage(); + assertEquals(msg2, result); + + result = MessageFormatter.arrayFormat(msg3, args).getMessage(); + assertEquals(msg3, result); + } + + // tests the case when the parameters are supplied in a single array + @Test + public void testArrayFormat() { + result = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia0).getMessage(); + assertEquals("Value 1 is smaller than 2 and 3.", result); + + result = MessageFormatter.arrayFormat("{}{}{}", ia0).getMessage(); + assertEquals("123", result); + + result = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia0).getMessage(); + assertEquals("Value 1 is smaller than 2.", result); + + result = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia0).getMessage(); + assertEquals("Value 1 is smaller than 2", result); + + result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage(); + assertEquals("Val=1, {, Val=2", result); + + result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0).getMessage(); + assertEquals("Val=1, {, Val=2", result); + + result = MessageFormatter.arrayFormat("Val1={}, Val2={", ia0).getMessage(); + assertEquals("Val1=1, Val2={", result); + } + + @Test + public void testArrayValues() { + Integer p0 = i1; + Integer[] p1 = new Integer[] { i2, i3 }; + + result = MessageFormatter.format("{}{}", p0, p1).getMessage(); + assertEquals("1[2, 3]", result); + + // Integer[] + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", p1 }).getMessage(); + assertEquals("a[2, 3]", result); + + // byte[] + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new byte[] { 1, 2 } }).getMessage(); + assertEquals("a[1, 2]", result); + + // int[] + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new int[] { 1, 2 } }).getMessage(); + assertEquals("a[1, 2]", result); + + // float[] + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new float[] { 1, 2 } }).getMessage(); + assertEquals("a[1.0, 2.0]", result); + + // double[] + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", new double[] { 1, 2 } }).getMessage(); + assertEquals("a[1.0, 2.0]", result); + + } + + @Test + public void testMultiDimensionalArrayValues() { + Integer[][] multiIntegerA = new Integer[][] { ia0, ia1 }; + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntegerA }).getMessage(); + assertEquals("a[[1, 2, 3], [10, 20, 30]]", result); + + int[][] multiIntA = new int[][] { { 1, 2 }, { 10, 20 } }; + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiIntA }).getMessage(); + assertEquals("a[[1, 2], [10, 20]]", result); + + float[][] multiFloatA = new float[][] { { 1, 2 }, { 10, 20 } }; + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiFloatA }).getMessage(); + assertEquals("a[[1.0, 2.0], [10.0, 20.0]]", result); + + Object[][] multiOA = new Object[][] { ia0, ia1 }; + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", multiOA }).getMessage(); + assertEquals("a[[1, 2, 3], [10, 20, 30]]", result); + + Object[][][] _3DOA = new Object[][][] { multiOA, multiOA }; + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", _3DOA }).getMessage(); + assertEquals("a[[[1, 2, 3], [10, 20, 30]], [[1, 2, 3], [10, 20, 30]]]", result); + } + + @Test + public void testCyclicArrays() { + { + Object[] cyclicA = new Object[1]; + cyclicA[0] = cyclicA; + assertEquals("[[...]]", MessageFormatter.arrayFormat("{}", cyclicA).getMessage()); + } + { + Object[] a = new Object[2]; + a[0] = i1; + Object[] c = new Object[] { i3, a }; + Object[] b = new Object[] { i2, c }; + a[1] = b; + assertEquals("1[2, [3, [1, [...]]]]", MessageFormatter.arrayFormat("{}{}", a).getMessage()); + } + } + + @Test + public void testArrayThrowable() { + FormattingTuple ft; + Throwable t = new Throwable(); + Object[] ia = new Object[] { i1, i2, i3, t }; + Object[] iaWitness = new Object[] { i1, i2, i3 }; + + ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia); + assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage()); + assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); + assertEquals(t, ft.getThrowable()); + + ft = MessageFormatter.arrayFormat("{}{}{}", ia); + assertEquals("123", ft.getMessage()); + assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); + assertEquals(t, ft.getThrowable()); + + ft = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia); + assertEquals("Value 1 is smaller than 2.", ft.getMessage()); + assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); + assertEquals(t, ft.getThrowable()); + + ft = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia); + assertEquals("Value 1 is smaller than 2", ft.getMessage()); + assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); + assertEquals(t, ft.getThrowable()); + + ft = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia); + assertEquals("Val=1, {, Val=2", ft.getMessage()); + assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); + assertEquals(t, ft.getThrowable()); + + ft = MessageFormatter.arrayFormat("Val={}, \\{, Val={}", ia); + assertEquals("Val=1, \\{, Val=2", ft.getMessage()); + assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); + assertEquals(t, ft.getThrowable()); + + ft = MessageFormatter.arrayFormat("Val1={}, Val2={", ia); + assertEquals("Val1=1, Val2={", ft.getMessage()); + assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); + assertEquals(t, ft.getThrowable()); + + ft = MessageFormatter.arrayFormat("Value {} is smaller than {} and {}.", ia); + assertEquals("Value 1 is smaller than 2 and 3.", ft.getMessage()); + assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); + assertEquals(t, ft.getThrowable()); + + ft = MessageFormatter.arrayFormat("{}{}{}{}", ia); + assertEquals("123{}", ft.getMessage()); + assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); + assertEquals(t, ft.getThrowable()); + + ft = MessageFormatter.arrayFormat("1={}", new Object[] { i1 }, t); + assertEquals("1=1", ft.getMessage()); + assertTrue(Arrays.equals(new Object[] { i1 }, ft.getArgArray())); + assertEquals(t, ft.getThrowable()); + + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/MultithreadedInitializationTest.java b/slf4j-api/src/test/java/org/slf4j/helpers/MultithreadedInitializationTest.java index 435d2bd..6cf3613 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/MultithreadedInitializationTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/MultithreadedInitializationTest.java @@ -1,81 +1,81 @@ -package org.slf4j.helpers; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Random; -import java.util.concurrent.BrokenBarrierException; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.atomic.AtomicLong; - -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerAccessingThread; -import org.slf4j.LoggerFactory; -import org.slf4j.event.EventRecodingLogger; - -abstract public class MultithreadedInitializationTest { - final protected static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2; - - private final List createdLoggers = Collections.synchronizedList(new ArrayList()); - - final private AtomicLong eventCount = new AtomicLong(0); - final private CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); - - int diff = new Random().nextInt(10000); - - @Test - public void multiThreadedInitialization() throws InterruptedException, BrokenBarrierException { - @SuppressWarnings("unused") - LoggerAccessingThread[] accessors = harness(); - - Logger logger = LoggerFactory.getLogger(getClass().getName()); - logger.info("hello"); - eventCount.getAndIncrement(); - - assertAllSubstLoggersAreFixed(); - long recordedEventCount = getRecordedEventCount(); - int LENIENCY_COUNT = 16; - - long expectedEventCount = eventCount.get() + extraLogEvents(); - - assertTrue(expectedEventCount + " >= " + recordedEventCount, expectedEventCount >= recordedEventCount); - assertTrue(expectedEventCount + " < " + recordedEventCount + "+" + LENIENCY_COUNT, expectedEventCount < recordedEventCount + LENIENCY_COUNT); - } - - abstract protected long getRecordedEventCount(); - - protected int extraLogEvents() { - return 0; - } - - private void assertAllSubstLoggersAreFixed() { - for (Logger logger : createdLoggers) { - if (logger instanceof SubstituteLogger) { - SubstituteLogger substLogger = (SubstituteLogger) logger; - if (substLogger.delegate() instanceof EventRecodingLogger) - fail("substLogger " + substLogger.getName() + " has a delegate of type EventRecodingLogger"); - } - } - } - - private LoggerAccessingThread[] harness() throws InterruptedException, BrokenBarrierException { - LoggerAccessingThread[] threads = new LoggerAccessingThread[THREAD_COUNT]; - for (int i = 0; i < THREAD_COUNT; i++) { - threads[i] = new LoggerAccessingThread(barrier, createdLoggers, i, eventCount); - threads[i].start(); - } - - // trigger barrier - barrier.await(); - - for (int i = 0; i < THREAD_COUNT; i++) { - threads[i].join(); - } - - return threads; - } -} +package org.slf4j.helpers; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.atomic.AtomicLong; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerAccessingThread; +import org.slf4j.LoggerFactory; +import org.slf4j.event.EventRecodingLogger; + +abstract public class MultithreadedInitializationTest { + final protected static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2; + + private final List createdLoggers = Collections.synchronizedList(new ArrayList()); + + final private AtomicLong eventCount = new AtomicLong(0); + final private CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); + + int diff = new Random().nextInt(10000); + + @Test + public void multiThreadedInitialization() throws InterruptedException, BrokenBarrierException { + @SuppressWarnings("unused") + LoggerAccessingThread[] accessors = harness(); + + Logger logger = LoggerFactory.getLogger(getClass().getName()); + logger.info("hello"); + eventCount.getAndIncrement(); + + assertAllSubstLoggersAreFixed(); + long recordedEventCount = getRecordedEventCount(); + int LENIENCY_COUNT = 16; + + long expectedEventCount = eventCount.get() + extraLogEvents(); + + assertTrue(expectedEventCount + " >= " + recordedEventCount, expectedEventCount >= recordedEventCount); + assertTrue(expectedEventCount + " < " + recordedEventCount + "+" + LENIENCY_COUNT, expectedEventCount < recordedEventCount + LENIENCY_COUNT); + } + + abstract protected long getRecordedEventCount(); + + protected int extraLogEvents() { + return 0; + } + + private void assertAllSubstLoggersAreFixed() { + for (Logger logger : createdLoggers) { + if (logger instanceof SubstituteLogger) { + SubstituteLogger substLogger = (SubstituteLogger) logger; + if (substLogger.delegate() instanceof EventRecodingLogger) + fail("substLogger " + substLogger.getName() + " has a delegate of type EventRecodingLogger"); + } + } + } + + private LoggerAccessingThread[] harness() throws InterruptedException, BrokenBarrierException { + LoggerAccessingThread[] threads = new LoggerAccessingThread[THREAD_COUNT]; + for (int i = 0; i < THREAD_COUNT; i++) { + threads[i] = new LoggerAccessingThread(barrier, createdLoggers, i, eventCount); + threads[i].start(); + } + + // trigger barrier + barrier.await(); + + for (int i = 0; i < THREAD_COUNT; i++) { + threads[i].join(); + } + + return threads; + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/MyRandom.java b/slf4j-api/src/test/java/org/slf4j/helpers/MyRandom.java index b0feb19..c817d67 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/MyRandom.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/MyRandom.java @@ -1,51 +1,51 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -class MyRandom { - - private final static long m = 200000000041L; // a prime number - private final static long a = 2000000011L; // a prime number - - long y; - long unused; - int bits = 32; - - public MyRandom() { - this(System.nanoTime()); - } - - public MyRandom(long seed) { - this.y = seed; - } - - int nextInt() { - // we don't really care about the randomness of this - // generator - y = (a * y + 1) % m; - unused = y >>> (48 - bits); // just exercise the >>> operator - return (int) (y); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +class MyRandom { + + private final static long m = 200000000041L; // a prime number + private final static long a = 2000000011L; // a prime number + + long y; + long unused; + int bits = 32; + + public MyRandom() { + this(System.nanoTime()); + } + + public MyRandom(long seed) { + this.y = seed; + } + + int nextInt() { + // we don't really care about the randomness of this + // generator + y = (a * y + 1) % m; + unused = y >>> (48 - bits); // just exercise the >>> operator + return (int) (y); + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/SubstitutableLoggerTest.java b/slf4j-api/src/test/java/org/slf4j/helpers/SubstitutableLoggerTest.java index dc7672e..c8f4447 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/SubstitutableLoggerTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/SubstitutableLoggerTest.java @@ -1,112 +1,112 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.event.EventRecodingLogger; -import org.slf4j.helpers.SubstituteLogger; - -/** - * @author Chetan Mehrotra - */ -public class SubstitutableLoggerTest { - private static final Set EXCLUDED_METHODS = new HashSet(Arrays.asList("getName")); - - @Test - public void testDelegate() throws Exception { - SubstituteLogger log = new SubstituteLogger("foo", null, false); - assertTrue(log.delegate() instanceof EventRecodingLogger); - - Set expectedMethodSignatures = determineMethodSignatures(Logger.class); - LoggerInvocationHandler ih = new LoggerInvocationHandler(); - Logger proxyLogger = (Logger) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Logger.class }, ih); - log.setDelegate(proxyLogger); - - invokeMethods(log); - - // Assert that all methods are delegated - expectedMethodSignatures.removeAll(ih.getInvokedMethodSignatures()); - if (!expectedMethodSignatures.isEmpty()) { - fail("Following methods are not delegated " + expectedMethodSignatures.toString()); - } - } - - private void invokeMethods(Logger proxyLogger) throws InvocationTargetException, IllegalAccessException { - for (Method m : Logger.class.getDeclaredMethods()) { - if (!EXCLUDED_METHODS.contains(m.getName())) { - m.invoke(proxyLogger, new Object[m.getParameterTypes().length]); - } - } - } - - private class LoggerInvocationHandler implements InvocationHandler { - private final Set invokedMethodSignatures = new HashSet(); - - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - invokedMethodSignatures.add(getMethodSignature(method)); - if (method.getName().startsWith("is")) { - return true; - } - return null; - } - - public Set getInvokedMethodSignatures() { - return invokedMethodSignatures; - } - } - - private static Set determineMethodSignatures(Class loggerClass) { - Set methodSignatures = new HashSet(); - for (Method m : loggerClass.getDeclaredMethods()) { - if (!EXCLUDED_METHODS.contains(m.getName())) { - methodSignatures.add(getMethodSignature(m)); - } - } - return methodSignatures; - } - - private static String getMethodSignature(Method m) { - List result = new ArrayList(); - result.add(m.getName()); - for (Class clazz : m.getParameterTypes()) { - result.add(clazz.getSimpleName()); - } - return result.toString(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.event.EventRecodingLogger; +import org.slf4j.helpers.SubstituteLogger; + +/** + * @author Chetan Mehrotra + */ +public class SubstitutableLoggerTest { + private static final Set EXCLUDED_METHODS = new HashSet(Arrays.asList("getName")); + + @Test + public void testDelegate() throws Exception { + SubstituteLogger log = new SubstituteLogger("foo", null, false); + assertTrue(log.delegate() instanceof EventRecodingLogger); + + Set expectedMethodSignatures = determineMethodSignatures(Logger.class); + LoggerInvocationHandler ih = new LoggerInvocationHandler(); + Logger proxyLogger = (Logger) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Logger.class }, ih); + log.setDelegate(proxyLogger); + + invokeMethods(log); + + // Assert that all methods are delegated + expectedMethodSignatures.removeAll(ih.getInvokedMethodSignatures()); + if (!expectedMethodSignatures.isEmpty()) { + fail("Following methods are not delegated " + expectedMethodSignatures.toString()); + } + } + + private void invokeMethods(Logger proxyLogger) throws InvocationTargetException, IllegalAccessException { + for (Method m : Logger.class.getDeclaredMethods()) { + if (!EXCLUDED_METHODS.contains(m.getName())) { + m.invoke(proxyLogger, new Object[m.getParameterTypes().length]); + } + } + } + + private class LoggerInvocationHandler implements InvocationHandler { + private final Set invokedMethodSignatures = new HashSet(); + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + invokedMethodSignatures.add(getMethodSignature(method)); + if (method.getName().startsWith("is")) { + return true; + } + return null; + } + + public Set getInvokedMethodSignatures() { + return invokedMethodSignatures; + } + } + + private static Set determineMethodSignatures(Class loggerClass) { + Set methodSignatures = new HashSet(); + for (Method m : loggerClass.getDeclaredMethods()) { + if (!EXCLUDED_METHODS.contains(m.getName())) { + methodSignatures.add(getMethodSignature(m)); + } + } + return methodSignatures; + } + + private static String getMethodSignature(Method m) { + List result = new ArrayList(); + result.add(m.getName()); + for (Class clazz : m.getParameterTypes()) { + result.add(clazz.getSimpleName()); + } + return result.toString(); + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/SubstituteLoggerFactoryTest.java b/slf4j-api/src/test/java/org/slf4j/helpers/SubstituteLoggerFactoryTest.java old file mode 100644 new file mode 100755 index 620af1b..9820f8b 100755 --- a/slf4j-api/src/test/java/org/slf4j/helpers/SubstituteLoggerFactoryTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/SubstituteLoggerFactoryTest.java @@ -1,76 +1,76 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.slf4j.Logger; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -public class SubstituteLoggerFactoryTest { - private SubstituteLoggerFactory factory = new SubstituteLoggerFactory(); - - @Test - public void testFactory() { - Logger log = factory.getLogger("foo"); - assertNotNull(log); - - Logger log2 = factory.getLogger("foo"); - assertTrue("Loggers with same name must be same", log == log2); - } - - @Test - public void testLoggerNameList() { - factory.getLogger("foo1"); - factory.getLogger("foo2"); - - Set expectedNames = new HashSet(Arrays.asList("foo1", "foo2")); - Set actualNames = new HashSet(factory.getLoggerNames()); - - assertEquals(expectedNames, actualNames); - } - - @Test - public void testLoggers() { - factory.getLogger("foo1"); - factory.getLogger("foo2"); - - Set expectedNames = new HashSet(Arrays.asList("foo1", "foo2")); - - Set actualNames = new HashSet(); - for (SubstituteLogger slog : factory.getLoggers()) { - actualNames.add(slog.getName()); - } - - assertEquals(expectedNames, actualNames); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.slf4j.Logger; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class SubstituteLoggerFactoryTest { + private SubstituteLoggerFactory factory = new SubstituteLoggerFactory(); + + @Test + public void testFactory() { + Logger log = factory.getLogger("foo"); + assertNotNull(log); + + Logger log2 = factory.getLogger("foo"); + assertTrue("Loggers with same name must be same", log == log2); + } + + @Test + public void testLoggerNameList() { + factory.getLogger("foo1"); + factory.getLogger("foo2"); + + Set expectedNames = new HashSet(Arrays.asList("foo1", "foo2")); + Set actualNames = new HashSet(factory.getLoggerNames()); + + assertEquals(expectedNames, actualNames); + } + + @Test + public void testLoggers() { + factory.getLogger("foo1"); + factory.getLogger("foo2"); + + Set expectedNames = new HashSet(Arrays.asList("foo1", "foo2")); + + Set actualNames = new HashSet(); + for (SubstituteLogger slog : factory.getLoggers()) { + actualNames.add(slog.getName()); + } + + assertEquals(expectedNames, actualNames); + } + +} diff --git a/slf4j-ext/pom.xml b/slf4j-ext/pom.xml old file mode 100644 new file mode 100755 index 558e3d2..9a69b3c 100755 --- a/slf4j-ext/pom.xml +++ b/slf4j-ext/pom.xml @@ -1,86 +1,86 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - slf4j-ext - - jar - SLF4J Extensions Module - Extensions to the SLF4J API - - http://www.slf4j.org - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - ${project.version} - test - - - ch.qos.cal10n - cal10n-api - true - - - javassist - javassist - 3.4.GA - true - - - commons-lang - commons-lang - 2.4 - true - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - false - once - plain - false - - **/AllTest.java - **/PackageTest.java - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - org.slf4j.agent.AgentPremain - - ../../../../javassist/javassist/3.4.GA/javassist-3.4.GA.jar javassist-3.4.GA.jar javassist.jar - - - - - - - - + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + slf4j-ext + + jar + SLF4J Extensions Module + Extensions to the SLF4J API + + http://www.slf4j.org + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + ${project.version} + test + + + ch.qos.cal10n + cal10n-api + true + + + javassist + javassist + 3.4.GA + true + + + commons-lang + commons-lang + 2.4 + true + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + false + once + plain + false + + **/AllTest.java + **/PackageTest.java + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.slf4j.agent.AgentPremain + + ../../../../javassist/javassist/3.4.GA/javassist-3.4.GA.jar javassist-3.4.GA.jar javassist.jar + + + + + + + + diff --git a/slf4j-ext/src/main/java/org/slf4j/NDC.java b/slf4j-ext/src/main/java/org/slf4j/NDC.java index 861c1bf..fbad274 100644 --- a/slf4j-ext/src/main/java/org/slf4j/NDC.java +++ b/slf4j-ext/src/main/java/org/slf4j/NDC.java @@ -1,62 +1,62 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import org.slf4j.MDC; - -public class NDC { - public final static String PREFIX = "NDC"; - - private static int size() { - int i = 0; - while (true) { - String val = MDC.get(PREFIX + i); - if (val != null) { - i++; - } else { - break; - } - } - return i; - } - - public static void push(String val) { - int next = size(); - MDC.put(PREFIX + next, val); - } - - public static String pop() { - int next = size(); - if (next == 0) { - return ""; - } - int last = next - 1; - String key = PREFIX + last; - String val = MDC.get(key); - MDC.remove(key); - return val; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import org.slf4j.MDC; + +public class NDC { + public final static String PREFIX = "NDC"; + + private static int size() { + int i = 0; + while (true) { + String val = MDC.get(PREFIX + i); + if (val != null) { + i++; + } else { + break; + } + } + return i; + } + + public static void push(String val) { + int next = size(); + MDC.put(PREFIX + next, val); + } + + public static String pop() { + int next = size(); + if (next == 0) { + return ""; + } + int last = next - 1; + String key = PREFIX + last; + String val = MDC.get(key); + MDC.remove(key); + return val; + } + +} diff --git a/slf4j-ext/src/main/java/org/slf4j/agent/AgentOptions.java b/slf4j-ext/src/main/java/org/slf4j/agent/AgentOptions.java index 0319acd..181dfba 100644 --- a/slf4j-ext/src/main/java/org/slf4j/agent/AgentOptions.java +++ b/slf4j-ext/src/main/java/org/slf4j/agent/AgentOptions.java @@ -1,63 +1,63 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.agent; - -/** - *

- * All recognized options in the string passed to the java agent. For - * "java -javaagent:foo.jar=OPTIONS HelloWorld" this would be "OPTIONS". - *

- *

- * It is considered to be a list of options separated by (currently) ";", on the - * form "option=value". The interpretation of "value" is specific to each - * option. - *

- */ -public class AgentOptions { - - /** - * List of class prefixes to ignore when instrumenting. Note: Classes loaded - * before the agent cannot be instrumented. - */ - public static final String IGNORE = "ignore"; - /** - * Indicate the SLF4J level that should be used by the logging statements - * added by the agent. Default is "info". - */ - public static final String LEVEL = "level"; - /** - * Indicate that the agent should print out "new java.util.Date()" at the time - * the option was processed and at shutdown time (using the shutdown hook). - * - */ - public static final String TIME = "time"; - /** - * Indicate that the agent should log actions to System.err, like adding - * logging to methods, etc. - * - */ - public static final String VERBOSE = "verbose"; - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.agent; + +/** + *

+ * All recognized options in the string passed to the java agent. For + * "java -javaagent:foo.jar=OPTIONS HelloWorld" this would be "OPTIONS". + *

+ *

+ * It is considered to be a list of options separated by (currently) ";", on the + * form "option=value". The interpretation of "value" is specific to each + * option. + *

+ */ +public class AgentOptions { + + /** + * List of class prefixes to ignore when instrumenting. Note: Classes loaded + * before the agent cannot be instrumented. + */ + public static final String IGNORE = "ignore"; + /** + * Indicate the SLF4J level that should be used by the logging statements + * added by the agent. Default is "info". + */ + public static final String LEVEL = "level"; + /** + * Indicate that the agent should print out "new java.util.Date()" at the time + * the option was processed and at shutdown time (using the shutdown hook). + * + */ + public static final String TIME = "time"; + /** + * Indicate that the agent should log actions to System.err, like adding + * logging to methods, etc. + * + */ + public static final String VERBOSE = "verbose"; + +} diff --git a/slf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java b/slf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java index 80ecebf..127b525 100644 --- a/slf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java +++ b/slf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java @@ -1,126 +1,126 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.agent; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.lang.instrument.Instrumentation; -import java.util.Date; -import java.util.Properties; - -import org.slf4j.instrumentation.LogTransformer; - -/** - * Entry point for slf4j-ext when used as a Java agent. - * - */ -public class AgentPremain { - - /** - * JavaAgent premain entry point as specified in the MANIFEST.MF file. See - * http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html for details. - * - * @param agentArgument - * string provided after "=" up to first space - * @param instrumentation - * instrumentation environment provided by the JVM - */ - public static void premain(String agentArgument, Instrumentation instrumentation) { - - // We cannot do sanity checks for slf4j here as the jars loaded - // by the application are not visible here. - - LogTransformer.Builder builder = new LogTransformer.Builder(); - builder = builder.addEntryExit(true); - - if (agentArgument != null) { - Properties args = parseArguments(agentArgument, ","); - - if (args.containsKey(AgentOptions.VERBOSE)) { - builder = builder.verbose(true); - } - - if (args.containsKey(AgentOptions.TIME)) { - printStartStopTimes(); - } - - if (args.containsKey(AgentOptions.IGNORE)) { - String ignore = args.getProperty(AgentOptions.IGNORE); - builder = builder.ignore(ignore.split(":")); - } - - if (args.containsKey(AgentOptions.LEVEL)) { - builder = builder.level(args.getProperty(AgentOptions.LEVEL)); - } - } - - instrumentation.addTransformer(builder.build()); - } - - /** - * Consider the argument string to be a property file (by converting the - * splitter character to line feeds), and then reading it like any other - * property file. - * - * - * @param agentArgument - * string given by instrumentation framework - * @param separator - * String to convert to line feeds - * @return argument converted to properties - */ - private static Properties parseArguments(String agentArgument, String separator) { - Properties p = new Properties(); - try { - String argumentAsLines = agentArgument.replaceAll(separator, "\n"); - p.load(new ByteArrayInputStream(argumentAsLines.getBytes())); - } catch (IOException e) { - String s = "Could not load arguments as properties"; - throw new RuntimeException(s, e); - } - return p; - } - - /** - * Print the start message to System.err with the time NOW, and register a - * shutdown hook which will print the stop message to System.err with the - * time then and the number of milliseconds passed since. - * - */ - private static void printStartStopTimes() { - final long start = System.currentTimeMillis(); - - System.err.println("Start at " + new Date()); - - Thread hook = new Thread() { - @Override - public void run() { - long timePassed = System.currentTimeMillis() - start; - System.err.println("Stop at " + new Date() + ", execution time = " + timePassed + " ms"); - } - }; - Runtime.getRuntime().addShutdownHook(hook); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.agent; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.lang.instrument.Instrumentation; +import java.util.Date; +import java.util.Properties; + +import org.slf4j.instrumentation.LogTransformer; + +/** + * Entry point for slf4j-ext when used as a Java agent. + * + */ +public class AgentPremain { + + /** + * JavaAgent premain entry point as specified in the MANIFEST.MF file. See + * http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html for details. + * + * @param agentArgument + * string provided after "=" up to first space + * @param instrumentation + * instrumentation environment provided by the JVM + */ + public static void premain(String agentArgument, Instrumentation instrumentation) { + + // We cannot do sanity checks for slf4j here as the jars loaded + // by the application are not visible here. + + LogTransformer.Builder builder = new LogTransformer.Builder(); + builder = builder.addEntryExit(true); + + if (agentArgument != null) { + Properties args = parseArguments(agentArgument, ","); + + if (args.containsKey(AgentOptions.VERBOSE)) { + builder = builder.verbose(true); + } + + if (args.containsKey(AgentOptions.TIME)) { + printStartStopTimes(); + } + + if (args.containsKey(AgentOptions.IGNORE)) { + String ignore = args.getProperty(AgentOptions.IGNORE); + builder = builder.ignore(ignore.split(":")); + } + + if (args.containsKey(AgentOptions.LEVEL)) { + builder = builder.level(args.getProperty(AgentOptions.LEVEL)); + } + } + + instrumentation.addTransformer(builder.build()); + } + + /** + * Consider the argument string to be a property file (by converting the + * splitter character to line feeds), and then reading it like any other + * property file. + * + * + * @param agentArgument + * string given by instrumentation framework + * @param separator + * String to convert to line feeds + * @return argument converted to properties + */ + private static Properties parseArguments(String agentArgument, String separator) { + Properties p = new Properties(); + try { + String argumentAsLines = agentArgument.replaceAll(separator, "\n"); + p.load(new ByteArrayInputStream(argumentAsLines.getBytes())); + } catch (IOException e) { + String s = "Could not load arguments as properties"; + throw new RuntimeException(s, e); + } + return p; + } + + /** + * Print the start message to System.err with the time NOW, and register a + * shutdown hook which will print the stop message to System.err with the + * time then and the number of milliseconds passed since. + * + */ + private static void printStartStopTimes() { + final long start = System.currentTimeMillis(); + + System.err.println("Start at " + new Date()); + + Thread hook = new Thread() { + @Override + public void run() { + long timePassed = System.currentTimeMillis() - start; + System.err.println("Stop at " + new Date() + ", execution time = " + timePassed + " ms"); + } + }; + Runtime.getRuntime().addShutdownHook(hook); + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/agent/package.html b/slf4j-ext/src/main/java/org/slf4j/agent/package.html index ed68a70..6172646 100644 --- a/slf4j-ext/src/main/java/org/slf4j/agent/package.html +++ b/slf4j-ext/src/main/java/org/slf4j/agent/package.html @@ -1,33 +1,33 @@ - - - - - - - - - -

"-javaagent" routines for SLF4J.

-

The "-javaagent" flag provided in Java 5+ allows for writing -agents in Java, which previously was possible in native code only. The -full details are available at http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html. - - -Please notice that code made available to the java agent is also -available to the actual program executed.

-

The slf4j-ext-X.Y.Z.jar file provides such a java agent, which is -implemented in AgentPremain.java. It is used by adding a -javaagent flag to the Java command line: - -E.g. -

java HelloWorld
-is changed to -
java -javaagent:/path/to/slf4j-ext-X.Y.Z.jar=OPTIONS HelloWorld
- -What is actually done, depends on the OPTIONS passed to the agent. These are listed in AgentOptions.java. -

- - - - - + + + + + + + + + +

"-javaagent" routines for SLF4J.

+

The "-javaagent" flag provided in Java 5+ allows for writing +agents in Java, which previously was possible in native code only. The +full details are available at http://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary.html. + + +Please notice that code made available to the java agent is also +available to the actual program executed.

+

The slf4j-ext-X.Y.Z.jar file provides such a java agent, which is +implemented in AgentPremain.java. It is used by adding a -javaagent flag to the Java command line: + +E.g. +

java HelloWorld
+is changed to +
java -javaagent:/path/to/slf4j-ext-X.Y.Z.jar=OPTIONS HelloWorld
+ +What is actually done, depends on the OPTIONS passed to the agent. These are listed in AgentOptions.java. +

+ + + + + diff --git a/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLogger.java b/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLogger.java index b2d7868..d4ee8fe 100644 --- a/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLogger.java +++ b/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLogger.java @@ -1,173 +1,173 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.cal10n; - -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; -import org.slf4j.ext.LoggerWrapper; -import org.slf4j.spi.LocationAwareLogger; - -import ch.qos.cal10n.IMessageConveyor; -import ch.qos.cal10n.MessageParameterObj; - -/** - * A logger specialized in localized logging. Localization is based in the CAL10N project

. - * - * @author Ceki Gülcü - */ -public class LocLogger extends LoggerWrapper implements Logger { - - private static final String FQCN = LocLogger.class.getName(); - - /** - * Every localized message logged by a LocLogger will bear this marker. It - * allows marker-aware implementations to perform additional processing on - * localized messages. - */ - static Marker LOCALIZED = MarkerFactory.getMarker("LOCALIZED"); - - final IMessageConveyor imc; - - public LocLogger(Logger logger, IMessageConveyor imc) { - super(logger, LoggerWrapper.class.getName()); - if (imc == null) { - throw new IllegalArgumentException("IMessageConveyor cannot be null"); - } - this.imc = imc; - } - - /** - * Log a localized message at the TRACE level. - * - * @param key - * the key used for localization - * @param args - * optional arguments - */ - public void trace(Enum key, Object... args) { - if (!logger.isTraceEnabled()) { - return; - } - String translatedMsg = imc.getMessage(key, args); - MessageParameterObj mpo = new MessageParameterObj(key, args); - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.TRACE_INT, translatedMsg, args, null); - } else { - logger.trace(LOCALIZED, translatedMsg, mpo); - } - } - - /** - * Log a localized message at the DEBUG level. - * - * @param key - * the key used for localization - * @param args - * optional arguments - */ - public void debug(Enum key, Object... args) { - if (!logger.isDebugEnabled()) { - return; - } - String translatedMsg = imc.getMessage(key, args); - MessageParameterObj mpo = new MessageParameterObj(key, args); - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.DEBUG_INT, translatedMsg, args, null); - } else { - logger.debug(LOCALIZED, translatedMsg, mpo); - } - } - - /** - * Log a localized message at the INFO level. - * - * @param key - * the key used for localization - * @param args - * optional arguments - */ - public void info(Enum key, Object... args) { - if (!logger.isInfoEnabled()) { - return; - } - String translatedMsg = imc.getMessage(key, args); - MessageParameterObj mpo = new MessageParameterObj(key, args); - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.INFO_INT, translatedMsg, args, null); - } else { - logger.info(LOCALIZED, translatedMsg, mpo); - } - } - - /** - * Log a localized message at the WARN level. - * - * @param key - * the key used for localization - * @param args - * optional arguments - */ - public void warn(Enum key, Object... args) { - if (!logger.isWarnEnabled()) { - return; - } - String translatedMsg = imc.getMessage(key, args); - MessageParameterObj mpo = new MessageParameterObj(key, args); - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.WARN_INT, translatedMsg, args, null); - } else { - logger.warn(LOCALIZED, translatedMsg, mpo); - } - } - - /** - * Log a localized message at the ERROR level. - * - * @param key - * the key used for localization - * @param args - * optional arguments - */ - public void error(Enum key, Object... args) { - if (!logger.isErrorEnabled()) { - return; - } - String translatedMsg = imc.getMessage(key, args); - MessageParameterObj mpo = new MessageParameterObj(key, args); - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.ERROR_INT, translatedMsg, args, null); - } else { - logger.error(LOCALIZED, translatedMsg, mpo); - } - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.cal10n; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; +import org.slf4j.ext.LoggerWrapper; +import org.slf4j.spi.LocationAwareLogger; + +import ch.qos.cal10n.IMessageConveyor; +import ch.qos.cal10n.MessageParameterObj; + +/** + * A logger specialized in localized logging. Localization is based in the
CAL10N project

. + * + * @author Ceki Gülcü + */ +public class LocLogger extends LoggerWrapper implements Logger { + + private static final String FQCN = LocLogger.class.getName(); + + /** + * Every localized message logged by a LocLogger will bear this marker. It + * allows marker-aware implementations to perform additional processing on + * localized messages. + */ + static Marker LOCALIZED = MarkerFactory.getMarker("LOCALIZED"); + + final IMessageConveyor imc; + + public LocLogger(Logger logger, IMessageConveyor imc) { + super(logger, LoggerWrapper.class.getName()); + if (imc == null) { + throw new IllegalArgumentException("IMessageConveyor cannot be null"); + } + this.imc = imc; + } + + /** + * Log a localized message at the TRACE level. + * + * @param key + * the key used for localization + * @param args + * optional arguments + */ + public void trace(Enum key, Object... args) { + if (!logger.isTraceEnabled()) { + return; + } + String translatedMsg = imc.getMessage(key, args); + MessageParameterObj mpo = new MessageParameterObj(key, args); + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.TRACE_INT, translatedMsg, args, null); + } else { + logger.trace(LOCALIZED, translatedMsg, mpo); + } + } + + /** + * Log a localized message at the DEBUG level. + * + * @param key + * the key used for localization + * @param args + * optional arguments + */ + public void debug(Enum key, Object... args) { + if (!logger.isDebugEnabled()) { + return; + } + String translatedMsg = imc.getMessage(key, args); + MessageParameterObj mpo = new MessageParameterObj(key, args); + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.DEBUG_INT, translatedMsg, args, null); + } else { + logger.debug(LOCALIZED, translatedMsg, mpo); + } + } + + /** + * Log a localized message at the INFO level. + * + * @param key + * the key used for localization + * @param args + * optional arguments + */ + public void info(Enum key, Object... args) { + if (!logger.isInfoEnabled()) { + return; + } + String translatedMsg = imc.getMessage(key, args); + MessageParameterObj mpo = new MessageParameterObj(key, args); + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.INFO_INT, translatedMsg, args, null); + } else { + logger.info(LOCALIZED, translatedMsg, mpo); + } + } + + /** + * Log a localized message at the WARN level. + * + * @param key + * the key used for localization + * @param args + * optional arguments + */ + public void warn(Enum key, Object... args) { + if (!logger.isWarnEnabled()) { + return; + } + String translatedMsg = imc.getMessage(key, args); + MessageParameterObj mpo = new MessageParameterObj(key, args); + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.WARN_INT, translatedMsg, args, null); + } else { + logger.warn(LOCALIZED, translatedMsg, mpo); + } + } + + /** + * Log a localized message at the ERROR level. + * + * @param key + * the key used for localization + * @param args + * optional arguments + */ + public void error(Enum key, Object... args) { + if (!logger.isErrorEnabled()) { + return; + } + String translatedMsg = imc.getMessage(key, args); + MessageParameterObj mpo = new MessageParameterObj(key, args); + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(LOCALIZED, FQCN, LocationAwareLogger.ERROR_INT, translatedMsg, args, null); + } else { + logger.error(LOCALIZED, translatedMsg, mpo); + } + } + +} diff --git a/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLoggerFactory.java b/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLoggerFactory.java index 3067cc7..2e56fee 100644 --- a/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLoggerFactory.java +++ b/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLoggerFactory.java @@ -1,75 +1,75 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.cal10n; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.qos.cal10n.IMessageConveyor; - -/** - * - * This class is essentially a wrapper around an {@link LoggerFactory} producing - * {@link LocLogger} instances. - * - *

- * Contrary to {@link LoggerFactory#getLogger(String)} method of - * {@link LoggerFactory}, each call to {@link #getLocLogger(String)} produces a new - * instance of {@link LocLogger}. This should not matter because a LocLogger - * instance does have any state beyond that of the {@link Logger} instance it - * wraps and its message conveyor. - * - * @author Ceki Gülcü - * - */ -public class LocLoggerFactory { - - final IMessageConveyor imc; - - public LocLoggerFactory(IMessageConveyor imc) { - this.imc = imc; - } - - /** - * Get an LocLogger instance by name. - * - * @param name - * @return LocLogger instance by name. - */ - public LocLogger getLocLogger(String name) { - return new LocLogger(LoggerFactory.getLogger(name), imc); - } - - /** - * Get a new LocLogger instance by class. The returned LocLogger will be named - * after the class. - * - * @param clazz - * @return LocLogger instance by class - */ - public LocLogger getLocLogger(Class clazz) { - return getLocLogger(clazz.getName()); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.cal10n; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.qos.cal10n.IMessageConveyor; + +/** + * + * This class is essentially a wrapper around an {@link LoggerFactory} producing + * {@link LocLogger} instances. + * + *

+ * Contrary to {@link LoggerFactory#getLogger(String)} method of + * {@link LoggerFactory}, each call to {@link #getLocLogger(String)} produces a new + * instance of {@link LocLogger}. This should not matter because a LocLogger + * instance does have any state beyond that of the {@link Logger} instance it + * wraps and its message conveyor. + * + * @author Ceki Gülcü + * + */ +public class LocLoggerFactory { + + final IMessageConveyor imc; + + public LocLoggerFactory(IMessageConveyor imc) { + this.imc = imc; + } + + /** + * Get an LocLogger instance by name. + * + * @param name + * @return LocLogger instance by name. + */ + public LocLogger getLocLogger(String name) { + return new LocLogger(LoggerFactory.getLogger(name), imc); + } + + /** + * Get a new LocLogger instance by class. The returned LocLogger will be named + * after the class. + * + * @param clazz + * @return LocLogger instance by class + */ + public LocLogger getLocLogger(Class clazz) { + return getLocLogger(clazz.getName()); + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/cal10n/package.html b/slf4j-ext/src/main/java/org/slf4j/cal10n/package.html index d162e36..39cfc8d 100644 --- a/slf4j-ext/src/main/java/org/slf4j/cal10n/package.html +++ b/slf4j-ext/src/main/java/org/slf4j/cal10n/package.html @@ -1,12 +1,12 @@ - - - - - - - - - -

SLF4J API extensions

- - + + + + + + + + + +

SLF4J API extensions

+ + diff --git a/slf4j-ext/src/main/java/org/slf4j/ext/EventData.java b/slf4j-ext/src/main/java/org/slf4j/ext/EventData.java deleted file mode 100644 index dc5b502..0000000 --- a/slf4j-ext/src/main/java/org/slf4j/ext/EventData.java +++ /dev/null @@ -1,305 +0,0 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.ext; - -import java.io.Serializable; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.beans.XMLDecoder; -import java.beans.XMLEncoder; -import java.beans.ExceptionListener; - -/** - * Base class for Event Data. Event Data contains data to be logged about an - * event. Users may extend this class for each EventType they want to log. - * - * @author Ralph Goers - */ -public class EventData implements Serializable { - - private static final long serialVersionUID = 153270778642103985L; - - private Map eventData = new HashMap(); - public static final String EVENT_MESSAGE = "EventMessage"; - public static final String EVENT_TYPE = "EventType"; - public static final String EVENT_DATETIME = "EventDateTime"; - public static final String EVENT_ID = "EventId"; - - /** - * Default Constructor - */ - public EventData() { - } - - /** - * Constructor to create event data from a Map. - * - * @param map - * The event data. - */ - public EventData(Map map) { - eventData.putAll(map); - } - - /** - * Construct from a serialized form of the Map containing the RequestInfo - * elements - * - * @param xml - * The serialized form of the RequestInfo Map. - */ - @SuppressWarnings("unchecked") - public EventData(String xml) { - ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); - try { - XMLDecoder decoder = new XMLDecoder(bais); - this.eventData = (Map) decoder.readObject(); - } catch (Exception e) { - throw new EventException("Error decoding " + xml, e); - } - } - - /** - * Serialize all the EventData items into an XML representation. - * - * @return an XML String containing all the EventData items. - */ - public String toXML() { - return toXML(eventData); - } - - /** - * Serialize all the EventData items into an XML representation. - * - * @param map the Map to transform - * @return an XML String containing all the EventData items. - */ - public static String toXML(Map map) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - XMLEncoder encoder = new XMLEncoder(baos); - encoder.setExceptionListener(new ExceptionListener() { - public void exceptionThrown(Exception exception) { - exception.printStackTrace(); - } - }); - encoder.writeObject(map); - encoder.close(); - return baos.toString(); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * Retrieve the event identifier. - * - * @return The event identifier - */ - public String getEventId() { - return (String) this.eventData.get(EVENT_ID); - } - - /** - * Set the event identifier. - * - * @param eventId - * The event identifier. - */ - public void setEventId(String eventId) { - if (eventId == null) { - throw new IllegalArgumentException("eventId cannot be null"); - } - this.eventData.put(EVENT_ID, eventId); - } - - /** - * Retrieve the message text associated with this event, if any. - * - * @return The message text associated with this event or null if there is - * none. - */ - public String getMessage() { - return (String) this.eventData.get(EVENT_MESSAGE); - } - - /** - * Set the message text associated with this event. - * - * @param message - * The message text. - */ - public void setMessage(String message) { - this.eventData.put(EVENT_MESSAGE, message); - } - - /** - * Retrieve the date and time the event occurred. - * - * @return The Date associated with the event. - */ - public Date getEventDateTime() { - return (Date) this.eventData.get(EVENT_DATETIME); - } - - /** - * Set the date and time the event occurred in case it is not the same as when - * the event was logged. - * - * @param eventDateTime - * The event Date. - */ - public void setEventDateTime(Date eventDateTime) { - this.eventData.put(EVENT_DATETIME, eventDateTime); - } - - /** - * Set the type of event that occurred. - * - * @param eventType - * The type of the event. - */ - public void setEventType(String eventType) { - this.eventData.put(EVENT_TYPE, eventType); - } - - /** - * Retrieve the type of the event. - * - * @return The event type. - */ - public String getEventType() { - return (String) this.eventData.get(EVENT_TYPE); - } - - /** - * Add arbitrary attributes about the event. - * - * @param name - * The attribute's key. - * @param obj - * The data associated with the key. - */ - public void put(String name, Serializable obj) { - this.eventData.put(name, obj); - } - - /** - * Retrieve an event attribute. - * - * @param name - * The attribute's key. - * @return The value associated with the key or null if the key is not - * present. - */ - public Serializable get(String name) { - return (Serializable) this.eventData.get(name); - } - - /** - * Populate the event data from a Map. - * - * @param data - * The Map to copy. - */ - public void putAll(Map data) { - this.eventData.putAll(data); - } - - /** - * Returns the number of attributes in the EventData. - * - * @return the number of attributes in the EventData. - */ - public int getSize() { - return this.eventData.size(); - } - - /** - * Returns an Iterator over all the entries in the EventData. - * - * @return an Iterator that can be used to access all the event attributes. - */ - public Iterator> getEntrySetIterator() { - return this.eventData.entrySet().iterator(); - } - - /** - * Retrieve all the attributes in the EventData as a Map. Changes to this map - * will be reflected in the EventData. - * - * @return The Map of attributes in this EventData instance. - */ - public Map getEventMap() { - return this.eventData; - } - - /** - * Convert the EventData to a String. - * - * @return The EventData as a String. - */ - @Override - public String toString() { - return toXML(); - } - - /** - * Compare two EventData objects for equality. - * - * @param o - * The Object to compare. - * @return true if the objects are the same instance or contain all the same - * keys and their values. - */ - @SuppressWarnings("unchecked") - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof EventData || o instanceof Map)) { - return false; - } - Map map = (o instanceof EventData) ? ((EventData) o).getEventMap() : (Map) o; - - return this.eventData.equals(map); - } - - /** - * Compute the hashCode for this EventData instance. - * - * @return The hashcode for this EventData instance. - */ - @Override - public int hashCode() { - return this.eventData.hashCode(); - } -} \ No newline at end of file diff --git a/slf4j-ext/src/main/java/org/slf4j/ext/EventException.java b/slf4j-ext/src/main/java/org/slf4j/ext/EventException.java deleted file mode 100644 index d4dc3f9..0000000 --- a/slf4j-ext/src/main/java/org/slf4j/ext/EventException.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.ext; - -/** - * Exception used to identify issues related to an event that is being logged. - */ -public class EventException extends RuntimeException { - - private static final long serialVersionUID = -22873966112391992L; - - /** - * Default constructor. - */ - public EventException() { - super(); - } - - /** - * Constructor that allows an exception message. - * @param exceptionMessage The exception message. - */ - public EventException(String exceptionMessage) { - super(exceptionMessage); - } - - /** - * Constructor that chains another Exception or Error. - * @param originalException The original exception. - */ - public EventException(Throwable originalException) { - super(originalException); - } - - /** - * Constructor that chains another Exception or Error and also allows a message - * to be specified. - * @param exceptionMessage The exception message. - * @param originalException The original exception. - */ - public EventException(String exceptionMessage, Throwable originalException) { - super(exceptionMessage, originalException); - } -} diff --git a/slf4j-ext/src/main/java/org/slf4j/ext/EventLogger.java b/slf4j-ext/src/main/java/org/slf4j/ext/EventLogger.java deleted file mode 100644 index 024c6ad..0000000 --- a/slf4j-ext/src/main/java/org/slf4j/ext/EventLogger.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.ext; - -import org.slf4j.LoggerFactory; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; -import org.slf4j.spi.LocationAwareLogger; - -/** - * Simple Logger used to log events. All events are directed to a logger named "EventLogger" - * with a level of INFO and with an Event marker. - * - * @author Ralph Goers - */ -public class EventLogger { - - private static final String FQCN = EventLogger.class.getName(); - - static Marker EVENT_MARKER = MarkerFactory.getMarker("EVENT"); - - private static LoggerWrapper eventLogger = new LoggerWrapper(LoggerFactory.getLogger("EventLogger"), FQCN); - - /** - * There can only be a single EventLogger. - */ - private EventLogger() { - } - - /** - * Logs the event. - * - * @param data The EventData. - */ - public static void logEvent(EventData data) { - if (eventLogger.instanceofLAL) { - ((LocationAwareLogger) eventLogger.logger).log(EVENT_MARKER, FQCN, LocationAwareLogger.INFO_INT, data.toXML(), new Object[] { data }, null); - } else { - eventLogger.logger.info(EVENT_MARKER, data.toXML(), data); - } - } -} diff --git a/slf4j-ext/src/main/java/org/slf4j/ext/LoggerWrapper.java b/slf4j-ext/src/main/java/org/slf4j/ext/LoggerWrapper.java index 1a6f80d..392ddaf 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/LoggerWrapper.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/LoggerWrapper.java @@ -1,844 +1,844 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.ext; - -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.helpers.FormattingTuple; -import org.slf4j.helpers.MessageFormatter; -import org.slf4j.spi.LocationAwareLogger; - -/** - * A helper class wrapping an {@link org.slf4j.Logger} instance preserving - * location information if the wrapped instance supports it. - * - * @author Ralph Goers - * @author Ceki Gülcü - */ -public class LoggerWrapper implements Logger { - - // To ensure consistency between two instances sharing the same name - // (homonyms) - // a LoggerWrapper should not contain any state beyond - // the Logger instance it wraps. - // Note that 'instanceofLAL' directly depends on Logger. - // fqcn depend on the caller, but its value would not be different - // between successive invocations of a factory class - - protected final Logger logger; - final String fqcn; - // is this logger instance a LocationAwareLogger - protected final boolean instanceofLAL; - - public LoggerWrapper(Logger logger, String fqcn) { - this.logger = logger; - this.fqcn = fqcn; - if (logger instanceof LocationAwareLogger) { - instanceofLAL = true; - } else { - instanceofLAL = false; - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isTraceEnabled(Marker marker) { - return logger.isTraceEnabled(marker); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(String msg) { - if (!logger.isTraceEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null); - } else { - logger.trace(msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(String format, Object arg) { - if (!logger.isTraceEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg }, null); - } else { - logger.trace(format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(String format, Object arg1, Object arg2) { - if (!logger.isTraceEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg1, arg2 }, null); - } else { - logger.trace(format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(String format, Object... args) { - if (!logger.isTraceEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null); - } else { - logger.trace(format, args); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(String msg, Throwable t) { - if (!logger.isTraceEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, t); - } else { - logger.trace(msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(Marker marker, String msg) { - if (!logger.isTraceEnabled(marker)) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null); - } else { - logger.trace(marker, msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(Marker marker, String format, Object arg) { - if (!logger.isTraceEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg }, null); - } else { - logger.trace(marker, format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(Marker marker, String format, Object arg1, Object arg2) { - if (!logger.isTraceEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg1, arg2 }, null); - } else { - logger.trace(marker, format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(Marker marker, String format, Object... args) { - if (!logger.isTraceEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null); - } else { - logger.trace(marker, format, args); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(Marker marker, String msg, Throwable t) { - if (!logger.isTraceEnabled(marker)) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, msg, null, t); - } else { - logger.trace(marker, msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isDebugEnabled(Marker marker) { - return logger.isDebugEnabled(marker); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String msg) { - if (!logger.isDebugEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null); - } else { - logger.debug(msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String format, Object arg) { - if (!logger.isDebugEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg }, null); - } else { - logger.debug(format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String format, Object arg1, Object arg2) { - if (!logger.isDebugEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg1, arg2 }, null); - } else { - logger.debug(format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String format, Object... argArray) { - if (!logger.isDebugEnabled()) - return; - - if (instanceofLAL) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), ft.getArgArray(), ft.getThrowable()); - } else { - logger.debug(format, argArray); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String msg, Throwable t) { - if (!logger.isDebugEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, t); - } else { - logger.debug(msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(Marker marker, String msg) { - if (!logger.isDebugEnabled(marker)) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null); - } else { - logger.debug(marker, msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(Marker marker, String format, Object arg) { - if (!logger.isDebugEnabled(marker)) - return; - if (instanceofLAL) { - FormattingTuple ft = MessageFormatter.format(format, arg); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), ft.getArgArray(), ft.getThrowable()); - } else { - logger.debug(marker, format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(Marker marker, String format, Object arg1, Object arg2) { - if (!logger.isDebugEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg1, arg2 }, null); - } else { - logger.debug(marker, format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(Marker marker, String format, Object... argArray) { - if (!logger.isDebugEnabled(marker)) - return; - if (instanceofLAL) { - - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), argArray, ft.getThrowable()); - } else { - logger.debug(marker, format, argArray); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(Marker marker, String msg, Throwable t) { - if (!logger.isDebugEnabled(marker)) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, t); - } else { - logger.debug(marker, msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isInfoEnabled(Marker marker) { - return logger.isInfoEnabled(marker); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(String msg) { - if (!logger.isInfoEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, null); - } else { - logger.info(msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(String format, Object arg) { - if (!logger.isInfoEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null); - } else { - logger.info(format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(String format, Object arg1, Object arg2) { - if (!logger.isInfoEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg1, arg2 }, null); - } else { - logger.info(format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(String format, Object... args) { - if (!logger.isInfoEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, args, null); - } else { - logger.info(format, args); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(String msg, Throwable t) { - if (!logger.isInfoEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, t); - } else { - logger.info(msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(Marker marker, String msg) { - if (!logger.isInfoEnabled(marker)) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, msg, null, null); - } else { - logger.info(marker, msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(Marker marker, String format, Object arg) { - if (!logger.isInfoEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null); - } else { - logger.info(marker, format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(Marker marker, String format, Object arg1, Object arg2) { - if (!logger.isInfoEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg1, arg2 }, null); - } else { - logger.info(marker, format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(Marker marker, String format, Object... args) { - if (!logger.isInfoEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, args, null); - } else { - logger.info(marker, format, args); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(Marker marker, String msg, Throwable t) { - if (!logger.isInfoEnabled(marker)) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, msg, null, t); - } else { - logger.info(marker, msg, t); - } - } - - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isWarnEnabled(Marker marker) { - return logger.isWarnEnabled(marker); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(String msg) { - if (!logger.isWarnEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, null); - } else { - logger.warn(msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(String format, Object arg) { - if (!logger.isWarnEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg }, null); - } else { - logger.warn(format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(String format, Object arg1, Object arg2) { - if (!logger.isWarnEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null); - } else { - logger.warn(format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(String format, Object... args) { - if (!logger.isWarnEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, args, null); - } else { - logger.warn(format, args); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(String msg, Throwable t) { - if (!logger.isWarnEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, t); - } else { - logger.warn(msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(Marker marker, String msg) { - if (!logger.isWarnEnabled(marker)) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, msg, null, null); - } else { - logger.warn(marker, msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(Marker marker, String format, Object arg) { - if (!logger.isWarnEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg }, null); - } else { - logger.warn(marker, format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(Marker marker, String format, Object arg1, Object arg2) { - if (!logger.isWarnEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null); - } else { - logger.warn(marker, format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(Marker marker, String format, Object... args) { - if (!logger.isWarnEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, args, null); - } else { - logger.warn(marker, format, args); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(Marker marker, String msg, Throwable t) { - if (!logger.isWarnEnabled(marker)) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, msg, null, t); - } else { - logger.warn(marker, msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isErrorEnabled(Marker marker) { - return logger.isErrorEnabled(marker); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(String msg) { - if (!logger.isErrorEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null); - } else { - logger.error(msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(String format, Object arg) { - if (!logger.isErrorEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg }, null); - } else { - logger.error(format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(String format, Object arg1, Object arg2) { - if (!logger.isErrorEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null); - } else { - logger.error(format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(String format, Object... args) { - if (!logger.isErrorEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, args, null); - } else { - logger.error(format, args); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(String msg, Throwable t) { - if (!logger.isErrorEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t); - } else { - logger.error(msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(Marker marker, String msg) { - if (!logger.isErrorEnabled(marker)) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null); - } else { - logger.error(marker, msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(Marker marker, String format, Object arg) { - if (!logger.isErrorEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg }, null); - } else { - logger.error(marker, format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(Marker marker, String format, Object arg1, Object arg2) { - if (!logger.isErrorEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null); - } else { - logger.error(marker, format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(Marker marker, String format, Object... args) { - if (!logger.isErrorEnabled(marker)) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, args, null); - } else { - logger.error(marker, format, args); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(Marker marker, String msg, Throwable t) { - if (!logger.isErrorEnabled(marker)) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t); - } else { - logger.error(marker, msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public String getName() { - return logger.getName(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.ext; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.helpers.FormattingTuple; +import org.slf4j.helpers.MessageFormatter; +import org.slf4j.spi.LocationAwareLogger; + +/** + * A helper class wrapping an {@link org.slf4j.Logger} instance preserving + * location information if the wrapped instance supports it. + * + * @author Ralph Goers + * @author Ceki Gülcü + */ +public class LoggerWrapper implements Logger { + + // To ensure consistency between two instances sharing the same name + // (homonyms) + // a LoggerWrapper should not contain any state beyond + // the Logger instance it wraps. + // Note that 'instanceofLAL' directly depends on Logger. + // fqcn depend on the caller, but its value would not be different + // between successive invocations of a factory class + + protected final Logger logger; + final String fqcn; + // is this logger instance a LocationAwareLogger + protected final boolean instanceofLAL; + + public LoggerWrapper(Logger logger, String fqcn) { + this.logger = logger; + this.fqcn = fqcn; + if (logger instanceof LocationAwareLogger) { + instanceofLAL = true; + } else { + instanceofLAL = false; + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isTraceEnabled(Marker marker) { + return logger.isTraceEnabled(marker); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String msg) { + if (!logger.isTraceEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null); + } else { + logger.trace(msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String format, Object arg) { + if (!logger.isTraceEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg }, null); + } else { + logger.trace(format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String format, Object arg1, Object arg2) { + if (!logger.isTraceEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg1, arg2 }, null); + } else { + logger.trace(format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String format, Object... args) { + if (!logger.isTraceEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null); + } else { + logger.trace(format, args); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String msg, Throwable t) { + if (!logger.isTraceEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, msg, null, t); + } else { + logger.trace(msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(Marker marker, String msg) { + if (!logger.isTraceEnabled(marker)) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, msg, null, null); + } else { + logger.trace(marker, msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(Marker marker, String format, Object arg) { + if (!logger.isTraceEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg }, null); + } else { + logger.trace(marker, format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(Marker marker, String format, Object arg1, Object arg2) { + if (!logger.isTraceEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, new Object[] { arg1, arg2 }, null); + } else { + logger.trace(marker, format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(Marker marker, String format, Object... args) { + if (!logger.isTraceEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null); + } else { + logger.trace(marker, format, args); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(Marker marker, String msg, Throwable t) { + if (!logger.isTraceEnabled(marker)) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.TRACE_INT, msg, null, t); + } else { + logger.trace(marker, msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isDebugEnabled(Marker marker) { + return logger.isDebugEnabled(marker); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String msg) { + if (!logger.isDebugEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null); + } else { + logger.debug(msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String format, Object arg) { + if (!logger.isDebugEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg }, null); + } else { + logger.debug(format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String format, Object arg1, Object arg2) { + if (!logger.isDebugEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg1, arg2 }, null); + } else { + logger.debug(format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String format, Object... argArray) { + if (!logger.isDebugEnabled()) + return; + + if (instanceofLAL) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), ft.getArgArray(), ft.getThrowable()); + } else { + logger.debug(format, argArray); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String msg, Throwable t) { + if (!logger.isDebugEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, t); + } else { + logger.debug(msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(Marker marker, String msg) { + if (!logger.isDebugEnabled(marker)) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, null); + } else { + logger.debug(marker, msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(Marker marker, String format, Object arg) { + if (!logger.isDebugEnabled(marker)) + return; + if (instanceofLAL) { + FormattingTuple ft = MessageFormatter.format(format, arg); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), ft.getArgArray(), ft.getThrowable()); + } else { + logger.debug(marker, format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(Marker marker, String format, Object arg1, Object arg2) { + if (!logger.isDebugEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, formattedMessage, new Object[] { arg1, arg2 }, null); + } else { + logger.debug(marker, format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(Marker marker, String format, Object... argArray) { + if (!logger.isDebugEnabled(marker)) + return; + if (instanceofLAL) { + + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), argArray, ft.getThrowable()); + } else { + logger.debug(marker, format, argArray); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(Marker marker, String msg, Throwable t) { + if (!logger.isDebugEnabled(marker)) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, msg, null, t); + } else { + logger.debug(marker, msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isInfoEnabled(Marker marker) { + return logger.isInfoEnabled(marker); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(String msg) { + if (!logger.isInfoEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, null); + } else { + logger.info(msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(String format, Object arg) { + if (!logger.isInfoEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null); + } else { + logger.info(format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(String format, Object arg1, Object arg2) { + if (!logger.isInfoEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg1, arg2 }, null); + } else { + logger.info(format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(String format, Object... args) { + if (!logger.isInfoEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, args, null); + } else { + logger.info(format, args); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(String msg, Throwable t) { + if (!logger.isInfoEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.INFO_INT, msg, null, t); + } else { + logger.info(msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(Marker marker, String msg) { + if (!logger.isInfoEnabled(marker)) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, msg, null, null); + } else { + logger.info(marker, msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(Marker marker, String format, Object arg) { + if (!logger.isInfoEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg }, null); + } else { + logger.info(marker, format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(Marker marker, String format, Object arg1, Object arg2) { + if (!logger.isInfoEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, new Object[] { arg1, arg2 }, null); + } else { + logger.info(marker, format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(Marker marker, String format, Object... args) { + if (!logger.isInfoEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, formattedMessage, args, null); + } else { + logger.info(marker, format, args); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(Marker marker, String msg, Throwable t) { + if (!logger.isInfoEnabled(marker)) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.INFO_INT, msg, null, t); + } else { + logger.info(marker, msg, t); + } + } + + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isWarnEnabled(Marker marker) { + return logger.isWarnEnabled(marker); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String msg) { + if (!logger.isWarnEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, null); + } else { + logger.warn(msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String format, Object arg) { + if (!logger.isWarnEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg }, null); + } else { + logger.warn(format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String format, Object arg1, Object arg2) { + if (!logger.isWarnEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null); + } else { + logger.warn(format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String format, Object... args) { + if (!logger.isWarnEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, args, null); + } else { + logger.warn(format, args); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String msg, Throwable t) { + if (!logger.isWarnEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.WARN_INT, msg, null, t); + } else { + logger.warn(msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(Marker marker, String msg) { + if (!logger.isWarnEnabled(marker)) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, msg, null, null); + } else { + logger.warn(marker, msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(Marker marker, String format, Object arg) { + if (!logger.isWarnEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg }, null); + } else { + logger.warn(marker, format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(Marker marker, String format, Object arg1, Object arg2) { + if (!logger.isWarnEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, new Object[] { arg1, arg2 }, null); + } else { + logger.warn(marker, format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(Marker marker, String format, Object... args) { + if (!logger.isWarnEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, formattedMessage, args, null); + } else { + logger.warn(marker, format, args); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(Marker marker, String msg, Throwable t) { + if (!logger.isWarnEnabled(marker)) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.WARN_INT, msg, null, t); + } else { + logger.warn(marker, msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isErrorEnabled(Marker marker) { + return logger.isErrorEnabled(marker); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(String msg) { + if (!logger.isErrorEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null); + } else { + logger.error(msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(String format, Object arg) { + if (!logger.isErrorEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg }, null); + } else { + logger.error(format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(String format, Object arg1, Object arg2) { + if (!logger.isErrorEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null); + } else { + logger.error(format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(String format, Object... args) { + if (!logger.isErrorEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, args, null); + } else { + logger.error(format, args); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(String msg, Throwable t) { + if (!logger.isErrorEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t); + } else { + logger.error(msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(Marker marker, String msg) { + if (!logger.isErrorEnabled(marker)) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, null); + } else { + logger.error(marker, msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(Marker marker, String format, Object arg) { + if (!logger.isErrorEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg }, null); + } else { + logger.error(marker, format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(Marker marker, String format, Object arg1, Object arg2) { + if (!logger.isErrorEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null); + } else { + logger.error(marker, format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(Marker marker, String format, Object... args) { + if (!logger.isErrorEnabled(marker)) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage(); + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, args, null); + } else { + logger.error(marker, format, args); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(Marker marker, String msg, Throwable t) { + if (!logger.isErrorEnabled(marker)) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, msg, null, t); + } else { + logger.error(marker, msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public String getName() { + return logger.getName(); + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/ext/MDCStrLookup.java b/slf4j-ext/src/main/java/org/slf4j/ext/MDCStrLookup.java index f7bb557..5d1e63c 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/MDCStrLookup.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/MDCStrLookup.java @@ -1,49 +1,49 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.ext; - -import org.apache.commons.lang.text.StrLookup; -import org.slf4j.MDC; - -/** - * This class can be used with the Commons Lang StrSubstitutor to replace - * tokens that occur in Strings with their values in the MDC. - * - * @author Ralph Goers - */ -public class MDCStrLookup extends StrLookup { - /** - * Looks up up a value in the MDC. - * - * @param key the key to be looked up, may be null - * @return the matching value, null if no match - */ - public String lookup(String key) { - if (key == null) { - return null; - } - return MDC.get(key); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.ext; + +import org.apache.commons.lang.text.StrLookup; +import org.slf4j.MDC; + +/** + * This class can be used with the Commons Lang StrSubstitutor to replace + * tokens that occur in Strings with their values in the MDC. + * + * @author Ralph Goers + */ +public class MDCStrLookup extends StrLookup { + /** + * Looks up up a value in the MDC. + * + * @param key the key to be looked up, may be null + * @return the matching value, null if no match + */ + public String lookup(String key) { + if (key == null) { + return null; + } + return MDC.get(key); + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java b/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java index 897f38f..9a10225 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java @@ -1,216 +1,216 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.ext; - -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.FormattingTuple; -import org.slf4j.helpers.MessageFormatter; -import org.slf4j.spi.LocationAwareLogger; - -/** - * A utility that provides standard mechanisms for logging certain kinds of - * activities. - * - * @author Ralph Goers - * @author Ceki Gülcü - */ -public class XLogger extends LoggerWrapper implements Logger { - - private static final String FQCN = XLogger.class.getName(); - static Marker FLOW_MARKER = MarkerFactory.getMarker("FLOW"); - static Marker ENTRY_MARKER = MarkerFactory.getMarker("ENTRY"); - static Marker EXIT_MARKER = MarkerFactory.getMarker("EXIT"); - - static Marker EXCEPTION_MARKER = MarkerFactory.getMarker("EXCEPTION"); - static Marker THROWING_MARKER = MarkerFactory.getMarker("THROWING"); - static Marker CATCHING_MARKER = MarkerFactory.getMarker("CATCHING"); - - static String EXIT_MESSAGE_0 = "exit"; - static String EXIT_MESSAGE_1 = "exit with ({})"; - - static String ENTRY_MESSAGE_0 = "entry"; - static String ENTRY_MESSAGE_1 = "entry with ({})"; - static String ENTRY_MESSAGE_2 = "entry with ({}, {})"; - static String ENTRY_MESSAGE_3 = "entry with ({}, {}, {})"; - static String ENTRY_MESSAGE_4 = "entry with ({}, {}, {}, {})"; - static int ENTRY_MESSAGE_ARRAY_LEN = 5; - static String[] ENTRY_MESSAGE_ARRAY = new String[ENTRY_MESSAGE_ARRAY_LEN]; - static { - ENTRY_MARKER.add(FLOW_MARKER); - EXIT_MARKER.add(FLOW_MARKER); - THROWING_MARKER.add(EXCEPTION_MARKER); - CATCHING_MARKER.add(EXCEPTION_MARKER); - - ENTRY_MESSAGE_ARRAY[0] = ENTRY_MESSAGE_0; - ENTRY_MESSAGE_ARRAY[1] = ENTRY_MESSAGE_1; - ENTRY_MESSAGE_ARRAY[2] = ENTRY_MESSAGE_2; - ENTRY_MESSAGE_ARRAY[3] = ENTRY_MESSAGE_3; - ENTRY_MESSAGE_ARRAY[4] = ENTRY_MESSAGE_4; - } - - public enum Level { - TRACE("TRACE", LocationAwareLogger.TRACE_INT), DEBUG("DEBUG", LocationAwareLogger.DEBUG_INT), INFO("INFO", LocationAwareLogger.INFO_INT), WARN("WARN", - LocationAwareLogger.WARN_INT), ERROR("ERROR", LocationAwareLogger.ERROR_INT); - - private final String name; - private final int level; - - public String toString() { - return this.name; - } - - public int intValue() { - return this.level; - } - - private Level(String name, int level) { - this.name = name; - this.level = level; - } - } - - /** - * Given an underlying logger, construct an XLogger - * - * @param logger - * underlying logger - */ - public XLogger(Logger logger) { - // If class B extends A, assuming B does not override method x(), the caller - // of new B().x() is A and not B, see also - // http://jira.qos.ch/browse/SLF4J-105 - super(logger, LoggerWrapper.class.getName()); - } - - /** - * Log method entry. - * - * @param argArray - * supplied parameters - */ - public void entry(Object... argArray) { - if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { - String messagePattern = null; - if (argArray.length < ENTRY_MESSAGE_ARRAY_LEN) { - messagePattern = ENTRY_MESSAGE_ARRAY[argArray.length]; - } else { - messagePattern = buildMessagePattern(argArray.length); - } - FormattingTuple tp = MessageFormatter.arrayFormat(messagePattern, argArray); - ((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), argArray, tp.getThrowable()); - } - } - - /** - * Log method exit - */ - public void exit() { - if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { - ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, EXIT_MESSAGE_0, null, null); - } - } - - /** - * Log method exit - * - * @param result - * The result of the method being exited - */ - public T exit(T result) { - if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { - FormattingTuple tp = MessageFormatter.format(EXIT_MESSAGE_1, result); - ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), new Object[] { result }, tp.getThrowable()); - } - return result; - } - - /** - * Log an exception being thrown. The generated log event uses Level ERROR. - * - * @param throwable - * the exception being caught. - */ - public T throwing(T throwable) { - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "throwing", null, throwable); - } - return throwable; - } - - /** - * Log an exception being thrown allowing the log level to be specified. - * - * @param level - * the logging level to use. - * @param throwable - * the exception being caught. - */ - public T throwing(Level level, T throwable) { - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, level.level, "throwing", null, throwable); - } - return throwable; - } - - /** - * Log an exception being caught. The generated log event uses Level ERROR. - * - * @param throwable - * the exception being caught. - */ - public void catching(Throwable throwable) { - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "catching", null, throwable); - } - } - - /** - * Log an exception being caught allowing the log level to be specified. - * - * @param level - * the logging level to use. - * @param throwable - * the exception being caught. - */ - public void catching(Level level, Throwable throwable) { - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, level.level, "catching", null, throwable); - } - } - - private static String buildMessagePattern(int len) { - StringBuilder sb = new StringBuilder(); - sb.append(" entry with ("); - for (int i = 0; i < len; i++) { - sb.append("{}"); - if (i != len - 1) - sb.append(", "); - } - sb.append(')'); - return sb.toString(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.ext; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.FormattingTuple; +import org.slf4j.helpers.MessageFormatter; +import org.slf4j.spi.LocationAwareLogger; + +/** + * A utility that provides standard mechanisms for logging certain kinds of + * activities. + * + * @author Ralph Goers + * @author Ceki Gülcü + */ +public class XLogger extends LoggerWrapper implements Logger { + + private static final String FQCN = XLogger.class.getName(); + static Marker FLOW_MARKER = MarkerFactory.getMarker("FLOW"); + static Marker ENTRY_MARKER = MarkerFactory.getMarker("ENTRY"); + static Marker EXIT_MARKER = MarkerFactory.getMarker("EXIT"); + + static Marker EXCEPTION_MARKER = MarkerFactory.getMarker("EXCEPTION"); + static Marker THROWING_MARKER = MarkerFactory.getMarker("THROWING"); + static Marker CATCHING_MARKER = MarkerFactory.getMarker("CATCHING"); + + static String EXIT_MESSAGE_0 = "exit"; + static String EXIT_MESSAGE_1 = "exit with ({})"; + + static String ENTRY_MESSAGE_0 = "entry"; + static String ENTRY_MESSAGE_1 = "entry with ({})"; + static String ENTRY_MESSAGE_2 = "entry with ({}, {})"; + static String ENTRY_MESSAGE_3 = "entry with ({}, {}, {})"; + static String ENTRY_MESSAGE_4 = "entry with ({}, {}, {}, {})"; + static int ENTRY_MESSAGE_ARRAY_LEN = 5; + static String[] ENTRY_MESSAGE_ARRAY = new String[ENTRY_MESSAGE_ARRAY_LEN]; + static { + ENTRY_MARKER.add(FLOW_MARKER); + EXIT_MARKER.add(FLOW_MARKER); + THROWING_MARKER.add(EXCEPTION_MARKER); + CATCHING_MARKER.add(EXCEPTION_MARKER); + + ENTRY_MESSAGE_ARRAY[0] = ENTRY_MESSAGE_0; + ENTRY_MESSAGE_ARRAY[1] = ENTRY_MESSAGE_1; + ENTRY_MESSAGE_ARRAY[2] = ENTRY_MESSAGE_2; + ENTRY_MESSAGE_ARRAY[3] = ENTRY_MESSAGE_3; + ENTRY_MESSAGE_ARRAY[4] = ENTRY_MESSAGE_4; + } + + public enum Level { + TRACE("TRACE", LocationAwareLogger.TRACE_INT), DEBUG("DEBUG", LocationAwareLogger.DEBUG_INT), INFO("INFO", LocationAwareLogger.INFO_INT), WARN("WARN", + LocationAwareLogger.WARN_INT), ERROR("ERROR", LocationAwareLogger.ERROR_INT); + + private final String name; + private final int level; + + public String toString() { + return this.name; + } + + public int intValue() { + return this.level; + } + + private Level(String name, int level) { + this.name = name; + this.level = level; + } + } + + /** + * Given an underlying logger, construct an XLogger + * + * @param logger + * underlying logger + */ + public XLogger(Logger logger) { + // If class B extends A, assuming B does not override method x(), the caller + // of new B().x() is A and not B, see also + // http://jira.qos.ch/browse/SLF4J-105 + super(logger, LoggerWrapper.class.getName()); + } + + /** + * Log method entry. + * + * @param argArray + * supplied parameters + */ + public void entry(Object... argArray) { + if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { + String messagePattern = null; + if (argArray.length < ENTRY_MESSAGE_ARRAY_LEN) { + messagePattern = ENTRY_MESSAGE_ARRAY[argArray.length]; + } else { + messagePattern = buildMessagePattern(argArray.length); + } + FormattingTuple tp = MessageFormatter.arrayFormat(messagePattern, argArray); + ((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), argArray, tp.getThrowable()); + } + } + + /** + * Log method exit + */ + public void exit() { + if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { + ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, EXIT_MESSAGE_0, null, null); + } + } + + /** + * Log method exit + * + * @param result + * The result of the method being exited + */ + public T exit(T result) { + if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { + FormattingTuple tp = MessageFormatter.format(EXIT_MESSAGE_1, result); + ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, LocationAwareLogger.TRACE_INT, tp.getMessage(), new Object[] { result }, tp.getThrowable()); + } + return result; + } + + /** + * Log an exception being thrown. The generated log event uses Level ERROR. + * + * @param throwable + * the exception being caught. + */ + public T throwing(T throwable) { + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "throwing", null, throwable); + } + return throwable; + } + + /** + * Log an exception being thrown allowing the log level to be specified. + * + * @param level + * the logging level to use. + * @param throwable + * the exception being caught. + */ + public T throwing(Level level, T throwable) { + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, level.level, "throwing", null, throwable); + } + return throwable; + } + + /** + * Log an exception being caught. The generated log event uses Level ERROR. + * + * @param throwable + * the exception being caught. + */ + public void catching(Throwable throwable) { + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, LocationAwareLogger.ERROR_INT, "catching", null, throwable); + } + } + + /** + * Log an exception being caught allowing the log level to be specified. + * + * @param level + * the logging level to use. + * @param throwable + * the exception being caught. + */ + public void catching(Level level, Throwable throwable) { + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(CATCHING_MARKER, FQCN, level.level, "catching", null, throwable); + } + } + + private static String buildMessagePattern(int len) { + StringBuilder sb = new StringBuilder(); + sb.append(" entry with ("); + for (int i = 0; i < len; i++) { + sb.append("{}"); + if (i != len - 1) + sb.append(", "); + } + sb.append(')'); + return sb.toString(); + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/ext/XLoggerFactory.java b/slf4j-ext/src/main/java/org/slf4j/ext/XLoggerFactory.java index d85e57b..846a56e 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/XLoggerFactory.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/XLoggerFactory.java @@ -1,65 +1,65 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.ext; - -import org.slf4j.LoggerFactory; - -/** - * - * This class is essentially a wrapper around an - * {@link LoggerFactory} producing {@link XLogger} instances. - * - *

Contrary to {@link LoggerFactory#getLogger(String)} method of - * {@link LoggerFactory}, each call to {@link #getXLogger(String)} - * produces a new instance of XLogger. This should not matter - * because an XLogger instance does not have any state beyond that of - * the {@link org.slf4j.Logger Logger} instance it wraps. - * - * @author Ralph Goers - * @author Ceki Gülcü - */ -public class XLoggerFactory { - - /** - * Get an XLogger instance by name. - * - * @param name - * @return XLogger instance - */ - public static XLogger getXLogger(String name) { - return new XLogger(LoggerFactory.getLogger(name)); - } - - /** - * Get a new XLogger instance by class. The returned XLogger - * will be named after the class. - * - * @param clazz - * @return XLogger instance by name - */ - public static XLogger getXLogger(Class clazz) { - return getXLogger(clazz.getName()); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.ext; + +import org.slf4j.LoggerFactory; + +/** + * + * This class is essentially a wrapper around an + * {@link LoggerFactory} producing {@link XLogger} instances. + * + *

Contrary to {@link LoggerFactory#getLogger(String)} method of + * {@link LoggerFactory}, each call to {@link #getXLogger(String)} + * produces a new instance of XLogger. This should not matter + * because an XLogger instance does not have any state beyond that of + * the {@link org.slf4j.Logger Logger} instance it wraps. + * + * @author Ralph Goers + * @author Ceki Gülcü + */ +public class XLoggerFactory { + + /** + * Get an XLogger instance by name. + * + * @param name + * @return XLogger instance + */ + public static XLogger getXLogger(String name) { + return new XLogger(LoggerFactory.getLogger(name)); + } + + /** + * Get a new XLogger instance by class. The returned XLogger + * will be named after the class. + * + * @param clazz + * @return XLogger instance by name + */ + public static XLogger getXLogger(Class clazz) { + return getXLogger(clazz.getName()); + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/ext/package.html b/slf4j-ext/src/main/java/org/slf4j/ext/package.html index c90e0d9..5c55a91 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/package.html +++ b/slf4j-ext/src/main/java/org/slf4j/ext/package.html @@ -1,12 +1,12 @@ - - - - - - - - - -

Localized logging using the CAL10N API.

- - + + + + + + + + + +

Localized logging using the CAL10N API.

+ + diff --git a/slf4j-ext/src/main/java/org/slf4j/instrumentation/JavassistHelper.java b/slf4j-ext/src/main/java/org/slf4j/instrumentation/JavassistHelper.java index 3e0e14e..8799e56 100644 --- a/slf4j-ext/src/main/java/org/slf4j/instrumentation/JavassistHelper.java +++ b/slf4j-ext/src/main/java/org/slf4j/instrumentation/JavassistHelper.java @@ -1,186 +1,186 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.instrumentation; - -import javassist.CtBehavior; -import javassist.CtClass; -import javassist.CtMethod; -import javassist.Modifier; -import javassist.NotFoundException; -import javassist.bytecode.AttributeInfo; -import javassist.bytecode.CodeAttribute; -import javassist.bytecode.LocalVariableAttribute; - -/** - * Helper methods for Javassist functionality. - * - */ -public class JavassistHelper { - - /** - * Create a javassist source snippet which either is empty (for anything - * which does not return a value) or a explanatory text around the $_ - * javassist return value variable. - * - * @param method - * descriptor of method - * @return source snippet - * @throws NotFoundException - */ - public static String returnValue(CtBehavior method) throws NotFoundException { - - String returnValue = ""; - if (methodReturnsValue(method)) { - returnValue = " returns: \" + $_ + \"."; - } - return returnValue; - } - - /** - * determine if the given method returns a value, and return true if so. - * false otherwise. - * - * @param method - * @return - * @throws NotFoundException - */ - private static boolean methodReturnsValue(CtBehavior method) throws NotFoundException { - - if (method instanceof CtMethod == false) { - return false; - } - - CtClass returnType = ((CtMethod) method).getReturnType(); - String returnTypeName = returnType.getName(); - - boolean isVoidMethod = "void".equals(returnTypeName); - - boolean methodReturnsValue = isVoidMethod == false; - return methodReturnsValue; - } - - /** - * Return javassist source snippet which lists all the parameters and their - * values. If available the source names are extracted from the debug - * information and used, otherwise just a number is shown. - * - * @param method - * @return - * @throws NotFoundException - */ - public static String getSignature(CtBehavior method) throws NotFoundException { - - CtClass[] parameterTypes = method.getParameterTypes(); - - CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute(); - - LocalVariableAttribute locals = null; - - if (codeAttribute != null) { - AttributeInfo attribute; - attribute = codeAttribute.getAttribute("LocalVariableTable"); - locals = (LocalVariableAttribute) attribute; - } - - String methodName = method.getName(); - - StringBuilder sb = new StringBuilder(methodName).append("(\" "); - for (int i = 0; i < parameterTypes.length; i++) { - if (i > 0) { - // add a comma and a space between printed values - sb.append(" + \", \" "); - } - - CtClass parameterType = parameterTypes[i]; - boolean isArray = parameterType.isArray(); - CtClass arrayType = parameterType.getComponentType(); - if (isArray) { - while (arrayType.isArray()) { - arrayType = arrayType.getComponentType(); - } - } - - sb.append(" + \""); - try { - sb.append(parameterNameFor(method, locals, i)); - } catch (Exception e) { - sb.append(i + 1); - } - sb.append("\" + \"="); - - if (parameterType.isPrimitive()) { - // let the compiler handle primitive -> string - sb.append("\"+ $").append(i + 1); - } else { - String s = "org.slf4j.instrumentation.ToStringHelper.render"; - sb.append("\"+ ").append(s).append("($").append(i + 1).append(')'); - } - } - sb.append("+\")"); - - String signature = sb.toString(); - return signature; - } - - /** - * Determine the name of parameter with index i in the given method. Use the - * locals attributes about local variables from the classfile. Note: This is - * still work in progress. - * - * @param method - * @param locals - * @param i - * @return the name of the parameter if available or a number if not. - */ - static String parameterNameFor(CtBehavior method, LocalVariableAttribute locals, int i) { - - if (locals == null) { - return Integer.toString(i + 1); - } - - int modifiers = method.getModifiers(); - - int j = i; - - if (Modifier.isSynchronized(modifiers)) { - // skip object to synchronize upon. - j++; - // System.err.println("Synchronized"); - } - if (Modifier.isStatic(modifiers) == false) { - // skip "this" - j++; - // System.err.println("Instance"); - } - String variableName = locals.variableName(j); - // if (variableName.equals("this")) { - // System.err.println("'this' returned as a parameter name for " - // + method.getName() + " index " + j - // + - // ", names are probably shifted. Please submit source for class in slf4j bugreport"); - // } - return variableName; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.instrumentation; + +import javassist.CtBehavior; +import javassist.CtClass; +import javassist.CtMethod; +import javassist.Modifier; +import javassist.NotFoundException; +import javassist.bytecode.AttributeInfo; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.LocalVariableAttribute; + +/** + * Helper methods for Javassist functionality. + * + */ +public class JavassistHelper { + + /** + * Create a javassist source snippet which either is empty (for anything + * which does not return a value) or a explanatory text around the $_ + * javassist return value variable. + * + * @param method + * descriptor of method + * @return source snippet + * @throws NotFoundException + */ + public static String returnValue(CtBehavior method) throws NotFoundException { + + String returnValue = ""; + if (methodReturnsValue(method)) { + returnValue = " returns: \" + $_ + \"."; + } + return returnValue; + } + + /** + * determine if the given method returns a value, and return true if so. + * false otherwise. + * + * @param method + * @return + * @throws NotFoundException + */ + private static boolean methodReturnsValue(CtBehavior method) throws NotFoundException { + + if (method instanceof CtMethod == false) { + return false; + } + + CtClass returnType = ((CtMethod) method).getReturnType(); + String returnTypeName = returnType.getName(); + + boolean isVoidMethod = "void".equals(returnTypeName); + + boolean methodReturnsValue = isVoidMethod == false; + return methodReturnsValue; + } + + /** + * Return javassist source snippet which lists all the parameters and their + * values. If available the source names are extracted from the debug + * information and used, otherwise just a number is shown. + * + * @param method + * @return + * @throws NotFoundException + */ + public static String getSignature(CtBehavior method) throws NotFoundException { + + CtClass[] parameterTypes = method.getParameterTypes(); + + CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute(); + + LocalVariableAttribute locals = null; + + if (codeAttribute != null) { + AttributeInfo attribute; + attribute = codeAttribute.getAttribute("LocalVariableTable"); + locals = (LocalVariableAttribute) attribute; + } + + String methodName = method.getName(); + + StringBuilder sb = new StringBuilder(methodName).append("(\" "); + for (int i = 0; i < parameterTypes.length; i++) { + if (i > 0) { + // add a comma and a space between printed values + sb.append(" + \", \" "); + } + + CtClass parameterType = parameterTypes[i]; + boolean isArray = parameterType.isArray(); + CtClass arrayType = parameterType.getComponentType(); + if (isArray) { + while (arrayType.isArray()) { + arrayType = arrayType.getComponentType(); + } + } + + sb.append(" + \""); + try { + sb.append(parameterNameFor(method, locals, i)); + } catch (Exception e) { + sb.append(i + 1); + } + sb.append("\" + \"="); + + if (parameterType.isPrimitive()) { + // let the compiler handle primitive -> string + sb.append("\"+ $").append(i + 1); + } else { + String s = "org.slf4j.instrumentation.ToStringHelper.render"; + sb.append("\"+ ").append(s).append("($").append(i + 1).append(')'); + } + } + sb.append("+\")"); + + String signature = sb.toString(); + return signature; + } + + /** + * Determine the name of parameter with index i in the given method. Use the + * locals attributes about local variables from the classfile. Note: This is + * still work in progress. + * + * @param method + * @param locals + * @param i + * @return the name of the parameter if available or a number if not. + */ + static String parameterNameFor(CtBehavior method, LocalVariableAttribute locals, int i) { + + if (locals == null) { + return Integer.toString(i + 1); + } + + int modifiers = method.getModifiers(); + + int j = i; + + if (Modifier.isSynchronized(modifiers)) { + // skip object to synchronize upon. + j++; + // System.err.println("Synchronized"); + } + if (Modifier.isStatic(modifiers) == false) { + // skip "this" + j++; + // System.err.println("Instance"); + } + String variableName = locals.variableName(j); + // if (variableName.equals("this")) { + // System.err.println("'this' returned as a parameter name for " + // + method.getName() + " index " + j + // + + // ", names are probably shifted. Please submit source for class in slf4j bugreport"); + // } + return variableName; + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/instrumentation/LogTransformer.java b/slf4j-ext/src/main/java/org/slf4j/instrumentation/LogTransformer.java index 0089bd4..bc0e9a8 100644 --- a/slf4j-ext/src/main/java/org/slf4j/instrumentation/LogTransformer.java +++ b/slf4j-ext/src/main/java/org/slf4j/instrumentation/LogTransformer.java @@ -1,312 +1,312 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -/** - * - */ -package org.slf4j.instrumentation; - -import static org.slf4j.helpers.MessageFormatter.format; - -import java.io.ByteArrayInputStream; -import java.lang.instrument.ClassFileTransformer; -import java.security.ProtectionDomain; - -import javassist.CannotCompileException; -import javassist.ClassPool; -import javassist.CtBehavior; -import javassist.CtClass; -import javassist.CtField; -import javassist.NotFoundException; - -import org.slf4j.helpers.MessageFormatter; - -/** - *

- * LogTransformer does the work of analyzing each class, and if appropriate add - * log statements to each method to allow logging entry/exit. - *

- *

- * This class is based on the article Add Logging at Class Load Time with Java Instrumentation. - *

- */ -public class LogTransformer implements ClassFileTransformer { - - /** - * Builder provides a flexible way of configuring some of many options on the - * parent class instead of providing many constructors. - * - * http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html - * - */ - public static class Builder { - - /** - * Build and return the LogTransformer corresponding to the options set in - * this Builder. - * - * @return - */ - public LogTransformer build() { - if (verbose) { - System.err.println("Creating LogTransformer"); - } - return new LogTransformer(this); - } - - boolean addEntryExit; - - /** - * Should each method log entry (with parameters) and exit (with parameters - * and return value)? - * - * @param b - * value of flag - * @return - */ - public Builder addEntryExit(boolean b) { - addEntryExit = b; - return this; - } - - boolean addVariableAssignment; - - // private Builder addVariableAssignment(boolean b) { - // System.err.println("cannot currently log variable assignments."); - // addVariableAssignment = b; - // return this; - // } - - boolean verbose; - - /** - * Should LogTransformer be verbose in what it does? This currently list the - * names of the classes being processed. - * - * @param b - * @return - */ - public Builder verbose(boolean b) { - verbose = b; - return this; - } - - String[] ignore = { "org/slf4j/", "ch/qos/logback/", "org/apache/log4j/" }; - - public Builder ignore(String[] strings) { - this.ignore = strings; - return this; - } - - private String level = "info"; - - public Builder level(String level) { - level = level.toLowerCase(); - if (level.equals("info") || level.equals("debug") || level.equals("trace")) { - this.level = level; - } else { - if (verbose) { - System.err.println("level not info/debug/trace : " + level); - } - } - return this; - } - } - - private String level; - private String levelEnabled; - - private LogTransformer(Builder builder) { - String s = "WARNING: javassist not available on classpath for javaagent, log statements will not be added"; - try { - if (Class.forName("javassist.ClassPool") == null) { - System.err.println(s); - } - } catch (ClassNotFoundException e) { - System.err.println(s); - } - - this.addEntryExit = builder.addEntryExit; - // this.addVariableAssignment = builder.addVariableAssignment; - this.verbose = builder.verbose; - this.ignore = builder.ignore; - this.level = builder.level; - this.levelEnabled = "is" + builder.level.substring(0, 1).toUpperCase() + builder.level.substring(1) + "Enabled"; - } - - private boolean addEntryExit; - // private boolean addVariableAssignment; - private boolean verbose; - private String[] ignore; - - public byte[] transform(ClassLoader loader, String className, Class clazz, ProtectionDomain domain, byte[] bytes) { - - try { - return transform0(className, clazz, domain, bytes); - } catch (Exception e) { - System.err.println("Could not instrument " + className); - e.printStackTrace(); - return bytes; - } - } - - /** - * transform0 sees if the className starts with any of the namespaces to - * ignore, if so it is returned unchanged. Otherwise it is processed by - * doClass(...) - * - * @param className - * @param clazz - * @param domain - * @param bytes - * @return - */ - - private byte[] transform0(String className, Class clazz, ProtectionDomain domain, byte[] bytes) { - - try { - for (int i = 0; i < ignore.length; i++) { - if (className.startsWith(ignore[i])) { - return bytes; - } - } - String slf4jName = "org.slf4j.LoggerFactory"; - try { - if (domain != null && domain.getClassLoader() != null) { - domain.getClassLoader().loadClass(slf4jName); - } else { - if (verbose) { - System.err.println("Skipping " + className + " as it doesn't have a domain or a class loader."); - } - return bytes; - } - } catch (ClassNotFoundException e) { - if (verbose) { - System.err.println("Skipping " + className + " as slf4j is not available to it"); - } - return bytes; - } - if (verbose) { - System.err.println("Processing " + className); - } - return doClass(className, clazz, bytes); - } catch (Throwable e) { - System.out.println("e = " + e); - return bytes; - } - } - - private String loggerName; - - /** - * doClass() process a single class by first creates a class description from - * the byte codes. If it is a class (i.e. not an interface) the methods - * defined have bodies, and a static final logger object is added with the - * name of this class as an argument, and each method then gets processed with - * doMethod(...) to have logger calls added. - * - * @param name - * class name (slashes separate, not dots) - * @param clazz - * @param b - * @return - */ - private byte[] doClass(String name, Class clazz, byte[] b) { - ClassPool pool = ClassPool.getDefault(); - CtClass cl = null; - try { - cl = pool.makeClass(new ByteArrayInputStream(b)); - if (cl.isInterface() == false) { - - loggerName = "_____log"; - - // We have to declare the log variable. - - String pattern1 = "private static org.slf4j.Logger {};"; - String loggerDefinition = format(pattern1, loggerName).getMessage(); - CtField field = CtField.make(loggerDefinition, cl); - - // and assign it the appropriate value. - - String pattern2 = "org.slf4j.LoggerFactory.getLogger({}.class);"; - String replace = name.replace('/', '.'); - String getLogger = format(pattern2, replace).getMessage(); - - cl.addField(field, getLogger); - - // then check every behaviour (which includes methods). We are - // only - // interested in non-empty ones, as they have code. - // NOTE: This will be changed, as empty methods should be - // instrumented too. - - CtBehavior[] methods = cl.getDeclaredBehaviors(); - for (int i = 0; i < methods.length; i++) { - if (methods[i].isEmpty() == false) { - doMethod(methods[i]); - } - } - b = cl.toBytecode(); - } - } catch (Exception e) { - System.err.println("Could not instrument " + name + ", " + e); - e.printStackTrace(System.err); - } finally { - if (cl != null) { - cl.detach(); - } - } - return b; - } - - /** - * process a single method - this means add entry/exit logging if requested. - * It is only called for methods with a body. - * - * @param method - * method to work on - * @throws NotFoundException - * @throws CannotCompileException - */ - private void doMethod(CtBehavior method) throws NotFoundException, CannotCompileException { - - String signature = JavassistHelper.getSignature(method); - String returnValue = JavassistHelper.returnValue(method); - - if (addEntryExit) { - String messagePattern = "if ({}.{}()) {}.{}(\">> {}\");"; - Object[] arg1 = new Object[] { loggerName, levelEnabled, loggerName, level, signature }; - String before = MessageFormatter.arrayFormat(messagePattern, arg1).getMessage(); - // System.out.println(before); - method.insertBefore(before); - - String messagePattern2 = "if ({}.{}()) {}.{}(\"<< {}{}\");"; - Object[] arg2 = new Object[] { loggerName, levelEnabled, loggerName, level, signature, returnValue }; - String after = MessageFormatter.arrayFormat(messagePattern2, arg2).getMessage(); - // System.out.println(after); - method.insertAfter(after); - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +/** + * + */ +package org.slf4j.instrumentation; + +import static org.slf4j.helpers.MessageFormatter.format; + +import java.io.ByteArrayInputStream; +import java.lang.instrument.ClassFileTransformer; +import java.security.ProtectionDomain; + +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtBehavior; +import javassist.CtClass; +import javassist.CtField; +import javassist.NotFoundException; + +import org.slf4j.helpers.MessageFormatter; + +/** + *

+ * LogTransformer does the work of analyzing each class, and if appropriate add + * log statements to each method to allow logging entry/exit. + *

+ *

+ * This class is based on the article Add Logging at Class Load Time with Java Instrumentation. + *

+ */ +public class LogTransformer implements ClassFileTransformer { + + /** + * Builder provides a flexible way of configuring some of many options on the + * parent class instead of providing many constructors. + * + * http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html + * + */ + public static class Builder { + + /** + * Build and return the LogTransformer corresponding to the options set in + * this Builder. + * + * @return + */ + public LogTransformer build() { + if (verbose) { + System.err.println("Creating LogTransformer"); + } + return new LogTransformer(this); + } + + boolean addEntryExit; + + /** + * Should each method log entry (with parameters) and exit (with parameters + * and return value)? + * + * @param b + * value of flag + * @return + */ + public Builder addEntryExit(boolean b) { + addEntryExit = b; + return this; + } + + boolean addVariableAssignment; + + // private Builder addVariableAssignment(boolean b) { + // System.err.println("cannot currently log variable assignments."); + // addVariableAssignment = b; + // return this; + // } + + boolean verbose; + + /** + * Should LogTransformer be verbose in what it does? This currently list the + * names of the classes being processed. + * + * @param b + * @return + */ + public Builder verbose(boolean b) { + verbose = b; + return this; + } + + String[] ignore = { "org/slf4j/", "ch/qos/logback/", "org/apache/log4j/" }; + + public Builder ignore(String[] strings) { + this.ignore = strings; + return this; + } + + private String level = "info"; + + public Builder level(String level) { + level = level.toLowerCase(); + if (level.equals("info") || level.equals("debug") || level.equals("trace")) { + this.level = level; + } else { + if (verbose) { + System.err.println("level not info/debug/trace : " + level); + } + } + return this; + } + } + + private String level; + private String levelEnabled; + + private LogTransformer(Builder builder) { + String s = "WARNING: javassist not available on classpath for javaagent, log statements will not be added"; + try { + if (Class.forName("javassist.ClassPool") == null) { + System.err.println(s); + } + } catch (ClassNotFoundException e) { + System.err.println(s); + } + + this.addEntryExit = builder.addEntryExit; + // this.addVariableAssignment = builder.addVariableAssignment; + this.verbose = builder.verbose; + this.ignore = builder.ignore; + this.level = builder.level; + this.levelEnabled = "is" + builder.level.substring(0, 1).toUpperCase() + builder.level.substring(1) + "Enabled"; + } + + private boolean addEntryExit; + // private boolean addVariableAssignment; + private boolean verbose; + private String[] ignore; + + public byte[] transform(ClassLoader loader, String className, Class clazz, ProtectionDomain domain, byte[] bytes) { + + try { + return transform0(className, clazz, domain, bytes); + } catch (Exception e) { + System.err.println("Could not instrument " + className); + e.printStackTrace(); + return bytes; + } + } + + /** + * transform0 sees if the className starts with any of the namespaces to + * ignore, if so it is returned unchanged. Otherwise it is processed by + * doClass(...) + * + * @param className + * @param clazz + * @param domain + * @param bytes + * @return + */ + + private byte[] transform0(String className, Class clazz, ProtectionDomain domain, byte[] bytes) { + + try { + for (int i = 0; i < ignore.length; i++) { + if (className.startsWith(ignore[i])) { + return bytes; + } + } + String slf4jName = "org.slf4j.LoggerFactory"; + try { + if (domain != null && domain.getClassLoader() != null) { + domain.getClassLoader().loadClass(slf4jName); + } else { + if (verbose) { + System.err.println("Skipping " + className + " as it doesn't have a domain or a class loader."); + } + return bytes; + } + } catch (ClassNotFoundException e) { + if (verbose) { + System.err.println("Skipping " + className + " as slf4j is not available to it"); + } + return bytes; + } + if (verbose) { + System.err.println("Processing " + className); + } + return doClass(className, clazz, bytes); + } catch (Throwable e) { + System.out.println("e = " + e); + return bytes; + } + } + + private String loggerName; + + /** + * doClass() process a single class by first creates a class description from + * the byte codes. If it is a class (i.e. not an interface) the methods + * defined have bodies, and a static final logger object is added with the + * name of this class as an argument, and each method then gets processed with + * doMethod(...) to have logger calls added. + * + * @param name + * class name (slashes separate, not dots) + * @param clazz + * @param b + * @return + */ + private byte[] doClass(String name, Class clazz, byte[] b) { + ClassPool pool = ClassPool.getDefault(); + CtClass cl = null; + try { + cl = pool.makeClass(new ByteArrayInputStream(b)); + if (cl.isInterface() == false) { + + loggerName = "_____log"; + + // We have to declare the log variable. + + String pattern1 = "private static org.slf4j.Logger {};"; + String loggerDefinition = format(pattern1, loggerName).getMessage(); + CtField field = CtField.make(loggerDefinition, cl); + + // and assign it the appropriate value. + + String pattern2 = "org.slf4j.LoggerFactory.getLogger({}.class);"; + String replace = name.replace('/', '.'); + String getLogger = format(pattern2, replace).getMessage(); + + cl.addField(field, getLogger); + + // then check every behaviour (which includes methods). We are + // only + // interested in non-empty ones, as they have code. + // NOTE: This will be changed, as empty methods should be + // instrumented too. + + CtBehavior[] methods = cl.getDeclaredBehaviors(); + for (int i = 0; i < methods.length; i++) { + if (methods[i].isEmpty() == false) { + doMethod(methods[i]); + } + } + b = cl.toBytecode(); + } + } catch (Exception e) { + System.err.println("Could not instrument " + name + ", " + e); + e.printStackTrace(System.err); + } finally { + if (cl != null) { + cl.detach(); + } + } + return b; + } + + /** + * process a single method - this means add entry/exit logging if requested. + * It is only called for methods with a body. + * + * @param method + * method to work on + * @throws NotFoundException + * @throws CannotCompileException + */ + private void doMethod(CtBehavior method) throws NotFoundException, CannotCompileException { + + String signature = JavassistHelper.getSignature(method); + String returnValue = JavassistHelper.returnValue(method); + + if (addEntryExit) { + String messagePattern = "if ({}.{}()) {}.{}(\">> {}\");"; + Object[] arg1 = new Object[] { loggerName, levelEnabled, loggerName, level, signature }; + String before = MessageFormatter.arrayFormat(messagePattern, arg1).getMessage(); + // System.out.println(before); + method.insertBefore(before); + + String messagePattern2 = "if ({}.{}()) {}.{}(\"<< {}{}\");"; + Object[] arg2 = new Object[] { loggerName, levelEnabled, loggerName, level, signature, returnValue }; + String after = MessageFormatter.arrayFormat(messagePattern2, arg2).getMessage(); + // System.out.println(after); + method.insertAfter(after); + } + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/instrumentation/ToStringHelper.java b/slf4j-ext/src/main/java/org/slf4j/instrumentation/ToStringHelper.java index 330f93f..b20f585 100644 --- a/slf4j-ext/src/main/java/org/slf4j/instrumentation/ToStringHelper.java +++ b/slf4j-ext/src/main/java/org/slf4j/instrumentation/ToStringHelper.java @@ -1,191 +1,191 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.instrumentation; - -import java.util.Map; -import java.util.WeakHashMap; - -public class ToStringHelper { - - /** - * Prefix to use at the start of the representation. Always used. - */ - private static final String ARRAY_PREFIX = "["; - - /** - * Suffix to use at the end of the representation. Always used. - */ - private static final char ARRAY_SUFFIX = ']'; - - /** - * String separating each element when rendering an array. To be compatible - * with lists comma-space is used. - */ - - private static final char[] ELEMENT_SEPARATOR = ", ".toCharArray(); - - /** - * unrenderableClasses is essentially a Set of Class objects which has for - * some reason failed to render properly when invoked through a toString - * method call. To avoid memory leaks a data structure using weak references - * is needed, but unfortunately the runtime library does not contain a - * WeakHashSet class, so the behavior is emulated with a WeakHashmap with - * the class as the key, and a Long containing the value of - * System.currentTimeMilis when an instance of the class failed to render. - */ - - final static Map, Object> unrenderableClasses = new WeakHashMap, Object>(); - - /** - * Returns o.toString() unless it throws an exception (which causes it to be - * stored in unrenderableClasses) or already was present in - * unrenderableClasses. If so, the same string is returned as would have - * been returned by Object.toString(). Arrays get special treatment as they - * don't have usable toString methods. - * - * @param o - * incoming object to render. - * @return - */ - - public static String render(Object o) { - if (o == null) { - return String.valueOf(o); - } - Class objectClass = o.getClass(); - - if (unrenderableClasses.containsKey(objectClass) == false) { - try { - if (objectClass.isArray()) { - return renderArray(o, objectClass).toString(); - } else { - return o.toString(); - } - } catch (Exception e) { - Long now = new Long(System.currentTimeMillis()); - - System.err.println("Disabling exception throwing class " + objectClass.getName() + ", " + e.getMessage()); - - unrenderableClasses.put(objectClass, now); - } - } - String name = o.getClass().getName(); - return name + "@" + Integer.toHexString(o.hashCode()); - } - - /** - * renderArray returns an array similar to a List. If the array type is an - * object they are rendered with "render(object)" for each. If the array - * type is a primitive each element is added directly to the string buffer - * collecting the result. - * - * @param o - * @param objectClass - * @return - */ - private static StringBuilder renderArray(Object o, Class objectClass) { - Class componentType = objectClass.getComponentType(); - StringBuilder sb = new StringBuilder(ARRAY_PREFIX); - - if (componentType.isPrimitive() == false) { - Object[] oa = (Object[]) o; - for (int i = 0; i < oa.length; i++) { - if (i > 0) { - sb.append(ELEMENT_SEPARATOR); - } - sb.append(render(oa[i])); - } - } else { - if (Boolean.TYPE.equals(componentType)) { - boolean[] ba = (boolean[]) o; - for (int i = 0; i < ba.length; i++) { - if (i > 0) { - sb.append(ELEMENT_SEPARATOR); - } - sb.append(ba[i]); - } - } else if (Integer.TYPE.equals(componentType)) { - int[] ia = (int[]) o; - for (int i = 0; i < ia.length; i++) { - if (i > 0) { - sb.append(ELEMENT_SEPARATOR); - } - sb.append(ia[i]); - } - - } else if (Long.TYPE.equals(componentType)) { - long[] ia = (long[]) o; - for (int i = 0; i < ia.length; i++) { - if (i > 0) { - sb.append(ELEMENT_SEPARATOR); - } - sb.append(ia[i]); - } - } else if (Double.TYPE.equals(componentType)) { - double[] ia = (double[]) o; - for (int i = 0; i < ia.length; i++) { - if (i > 0) { - sb.append(ELEMENT_SEPARATOR); - } - sb.append(ia[i]); - } - } else if (Float.TYPE.equals(componentType)) { - float[] ia = (float[]) o; - for (int i = 0; i < ia.length; i++) { - if (i > 0) { - sb.append(ELEMENT_SEPARATOR); - } - sb.append(ia[i]); - } - } else if (Character.TYPE.equals(componentType)) { - char[] ia = (char[]) o; - for (int i = 0; i < ia.length; i++) { - if (i > 0) { - sb.append(ELEMENT_SEPARATOR); - } - sb.append(ia[i]); - } - } else if (Short.TYPE.equals(componentType)) { - short[] ia = (short[]) o; - for (int i = 0; i < ia.length; i++) { - if (i > 0) { - sb.append(ELEMENT_SEPARATOR); - } - sb.append(ia[i]); - } - } else if (Byte.TYPE.equals(componentType)) { - byte[] ia = (byte[]) o; - for (int i = 0; i < ia.length; i++) { - if (i > 0) { - sb.append(ELEMENT_SEPARATOR); - } - sb.append(ia[i]); - } - } - } - sb.append(ARRAY_SUFFIX); - return sb; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.instrumentation; + +import java.util.Map; +import java.util.WeakHashMap; + +public class ToStringHelper { + + /** + * Prefix to use at the start of the representation. Always used. + */ + private static final String ARRAY_PREFIX = "["; + + /** + * Suffix to use at the end of the representation. Always used. + */ + private static final char ARRAY_SUFFIX = ']'; + + /** + * String separating each element when rendering an array. To be compatible + * with lists comma-space is used. + */ + + private static final char[] ELEMENT_SEPARATOR = ", ".toCharArray(); + + /** + * unrenderableClasses is essentially a Set of Class objects which has for + * some reason failed to render properly when invoked through a toString + * method call. To avoid memory leaks a data structure using weak references + * is needed, but unfortunately the runtime library does not contain a + * WeakHashSet class, so the behavior is emulated with a WeakHashmap with + * the class as the key, and a Long containing the value of + * System.currentTimeMilis when an instance of the class failed to render. + */ + + final static Map, Object> unrenderableClasses = new WeakHashMap, Object>(); + + /** + * Returns o.toString() unless it throws an exception (which causes it to be + * stored in unrenderableClasses) or already was present in + * unrenderableClasses. If so, the same string is returned as would have + * been returned by Object.toString(). Arrays get special treatment as they + * don't have usable toString methods. + * + * @param o + * incoming object to render. + * @return + */ + + public static String render(Object o) { + if (o == null) { + return String.valueOf(o); + } + Class objectClass = o.getClass(); + + if (unrenderableClasses.containsKey(objectClass) == false) { + try { + if (objectClass.isArray()) { + return renderArray(o, objectClass).toString(); + } else { + return o.toString(); + } + } catch (Exception e) { + Long now = new Long(System.currentTimeMillis()); + + System.err.println("Disabling exception throwing class " + objectClass.getName() + ", " + e.getMessage()); + + unrenderableClasses.put(objectClass, now); + } + } + String name = o.getClass().getName(); + return name + "@" + Integer.toHexString(o.hashCode()); + } + + /** + * renderArray returns an array similar to a List. If the array type is an + * object they are rendered with "render(object)" for each. If the array + * type is a primitive each element is added directly to the string buffer + * collecting the result. + * + * @param o + * @param objectClass + * @return + */ + private static StringBuilder renderArray(Object o, Class objectClass) { + Class componentType = objectClass.getComponentType(); + StringBuilder sb = new StringBuilder(ARRAY_PREFIX); + + if (componentType.isPrimitive() == false) { + Object[] oa = (Object[]) o; + for (int i = 0; i < oa.length; i++) { + if (i > 0) { + sb.append(ELEMENT_SEPARATOR); + } + sb.append(render(oa[i])); + } + } else { + if (Boolean.TYPE.equals(componentType)) { + boolean[] ba = (boolean[]) o; + for (int i = 0; i < ba.length; i++) { + if (i > 0) { + sb.append(ELEMENT_SEPARATOR); + } + sb.append(ba[i]); + } + } else if (Integer.TYPE.equals(componentType)) { + int[] ia = (int[]) o; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + sb.append(ELEMENT_SEPARATOR); + } + sb.append(ia[i]); + } + + } else if (Long.TYPE.equals(componentType)) { + long[] ia = (long[]) o; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + sb.append(ELEMENT_SEPARATOR); + } + sb.append(ia[i]); + } + } else if (Double.TYPE.equals(componentType)) { + double[] ia = (double[]) o; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + sb.append(ELEMENT_SEPARATOR); + } + sb.append(ia[i]); + } + } else if (Float.TYPE.equals(componentType)) { + float[] ia = (float[]) o; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + sb.append(ELEMENT_SEPARATOR); + } + sb.append(ia[i]); + } + } else if (Character.TYPE.equals(componentType)) { + char[] ia = (char[]) o; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + sb.append(ELEMENT_SEPARATOR); + } + sb.append(ia[i]); + } + } else if (Short.TYPE.equals(componentType)) { + short[] ia = (short[]) o; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + sb.append(ELEMENT_SEPARATOR); + } + sb.append(ia[i]); + } + } else if (Byte.TYPE.equals(componentType)) { + byte[] ia = (byte[]) o; + for (int i = 0; i < ia.length; i++) { + if (i > 0) { + sb.append(ELEMENT_SEPARATOR); + } + sb.append(ia[i]); + } + } + } + sb.append(ARRAY_SUFFIX); + return sb; + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/instrumentation/package.html b/slf4j-ext/src/main/java/org/slf4j/instrumentation/package.html index 0afac0c..7600149 100644 --- a/slf4j-ext/src/main/java/org/slf4j/instrumentation/package.html +++ b/slf4j-ext/src/main/java/org/slf4j/instrumentation/package.html @@ -1,18 +1,18 @@ - - - - - - - - - -

Java instrumentation routines for SLF4J.

- -

Byte code instrumentation is an way to change behaviour of java -classes at load time. This is done in-between the original byte -codes are retrieved and the class object is constructed by the class -loader. Currently this depends on the javassist library from JBoss -(which in turn uses it extensively in their application server).

- - + + + + + + + + + +

Java instrumentation routines for SLF4J.

+ +

Byte code instrumentation is an way to change behaviour of java +classes at load time. This is done in-between the original byte +codes are retrieved and the class object is constructed by the class +loader. Currently this depends on the javassist library from JBoss +(which in turn uses it extensively in their application server).

+ + diff --git a/slf4j-ext/src/main/java/org/slf4j/profiler/DurationUnit.java b/slf4j-ext/src/main/java/org/slf4j/profiler/DurationUnit.java index 58c68ea..9205d3e 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/DurationUnit.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/DurationUnit.java @@ -1,35 +1,35 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -/** - * An enum of supported time units. - * - * @author Ceki - * - */ -public enum DurationUnit { - NANOSECOND, MICROSECOND, MILLISSECOND, SECOND; +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +/** + * An enum of supported time units. + * + * @author Ceki + * + */ +public enum DurationUnit { + NANOSECOND, MICROSECOND, MILLISSECOND, SECOND; }diff --git a/slf4j-ext/src/main/java/org/slf4j/profiler/Profiler.java b/slf4j-ext/src/main/java/org/slf4j/profiler/Profiler.java index 6557416..fc9afd9 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/Profiler.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/Profiler.java @@ -1,262 +1,262 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; - -// + Profiler [BAS] -// |-- elapsed time [doX] 0 milliseconds. -// |-- elapsed time [doYYYYY] 56 milliseconds. -// |--+ Profiler Y -// |-- elapsed time [doZ] 21 milliseconds. -// |-- elapsed time [doZ] 21 milliseconds. -// |-- Total elapsed time [Y] 78 milliseconds. -// |-- elapsed time [doZ] 21 milliseconds. -// |-- Total elapsed time [BAS] 78 milliseconds. - -/** - * A poor man's profiler to measure the time elapsed performing some lengthy - * task. - * - * @author Ceki Gülcü - */ -public class Profiler implements TimeInstrument { - - final static String PROFILER_MARKER_NAME = "PROFILER"; - - final static int MIN_SW_NAME_LENGTH = 24; - final static int MIN_SW_ELAPSED_TIME_NUMBER_LENGTH = 9; - - final String name; - final StopWatch globalStopWatch; - - List childTimeInstrumentList = new ArrayList(); - - // optional field - ProfilerRegistry profilerRegistry; - // optional field - Logger logger; - - public Profiler(String name) { - this.name = name; - this.globalStopWatch = new StopWatch(name); - } - - public String getName() { - return name; - } - - public ProfilerRegistry getProfilerRegistry() { - return profilerRegistry; - } - - public void registerWith(ProfilerRegistry profilerRegistry) { - if (profilerRegistry == null) { - return; - } - this.profilerRegistry = profilerRegistry; - profilerRegistry.put(this); - } - - public Logger getLogger() { - return logger; - } - - public void setLogger(Logger logger) { - this.logger = logger; - } - - /** - * Starts a child stop watch and stops any previously started time - * instruments. - */ - public void start(String name) { - stopLastTimeInstrument(); - StopWatch childSW = new StopWatch(name); - childTimeInstrumentList.add(childSW); - } - - public Profiler startNested(String name) { - stopLastTimeInstrument(); - Profiler nestedProfiler = new Profiler(name); - nestedProfiler.registerWith(profilerRegistry); - nestedProfiler.setLogger(logger); - childTimeInstrumentList.add(nestedProfiler); - return nestedProfiler; - } - - TimeInstrument getLastTimeInstrument() { - if (childTimeInstrumentList.size() > 0) { - return childTimeInstrumentList.get(childTimeInstrumentList.size() - 1); - } else { - return null; - } - } - - void stopLastTimeInstrument() { - TimeInstrument last = getLastTimeInstrument(); - if (last != null) { - last.stop(); - } - } - - // void stopNestedProfilers() { - // for (Object child : childTimeInstrumentList) { - // if (child instanceof Profiler) - // ((Profiler) child).stop(); - // } - // } - - public long elapsedTime() { - return globalStopWatch.elapsedTime(); - } - - public TimeInstrument stop() { - stopLastTimeInstrument(); - globalStopWatch.stop(); - return this; - } - - public TimeInstrumentStatus getStatus() { - return globalStopWatch.status; - } - - /** - * This method is used in tests. - */ - void sanityCheck() throws IllegalStateException { - if (getStatus() != TimeInstrumentStatus.STOPPED) { - throw new IllegalStateException("time instrument [" + getName() + " is not stopped"); - } - - long totalElapsed = globalStopWatch.elapsedTime(); - long childTotal = 0; - - for (TimeInstrument ti : childTimeInstrumentList) { - childTotal += ti.elapsedTime(); - if (ti.getStatus() != TimeInstrumentStatus.STOPPED) { - throw new IllegalStateException("time instrument [" + ti.getName() + " is not stopped"); - } - if (ti instanceof Profiler) { - Profiler nestedProfiler = (Profiler) ti; - nestedProfiler.sanityCheck(); - } - } - if (totalElapsed < childTotal) { - throw new IllegalStateException("children have a higher accumulated elapsed time"); - } - } - - static String TOP_PROFILER_FIRST_PREFIX = "+"; - static String NESTED_PROFILER_FIRST_PREFIX = "|---+"; - static String TOTAL_ELAPSED = " Total "; - static String SUBTOTAL_ELAPSED = " Subtotal "; - static String ELAPSED_TIME = " elapsed time "; - - public void print() { - System.out.println(toString()); - } - - @Override - public String toString() { - DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch); - return buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, ""); - } - - public void log() { - Marker profilerMarker = MarkerFactory.getMarker(PROFILER_MARKER_NAME); - if (logger == null) { - throw new NullPointerException("If you invoke the log() method, then you must associate a logger with this profiler."); - } - if (logger.isDebugEnabled(profilerMarker)) { - DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch); - String r = buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, ""); - logger.debug(profilerMarker, SpacePadder.LINE_SEP + r); - } - } - - /** - * Return a copy of the child instrument list for this Profiler instance. - * - * @return a copy of this instance's child time instrument list - * @since 1.5.9 - */ - public List getCopyOfChildTimeInstruments() { - List copy = new ArrayList(childTimeInstrumentList); - return copy; - } - - /** - * Return a copy of the global stopwatch of this Profiler instance. - * - * @return a copy of this instance's global stop watch - * @since 1.5.9 - */ - public StopWatch getCopyOfGlobalStopWatch() { - StopWatch copy = new StopWatch(globalStopWatch); - return copy; - } - - private String buildProfilerString(DurationUnit du, String firstPrefix, String label, String indentation) { - StringBuilder buf = new StringBuilder(); - - buf.append(firstPrefix); - buf.append(" Profiler ["); - buf.append(name); - buf.append("]"); - buf.append(SpacePadder.LINE_SEP); - for (TimeInstrument child : childTimeInstrumentList) { - if (child instanceof StopWatch) { - buildStopWatchString(buf, du, ELAPSED_TIME, indentation, (StopWatch) child); - } else if (child instanceof Profiler) { - Profiler profiler = (Profiler) child; - String subString = profiler.buildProfilerString(du, NESTED_PROFILER_FIRST_PREFIX, SUBTOTAL_ELAPSED, indentation + " "); - buf.append(subString); - buildStopWatchString(buf, du, ELAPSED_TIME, indentation, profiler.globalStopWatch); - } - } - buildStopWatchString(buf, du, label, indentation, globalStopWatch); - return buf.toString(); - } - - private static void buildStopWatchString(StringBuilder buf, DurationUnit du, String prefix, String indentation, StopWatch sw) { - - buf.append(indentation); - buf.append("|--"); - buf.append(prefix); - SpacePadder.leftPad(buf, "[" + sw.getName() + "]", MIN_SW_NAME_LENGTH); - buf.append(" "); - String timeStr = Util.durationInDurationUnitsAsStr(sw.elapsedTime(), du); - SpacePadder.leftPad(buf, timeStr, MIN_SW_ELAPSED_TIME_NUMBER_LENGTH); - buf.append(" "); - Util.appendDurationUnitAsStr(buf, du); - buf.append(SpacePadder.LINE_SEP); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +// + Profiler [BAS] +// |-- elapsed time [doX] 0 milliseconds. +// |-- elapsed time [doYYYYY] 56 milliseconds. +// |--+ Profiler Y +// |-- elapsed time [doZ] 21 milliseconds. +// |-- elapsed time [doZ] 21 milliseconds. +// |-- Total elapsed time [Y] 78 milliseconds. +// |-- elapsed time [doZ] 21 milliseconds. +// |-- Total elapsed time [BAS] 78 milliseconds. + +/** + * A poor man's profiler to measure the time elapsed performing some lengthy + * task. + * + * @author Ceki Gülcü + */ +public class Profiler implements TimeInstrument { + + final static String PROFILER_MARKER_NAME = "PROFILER"; + + final static int MIN_SW_NAME_LENGTH = 24; + final static int MIN_SW_ELAPSED_TIME_NUMBER_LENGTH = 9; + + final String name; + final StopWatch globalStopWatch; + + List childTimeInstrumentList = new ArrayList(); + + // optional field + ProfilerRegistry profilerRegistry; + // optional field + Logger logger; + + public Profiler(String name) { + this.name = name; + this.globalStopWatch = new StopWatch(name); + } + + public String getName() { + return name; + } + + public ProfilerRegistry getProfilerRegistry() { + return profilerRegistry; + } + + public void registerWith(ProfilerRegistry profilerRegistry) { + if (profilerRegistry == null) { + return; + } + this.profilerRegistry = profilerRegistry; + profilerRegistry.put(this); + } + + public Logger getLogger() { + return logger; + } + + public void setLogger(Logger logger) { + this.logger = logger; + } + + /** + * Starts a child stop watch and stops any previously started time + * instruments. + */ + public void start(String name) { + stopLastTimeInstrument(); + StopWatch childSW = new StopWatch(name); + childTimeInstrumentList.add(childSW); + } + + public Profiler startNested(String name) { + stopLastTimeInstrument(); + Profiler nestedProfiler = new Profiler(name); + nestedProfiler.registerWith(profilerRegistry); + nestedProfiler.setLogger(logger); + childTimeInstrumentList.add(nestedProfiler); + return nestedProfiler; + } + + TimeInstrument getLastTimeInstrument() { + if (childTimeInstrumentList.size() > 0) { + return childTimeInstrumentList.get(childTimeInstrumentList.size() - 1); + } else { + return null; + } + } + + void stopLastTimeInstrument() { + TimeInstrument last = getLastTimeInstrument(); + if (last != null) { + last.stop(); + } + } + + // void stopNestedProfilers() { + // for (Object child : childTimeInstrumentList) { + // if (child instanceof Profiler) + // ((Profiler) child).stop(); + // } + // } + + public long elapsedTime() { + return globalStopWatch.elapsedTime(); + } + + public TimeInstrument stop() { + stopLastTimeInstrument(); + globalStopWatch.stop(); + return this; + } + + public TimeInstrumentStatus getStatus() { + return globalStopWatch.status; + } + + /** + * This method is used in tests. + */ + void sanityCheck() throws IllegalStateException { + if (getStatus() != TimeInstrumentStatus.STOPPED) { + throw new IllegalStateException("time instrument [" + getName() + " is not stopped"); + } + + long totalElapsed = globalStopWatch.elapsedTime(); + long childTotal = 0; + + for (TimeInstrument ti : childTimeInstrumentList) { + childTotal += ti.elapsedTime(); + if (ti.getStatus() != TimeInstrumentStatus.STOPPED) { + throw new IllegalStateException("time instrument [" + ti.getName() + " is not stopped"); + } + if (ti instanceof Profiler) { + Profiler nestedProfiler = (Profiler) ti; + nestedProfiler.sanityCheck(); + } + } + if (totalElapsed < childTotal) { + throw new IllegalStateException("children have a higher accumulated elapsed time"); + } + } + + static String TOP_PROFILER_FIRST_PREFIX = "+"; + static String NESTED_PROFILER_FIRST_PREFIX = "|---+"; + static String TOTAL_ELAPSED = " Total "; + static String SUBTOTAL_ELAPSED = " Subtotal "; + static String ELAPSED_TIME = " elapsed time "; + + public void print() { + System.out.println(toString()); + } + + @Override + public String toString() { + DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch); + return buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, ""); + } + + public void log() { + Marker profilerMarker = MarkerFactory.getMarker(PROFILER_MARKER_NAME); + if (logger == null) { + throw new NullPointerException("If you invoke the log() method, then you must associate a logger with this profiler."); + } + if (logger.isDebugEnabled(profilerMarker)) { + DurationUnit du = Util.selectDurationUnitForDisplay(globalStopWatch); + String r = buildProfilerString(du, TOP_PROFILER_FIRST_PREFIX, TOTAL_ELAPSED, ""); + logger.debug(profilerMarker, SpacePadder.LINE_SEP + r); + } + } + + /** + * Return a copy of the child instrument list for this Profiler instance. + * + * @return a copy of this instance's child time instrument list + * @since 1.5.9 + */ + public List getCopyOfChildTimeInstruments() { + List copy = new ArrayList(childTimeInstrumentList); + return copy; + } + + /** + * Return a copy of the global stopwatch of this Profiler instance. + * + * @return a copy of this instance's global stop watch + * @since 1.5.9 + */ + public StopWatch getCopyOfGlobalStopWatch() { + StopWatch copy = new StopWatch(globalStopWatch); + return copy; + } + + private String buildProfilerString(DurationUnit du, String firstPrefix, String label, String indentation) { + StringBuilder buf = new StringBuilder(); + + buf.append(firstPrefix); + buf.append(" Profiler ["); + buf.append(name); + buf.append("]"); + buf.append(SpacePadder.LINE_SEP); + for (TimeInstrument child : childTimeInstrumentList) { + if (child instanceof StopWatch) { + buildStopWatchString(buf, du, ELAPSED_TIME, indentation, (StopWatch) child); + } else if (child instanceof Profiler) { + Profiler profiler = (Profiler) child; + String subString = profiler.buildProfilerString(du, NESTED_PROFILER_FIRST_PREFIX, SUBTOTAL_ELAPSED, indentation + " "); + buf.append(subString); + buildStopWatchString(buf, du, ELAPSED_TIME, indentation, profiler.globalStopWatch); + } + } + buildStopWatchString(buf, du, label, indentation, globalStopWatch); + return buf.toString(); + } + + private static void buildStopWatchString(StringBuilder buf, DurationUnit du, String prefix, String indentation, StopWatch sw) { + + buf.append(indentation); + buf.append("|--"); + buf.append(prefix); + SpacePadder.leftPad(buf, "[" + sw.getName() + "]", MIN_SW_NAME_LENGTH); + buf.append(" "); + String timeStr = Util.durationInDurationUnitsAsStr(sw.elapsedTime(), du); + SpacePadder.leftPad(buf, timeStr, MIN_SW_ELAPSED_TIME_NUMBER_LENGTH); + buf.append(" "); + Util.appendDurationUnitAsStr(buf, du); + buf.append(SpacePadder.LINE_SEP); + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/profiler/ProfilerRegistry.java b/slf4j-ext/src/main/java/org/slf4j/profiler/ProfilerRegistry.java index 94a4f62..61fda75 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/ProfilerRegistry.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/ProfilerRegistry.java @@ -1,65 +1,65 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -import java.util.HashMap; -import java.util.Map; - -/** - * A minimalist registry of profilers. - * - * @author Ceki Gülcü - */ -public class ProfilerRegistry { - - private static final InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal(); - - Map profilerMap = new HashMap(); - - public void put(Profiler profiler) { - put(profiler.getName(), profiler); - } - - public void put(String name, Profiler profiler) { - profilerMap.put(name, profiler); - } - - public static ProfilerRegistry getThreadContextInstance() { - ProfilerRegistry pr = inheritableThreadLocal.get(); - if (pr == null) { - pr = new ProfilerRegistry(); - inheritableThreadLocal.set(pr); - } - return pr; - } - - public Profiler get(String name) { - return profilerMap.get(name); - } - - public void clear() { - profilerMap.clear(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +import java.util.HashMap; +import java.util.Map; + +/** + * A minimalist registry of profilers. + * + * @author Ceki Gülcü + */ +public class ProfilerRegistry { + + private static final InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal(); + + Map profilerMap = new HashMap(); + + public void put(Profiler profiler) { + put(profiler.getName(), profiler); + } + + public void put(String name, Profiler profiler) { + profilerMap.put(name, profiler); + } + + public static ProfilerRegistry getThreadContextInstance() { + ProfilerRegistry pr = inheritableThreadLocal.get(); + if (pr == null) { + pr = new ProfilerRegistry(); + inheritableThreadLocal.set(pr); + } + return pr; + } + + public Profiler get(String name) { + return profilerMap.get(name); + } + + public void clear() { + profilerMap.clear(); + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/profiler/SpacePadder.java b/slf4j-ext/src/main/java/org/slf4j/profiler/SpacePadder.java index a1e5f22..e30486b 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/SpacePadder.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/SpacePadder.java @@ -1,127 +1,127 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -public class SpacePadder { - public static final String LINE_SEP = System.getProperty("line.separator"); - - final static String[] SPACES = { " ", " ", " ", " ", // 1,2,4,8 - // spaces - " ", // 16 spaces - " " }; // 32 spaces - - @Deprecated - final static public void leftPad(StringBuffer buf, String s, int desiredLength) { - int actualLen = 0; - if (s != null) { - actualLen = s.length(); - } - if (actualLen < desiredLength) { - spacePad(buf, desiredLength - actualLen); - } - if (s != null) { - buf.append(s); - } - } - - final static public void leftPad(StringBuilder buf, String s, int desiredLength) { - int actualLen = 0; - if (s != null) { - actualLen = s.length(); - } - if (actualLen < desiredLength) { - spacePad(buf, desiredLength - actualLen); - } - if (s != null) { - buf.append(s); - } - } - - @Deprecated - final static public void rightPad(StringBuffer buf, String s, int desiredLength) { - int actualLen = 0; - if (s != null) { - actualLen = s.length(); - } - if (s != null) { - buf.append(s); - } - if (actualLen < desiredLength) { - spacePad(buf, desiredLength - actualLen); - } - } - - final static public void rightPad(StringBuilder buf, String s, int desiredLength) { - int actualLen = 0; - if (s != null) { - actualLen = s.length(); - } - if (s != null) { - buf.append(s); - } - if (actualLen < desiredLength) { - spacePad(buf, desiredLength - actualLen); - } - } - - /** - * Fast space padding method. - * - * @param sbuf the buffer to pad - * @param length the target size of the buffer after padding - */ - @Deprecated - final static public void spacePad(StringBuffer sbuf, int length) { - while (length >= 32) { - sbuf.append(SPACES[5]); - length -= 32; - } - - for (int i = 4; i >= 0; i--) { - if ((length & (1 << i)) != 0) { - sbuf.append(SPACES[i]); - } - } - } - - /** - * Fast space padding method. - * - * @param sbuf the buffer to pad - * @param length the target size of the buffer after padding - */ - final static public void spacePad(StringBuilder sbuf, int length) { - while (length >= 32) { - sbuf.append(SPACES[5]); - length -= 32; - } - - for (int i = 4; i >= 0; i--) { - if ((length & (1 << i)) != 0) { - sbuf.append(SPACES[i]); - } - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +public class SpacePadder { + public static final String LINE_SEP = System.getProperty("line.separator"); + + final static String[] SPACES = { " ", " ", " ", " ", // 1,2,4,8 + // spaces + " ", // 16 spaces + " " }; // 32 spaces + + @Deprecated + final static public void leftPad(StringBuffer buf, String s, int desiredLength) { + int actualLen = 0; + if (s != null) { + actualLen = s.length(); + } + if (actualLen < desiredLength) { + spacePad(buf, desiredLength - actualLen); + } + if (s != null) { + buf.append(s); + } + } + + final static public void leftPad(StringBuilder buf, String s, int desiredLength) { + int actualLen = 0; + if (s != null) { + actualLen = s.length(); + } + if (actualLen < desiredLength) { + spacePad(buf, desiredLength - actualLen); + } + if (s != null) { + buf.append(s); + } + } + + @Deprecated + final static public void rightPad(StringBuffer buf, String s, int desiredLength) { + int actualLen = 0; + if (s != null) { + actualLen = s.length(); + } + if (s != null) { + buf.append(s); + } + if (actualLen < desiredLength) { + spacePad(buf, desiredLength - actualLen); + } + } + + final static public void rightPad(StringBuilder buf, String s, int desiredLength) { + int actualLen = 0; + if (s != null) { + actualLen = s.length(); + } + if (s != null) { + buf.append(s); + } + if (actualLen < desiredLength) { + spacePad(buf, desiredLength - actualLen); + } + } + + /** + * Fast space padding method. + * + * @param sbuf the buffer to pad + * @param length the target size of the buffer after padding + */ + @Deprecated + final static public void spacePad(StringBuffer sbuf, int length) { + while (length >= 32) { + sbuf.append(SPACES[5]); + length -= 32; + } + + for (int i = 4; i >= 0; i--) { + if ((length & (1 << i)) != 0) { + sbuf.append(SPACES[i]); + } + } + } + + /** + * Fast space padding method. + * + * @param sbuf the buffer to pad + * @param length the target size of the buffer after padding + */ + final static public void spacePad(StringBuilder sbuf, int length) { + while (length >= 32) { + sbuf.append(SPACES[5]); + length -= 32; + } + + for (int i = 4; i >= 0; i--) { + if ((length & (1 << i)) != 0) { + sbuf.append(SPACES[i]); + } + } + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/profiler/StopWatch.java b/slf4j-ext/src/main/java/org/slf4j/profiler/StopWatch.java index a2891b8..60488fc 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/StopWatch.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/StopWatch.java @@ -1,116 +1,116 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -/** - * A very basic {@link TimeInstrument} which can be started and stopped - * once and only once. - * - * @author Ceki Gülcü - * - */ -public class StopWatch implements TimeInstrument { - - private String name; - private long startTime; - private long stopTime; - TimeInstrumentStatus status; - - public StopWatch(String name) { - start(name); - } - - StopWatch(StopWatch original) { - this.name = original.name; - this.startTime = original.startTime; - this.stopTime = original.stopTime; - this.status = original.status; - } - - public void start(String name) { - this.name = name; - startTime = System.nanoTime(); - status = TimeInstrumentStatus.STARTED; - } - - public String getName() { - return name; - } - - public TimeInstrument stop() { - if (status == TimeInstrumentStatus.STOPPED) { - return this; - } - return stop(System.nanoTime()); - } - - public StopWatch stop(long stopTime) { - this.status = TimeInstrumentStatus.STOPPED; - this.stopTime = stopTime; - return this; - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("StopWatch ["); - buf.append(name); - buf.append("] "); - - switch (status) { - case STARTED: - buf.append("STARTED"); - break; - case STOPPED: - buf.append("elapsed time: "); - buf.append(Util.durationInDurationUnitsAsStr(elapsedTime(), DurationUnit.MICROSECOND)); - break; - default: - throw new IllegalStateException("Status " + status + " is not expected"); - } - return buf.toString(); - } - - public final long elapsedTime() { - if (status == TimeInstrumentStatus.STARTED) { - return 0; - } else { - return stopTime - startTime; - } - } - - public TimeInstrumentStatus getStatus() { - return status; - } - - public void print() { - System.out.println(toString()); - } - - public void log() { - throw new UnsupportedOperationException("A stopwatch instance does not know how to log"); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +/** + * A very basic {@link TimeInstrument} which can be started and stopped + * once and only once. + * + * @author Ceki Gülcü + * + */ +public class StopWatch implements TimeInstrument { + + private String name; + private long startTime; + private long stopTime; + TimeInstrumentStatus status; + + public StopWatch(String name) { + start(name); + } + + StopWatch(StopWatch original) { + this.name = original.name; + this.startTime = original.startTime; + this.stopTime = original.stopTime; + this.status = original.status; + } + + public void start(String name) { + this.name = name; + startTime = System.nanoTime(); + status = TimeInstrumentStatus.STARTED; + } + + public String getName() { + return name; + } + + public TimeInstrument stop() { + if (status == TimeInstrumentStatus.STOPPED) { + return this; + } + return stop(System.nanoTime()); + } + + public StopWatch stop(long stopTime) { + this.status = TimeInstrumentStatus.STOPPED; + this.stopTime = stopTime; + return this; + } + + @Override + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append("StopWatch ["); + buf.append(name); + buf.append("] "); + + switch (status) { + case STARTED: + buf.append("STARTED"); + break; + case STOPPED: + buf.append("elapsed time: "); + buf.append(Util.durationInDurationUnitsAsStr(elapsedTime(), DurationUnit.MICROSECOND)); + break; + default: + throw new IllegalStateException("Status " + status + " is not expected"); + } + return buf.toString(); + } + + public final long elapsedTime() { + if (status == TimeInstrumentStatus.STARTED) { + return 0; + } else { + return stopTime - startTime; + } + } + + public TimeInstrumentStatus getStatus() { + return status; + } + + public void print() { + System.out.println(toString()); + } + + public void log() { + throw new UnsupportedOperationException("A stopwatch instance does not know how to log"); + } + +} diff --git a/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrument.java b/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrument.java index 92456fc..3b2387f 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrument.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrument.java @@ -1,77 +1,77 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -/** - * This interface sets the methods that must be implemented by - * {@link Profiler} and {@link StopWatch} classes. It settles the - * general feel of the profiler package. - * - * @author Ceki Gülcü - * - */ -public interface TimeInstrument { - - /** - * All time instruments are named entities. - * @return the name of this instrument - */ - String getName(); - - TimeInstrumentStatus getStatus(); - - /** - * Start this time instrument. - * - * @param name - */ - void start(String name); - - /** - * Stop this time instrument. - * - * @return this - */ - TimeInstrument stop(); - - /** - * Time elapsed between start and stop, in nanoseconds. - * - * @return time elapsed in nanoseconds - */ - long elapsedTime(); - - /** - * Print information about this time instrument on the console. - */ - void print(); - - /** - * If the time instrument has an associated logger, then log information about - * this time instrument. Note that {@link StopWatch} instances cannot log while {@link Profiler} - * instances can. - */ - void log(); -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +/** + * This interface sets the methods that must be implemented by + * {@link Profiler} and {@link StopWatch} classes. It settles the + * general feel of the profiler package. + * + * @author Ceki Gülcü + * + */ +public interface TimeInstrument { + + /** + * All time instruments are named entities. + * @return the name of this instrument + */ + String getName(); + + TimeInstrumentStatus getStatus(); + + /** + * Start this time instrument. + * + * @param name + */ + void start(String name); + + /** + * Stop this time instrument. + * + * @return this + */ + TimeInstrument stop(); + + /** + * Time elapsed between start and stop, in nanoseconds. + * + * @return time elapsed in nanoseconds + */ + long elapsedTime(); + + /** + * Print information about this time instrument on the console. + */ + void print(); + + /** + * If the time instrument has an associated logger, then log information about + * this time instrument. Note that {@link StopWatch} instances cannot log while {@link Profiler} + * instances can. + */ + void log(); +} diff --git a/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrumentStatus.java b/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrumentStatus.java index 984ba25..f7eb6f7 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrumentStatus.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrumentStatus.java @@ -1,40 +1,40 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -/** - * A StopWatch can be in two states: STARTED or STOPPED. - */ - -package org.slf4j.profiler; - -/** - * A time instrument can be in STARTED or STOPPED status. - * - * @author Ceki Gülcü - * - */ -enum TimeInstrumentStatus { - STARTED, STOPPED; +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +/** + * A StopWatch can be in two states: STARTED or STOPPED. + */ + +package org.slf4j.profiler; + +/** + * A time instrument can be in STARTED or STOPPED status. + * + * @author Ceki Gülcü + * + */ +enum TimeInstrumentStatus { + STARTED, STOPPED; }diff --git a/slf4j-ext/src/main/java/org/slf4j/profiler/Util.java b/slf4j-ext/src/main/java/org/slf4j/profiler/Util.java index 5cbec11..28e645c 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/Util.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/Util.java @@ -1,114 +1,114 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -import java.text.DecimalFormat; - -/** - * - * A collection of utility methods. - * - * @author Ceki Gülcü - * - */ -class Util { - - static final long NANOS_IN_ONE_MICROSECOND = 1000; - static final long NANOS_IN_ONE_MILLISECOND = NANOS_IN_ONE_MICROSECOND * 1000; - static final long NANOS_IN_ONE_SECOND = NANOS_IN_ONE_MILLISECOND * 1000; - private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.000"); - - static DurationUnit selectDurationUnitForDisplay(StopWatch sw) { - return selectDurationUnitForDisplay(sw.elapsedTime()); - } - - static DurationUnit selectDurationUnitForDisplay(long durationInNanos) { - if (durationInNanos < 10 * NANOS_IN_ONE_MICROSECOND) { - return DurationUnit.NANOSECOND; - } else if (durationInNanos < 10 * NANOS_IN_ONE_MILLISECOND) { - return DurationUnit.MICROSECOND; - } else if (durationInNanos < 10 * NANOS_IN_ONE_SECOND) { - return DurationUnit.MILLISSECOND; - } else { - return DurationUnit.SECOND; - } - } - - static public double convertToMicros(long nanos) { - return (double) nanos / NANOS_IN_ONE_MICROSECOND; - } - - static public double convertToMillis(long nanos) { - return (double) nanos / NANOS_IN_ONE_MILLISECOND; - } - - static public double convertToSeconds(long nanos) { - return ((double) nanos / NANOS_IN_ONE_SECOND); - } - - static String durationInDurationUnitsAsStr(StringBuilder buf, StopWatch sw) { - DurationUnit du = selectDurationUnitForDisplay(sw); - return durationInDurationUnitsAsStr(sw.elapsedTime(), du); - } - - static String durationInDurationUnitsAsStr(long nanos, DurationUnit durationUnit) { - StringBuilder buf = new StringBuilder(); - switch (durationUnit) { - case NANOSECOND: - buf.append(nanos); - break; - case MICROSECOND: - double micros = convertToMicros(nanos); - buf.append(DECIMAL_FORMAT.format(micros)); - break; - case MILLISSECOND: - double millis = convertToMillis(nanos); - buf.append(DECIMAL_FORMAT.format(millis)); - break; - case SECOND: - double seconds = convertToSeconds(nanos); - buf.append(DECIMAL_FORMAT.format(seconds)); - break; - } - return buf.toString(); - } - - static void appendDurationUnitAsStr(StringBuilder buf, DurationUnit durationUnit) { - switch (durationUnit) { - case NANOSECOND: - buf.append("nanoseconds."); - break; - case MICROSECOND: - buf.append("microseconds."); - break; - case MILLISSECOND: - buf.append("milliseconds."); - break; - case SECOND: - buf.append(" seconds."); - break; - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +import java.text.DecimalFormat; + +/** + * + * A collection of utility methods. + * + * @author Ceki Gülcü + * + */ +class Util { + + static final long NANOS_IN_ONE_MICROSECOND = 1000; + static final long NANOS_IN_ONE_MILLISECOND = NANOS_IN_ONE_MICROSECOND * 1000; + static final long NANOS_IN_ONE_SECOND = NANOS_IN_ONE_MILLISECOND * 1000; + private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.000"); + + static DurationUnit selectDurationUnitForDisplay(StopWatch sw) { + return selectDurationUnitForDisplay(sw.elapsedTime()); + } + + static DurationUnit selectDurationUnitForDisplay(long durationInNanos) { + if (durationInNanos < 10 * NANOS_IN_ONE_MICROSECOND) { + return DurationUnit.NANOSECOND; + } else if (durationInNanos < 10 * NANOS_IN_ONE_MILLISECOND) { + return DurationUnit.MICROSECOND; + } else if (durationInNanos < 10 * NANOS_IN_ONE_SECOND) { + return DurationUnit.MILLISSECOND; + } else { + return DurationUnit.SECOND; + } + } + + static public double convertToMicros(long nanos) { + return (double) nanos / NANOS_IN_ONE_MICROSECOND; + } + + static public double convertToMillis(long nanos) { + return (double) nanos / NANOS_IN_ONE_MILLISECOND; + } + + static public double convertToSeconds(long nanos) { + return ((double) nanos / NANOS_IN_ONE_SECOND); + } + + static String durationInDurationUnitsAsStr(StringBuilder buf, StopWatch sw) { + DurationUnit du = selectDurationUnitForDisplay(sw); + return durationInDurationUnitsAsStr(sw.elapsedTime(), du); + } + + static String durationInDurationUnitsAsStr(long nanos, DurationUnit durationUnit) { + StringBuilder buf = new StringBuilder(); + switch (durationUnit) { + case NANOSECOND: + buf.append(nanos); + break; + case MICROSECOND: + double micros = convertToMicros(nanos); + buf.append(DECIMAL_FORMAT.format(micros)); + break; + case MILLISSECOND: + double millis = convertToMillis(nanos); + buf.append(DECIMAL_FORMAT.format(millis)); + break; + case SECOND: + double seconds = convertToSeconds(nanos); + buf.append(DECIMAL_FORMAT.format(seconds)); + break; + } + return buf.toString(); + } + + static void appendDurationUnitAsStr(StringBuilder buf, DurationUnit durationUnit) { + switch (durationUnit) { + case NANOSECOND: + buf.append("nanoseconds."); + break; + case MICROSECOND: + buf.append("microseconds."); + break; + case MILLISSECOND: + buf.append("milliseconds."); + break; + case SECOND: + buf.append(" seconds."); + break; + } + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/profiler/package.html b/slf4j-ext/src/main/java/org/slf4j/profiler/package.html index fe4eea6..0aea385 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/package.html +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/package.html @@ -1,13 +1,13 @@ - - - - - - - - - - -

Poor man's profiler API

- - + + + + + + + + + + +

Poor man's profiler API

+ + diff --git a/slf4j-ext/src/main/resources/META-INF/MANIFEST.MF b/slf4j-ext/src/main/resources/META-INF/MANIFEST.MF index 99fee1d..3328a2c 100644 --- a/slf4j-ext/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-ext/src/main/resources/META-INF/MANIFEST.MF @@ -1,8 +1,8 @@ -Implementation-Title: slf4j-ext -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.ext -Bundle-Name: slf4j-ext -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.slf4j.profiler;version=${parsedVersion.osgiVersion}, org.slf4j.cal10n;version=${parsedVersion.osgiVersion}, org.slf4j.ext;version=${parsedVersion.osgiVersion} -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} +Implementation-Title: slf4j-ext +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.ext +Bundle-Name: slf4j-ext +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.slf4j.profiler;version=${parsedVersion.osgiVersion}, org.slf4j.cal10n;version=${parsedVersion.osgiVersion}, org.slf4j.ext;version=${parsedVersion.osgiVersion} +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} diff --git a/slf4j-ext/src/test/java/org/slf4j/NDCTest.java b/slf4j-ext/src/test/java/org/slf4j/NDCTest.java index 4adfd31..e25164e 100644 --- a/slf4j-ext/src/test/java/org/slf4j/NDCTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/NDCTest.java @@ -1,60 +1,60 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -public class NDCTest { - - @Before - public void setUp() throws Exception { - MDC.clear(); - } - - @Test - public void testEmpty() { - assertEquals("", NDC.pop()); - } - - @Test - public void testSmoke() { - NDC.push("a"); - String result = NDC.pop(); - assertEquals("a", result); - } - - @Test - public void testSmoke2() { - NDC.push("a"); - NDC.push("b"); - String result1 = NDC.pop(); - String result0 = NDC.pop(); - assertEquals("b", result1); - assertEquals("a", result0); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class NDCTest { + + @Before + public void setUp() throws Exception { + MDC.clear(); + } + + @Test + public void testEmpty() { + assertEquals("", NDC.pop()); + } + + @Test + public void testSmoke() { + NDC.push("a"); + String result = NDC.pop(); + assertEquals("a", result); + } + + @Test + public void testSmoke2() { + NDC.push("a"); + NDC.push("b"); + String result1 = NDC.pop(); + String result0 = NDC.pop(); + assertEquals("b", result1); + assertEquals("a", result0); + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/LocLoggerTest.java b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/LocLoggerTest.java index d80a7de..becab67 100644 --- a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/LocLoggerTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/LocLoggerTest.java @@ -1,74 +1,74 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.cal10n_dummy; - -import static org.junit.Assert.assertEquals; - -import java.util.Locale; - -import org.apache.log4j.spi.LoggingEvent; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.cal10n.LocLogger; -import org.slf4j.cal10n.LocLoggerFactory; -import org.slf4j.dummyExt.ListAppender; - -import ch.qos.cal10n.IMessageConveyor; -import ch.qos.cal10n.MessageConveyor; - -public class LocLoggerTest { - - ListAppender listAppender; - org.apache.log4j.Logger log4jRoot; - - IMessageConveyor imc = new MessageConveyor(Locale.UK); - LocLoggerFactory llFactory_uk = new LocLoggerFactory(imc); - - final static String EXPECTED_FILE_NAME = "LocLoggerTest.java"; - - @Before - public void setUp() throws Exception { - // start from a clean slate for each test - - listAppender = new ListAppender(); - listAppender.extractLocationInfo = true; - log4jRoot = org.apache.log4j.Logger.getRootLogger(); - log4jRoot.addAppender(listAppender); - log4jRoot.setLevel(org.apache.log4j.Level.TRACE); - } - - void verify(LoggingEvent le, String expectedMsg) { - assertEquals(expectedMsg, le.getMessage()); - assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName()); - } - - @Test - public void testSmoke() { - LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass()); - locLogger.info(Months.JAN); - verify((LoggingEvent) listAppender.list.get(0), "January"); - - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.cal10n_dummy; + +import static org.junit.Assert.assertEquals; + +import java.util.Locale; + +import org.apache.log4j.spi.LoggingEvent; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.cal10n.LocLogger; +import org.slf4j.cal10n.LocLoggerFactory; +import org.slf4j.dummyExt.ListAppender; + +import ch.qos.cal10n.IMessageConveyor; +import ch.qos.cal10n.MessageConveyor; + +public class LocLoggerTest { + + ListAppender listAppender; + org.apache.log4j.Logger log4jRoot; + + IMessageConveyor imc = new MessageConveyor(Locale.UK); + LocLoggerFactory llFactory_uk = new LocLoggerFactory(imc); + + final static String EXPECTED_FILE_NAME = "LocLoggerTest.java"; + + @Before + public void setUp() throws Exception { + // start from a clean slate for each test + + listAppender = new ListAppender(); + listAppender.extractLocationInfo = true; + log4jRoot = org.apache.log4j.Logger.getRootLogger(); + log4jRoot.addAppender(listAppender); + log4jRoot.setLevel(org.apache.log4j.Level.TRACE); + } + + void verify(LoggingEvent le, String expectedMsg) { + assertEquals(expectedMsg, le.getMessage()); + assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName()); + } + + @Test + public void testSmoke() { + LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass()); + locLogger.info(Months.JAN); + verify((LoggingEvent) listAppender.list.get(0), "January"); + + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Months.java b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Months.java index 3c6a250..51fb423 100644 --- a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Months.java +++ b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Months.java @@ -1,35 +1,35 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.cal10n_dummy; - -import ch.qos.cal10n.BaseName; -import ch.qos.cal10n.Locale; -import ch.qos.cal10n.LocaleData; - -@BaseName("months") -@LocaleData(@Locale("en")) -public enum Months { - JAN, FEB, MAR, APR, MAY, JUN; -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.cal10n_dummy; + +import ch.qos.cal10n.BaseName; +import ch.qos.cal10n.Locale; +import ch.qos.cal10n.LocaleData; + +@BaseName("months") +@LocaleData(@Locale("en")) +public enum Months { + JAN, FEB, MAR, APR, MAY, JUN; +} diff --git a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/MyApplication.java b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/MyApplication.java index a7c618e..375bc2d 100644 --- a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/MyApplication.java +++ b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/MyApplication.java @@ -1,55 +1,55 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.cal10n_dummy; - -import java.util.Locale; - -import org.slf4j.cal10n.LocLogger; -import org.slf4j.cal10n.LocLoggerFactory; - -import ch.qos.cal10n.IMessageConveyor; -import ch.qos.cal10n.MessageConveyor; - -public class MyApplication { - - // create a message conveyor for a given locale - IMessageConveyor messageConveyor = new MessageConveyor(Locale.JAPAN); - - // create the LogLoggerFactory - LocLoggerFactory llFactory_uk = new LocLoggerFactory(messageConveyor); - - // create a locLogger - LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass()); - - public void applicationStart() { - locLogger.info(Production.APPLICATION_STARTED); - // .. - } - - public void applicationStop() { - locLogger.info(Production.APPLICATION_STOPPED); - // ... - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.cal10n_dummy; + +import java.util.Locale; + +import org.slf4j.cal10n.LocLogger; +import org.slf4j.cal10n.LocLoggerFactory; + +import ch.qos.cal10n.IMessageConveyor; +import ch.qos.cal10n.MessageConveyor; + +public class MyApplication { + + // create a message conveyor for a given locale + IMessageConveyor messageConveyor = new MessageConveyor(Locale.JAPAN); + + // create the LogLoggerFactory + LocLoggerFactory llFactory_uk = new LocLoggerFactory(messageConveyor); + + // create a locLogger + LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass()); + + public void applicationStart() { + locLogger.info(Production.APPLICATION_STARTED); + // .. + } + + public void applicationStop() { + locLogger.info(Production.APPLICATION_STOPPED); + // ... + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/PackageTest.java b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/PackageTest.java index b56dd4a..f77207b 100644 --- a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/PackageTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/PackageTest.java @@ -1,34 +1,34 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.cal10n_dummy; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ LocLoggerTest.class }) -public class PackageTest { -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.cal10n_dummy; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ LocLoggerTest.class }) +public class PackageTest { +} diff --git a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Production.java b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Production.java index af3880e..c0de6f1 100644 --- a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Production.java +++ b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Production.java @@ -1,35 +1,35 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.cal10n_dummy; - -import ch.qos.cal10n.LocaleData; -import ch.qos.cal10n.Locale; -import ch.qos.cal10n.BaseName; - -@BaseName("production") -@LocaleData({ @Locale("en_UK"), @Locale("fr") }) -public enum Production { - APPLICATION_STARTED, APPLICATION_STOPPED, DB_CONNECTION, DB_CONNECTION_FAILURE; +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.cal10n_dummy; + +import ch.qos.cal10n.LocaleData; +import ch.qos.cal10n.Locale; +import ch.qos.cal10n.BaseName; + +@BaseName("production") +@LocaleData({ @Locale("en_UK"), @Locale("fr") }) +public enum Production { + APPLICATION_STARTED, APPLICATION_STOPPED, DB_CONNECTION, DB_CONNECTION_FAILURE; }diff --git a/slf4j-ext/src/test/java/org/slf4j/dummyExt/EventLoggerTest.java b/slf4j-ext/src/test/java/org/slf4j/dummyExt/EventLoggerTest.java deleted file mode 100644 index b65b33f..0000000 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/EventLoggerTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.dummyExt; - -import static org.junit.Assert.assertEquals; - -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import org.apache.log4j.spi.LocationInfo; -import org.apache.log4j.spi.LoggingEvent; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.MDC; -import org.slf4j.ext.EventData; -import org.slf4j.ext.EventLogger; - -public class EventLoggerTest { - - ListAppender listAppender; - org.apache.log4j.Logger log4; - - final static String EXPECTED_FILE_NAME = "EventLoggerTest.java"; - - @Before - public void setUp() throws Exception { - - // start from a clean slate for each test - - listAppender = new ListAppender(); - listAppender.extractLocationInfo = true; - org.apache.log4j.Logger eventLogger = org.apache.log4j.Logger.getLogger("EventLogger"); - eventLogger.addAppender(listAppender); - eventLogger.setLevel(org.apache.log4j.Level.TRACE); - eventLogger.setAdditivity(false); - // Items that apply to any activity - MDC.put("ipAddress", "192.168.1.110"); - MDC.put("login", "TestUSer"); - MDC.put("hostname", "localhost"); - MDC.put("productName", "SLF4J"); - MDC.put("locale", Locale.getDefault().getDisplayName()); - MDC.put("timezone", TimeZone.getDefault().getDisplayName()); - - } - - @After - public void tearDown() throws Exception { - MDC.clear(); - } - - void verify(LoggingEvent le, String expectedMsg) { - assertEquals(expectedMsg, le.getMessage()); - assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName()); - } - - @Test - public void testEventLogger() { - EventData data[] = new EventData[2]; - data[0] = new EventData(); - data[0].setEventType("Login"); - data[0].setEventId("1"); - data[0].setEventDateTime(new Date()); - data[0].put("Userid", "TestUser"); - EventLogger.logEvent(data[0]); - - data[1] = new EventData(); - data[1].setEventType("Update"); - data[1].setEventId("2"); - data[1].setEventDateTime(new Date()); - data[1].put("FileName", "/etc/hosts"); - EventLogger.logEvent(data[1]); - - assertEquals(2, listAppender.list.size()); - for (int i = 0; i < 2; ++i) { - LoggingEvent event = listAppender.list.get(i); - verify(event, data[i].toXML()); - LocationInfo li = event.getLocationInformation(); - assertEquals(this.getClass().getName(), li.getClassName()); - assertEquals(event.getMDC("hostname"), "localhost"); - } - } -} \ No newline at end of file diff --git a/slf4j-ext/src/test/java/org/slf4j/dummyExt/ListAppender.java b/slf4j-ext/src/test/java/org/slf4j/dummyExt/ListAppender.java index 5a7cbc1..bb7f2f2 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/ListAppender.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/ListAppender.java @@ -1,53 +1,53 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.dummyExt; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.spi.LoggingEvent; - -public class ListAppender extends AppenderSkeleton { - - public List list = new ArrayList(); - - public boolean extractLocationInfo = false; - - protected void append(LoggingEvent event) { - list.add(event); - if (extractLocationInfo) { - event.getLocationInformation(); - } - } - - public void close() { - } - - public boolean requiresLayout() { - return false; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.dummyExt; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class ListAppender extends AppenderSkeleton { + + public List list = new ArrayList(); + + public boolean extractLocationInfo = false; + + protected void append(LoggingEvent event) { + list.add(event); + if (extractLocationInfo) { + event.getLocationInformation(); + } + } + + public void close() { + } + + public boolean requiresLayout() { + return false; + } + +} diff --git a/slf4j-ext/src/test/java/org/slf4j/dummyExt/MDCStrLookupTest.java b/slf4j-ext/src/test/java/org/slf4j/dummyExt/MDCStrLookupTest.java index d5a0a38..aa035b9 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/MDCStrLookupTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/MDCStrLookupTest.java @@ -1,46 +1,46 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.dummyExt; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.slf4j.MDC; -import org.slf4j.ext.MDCStrLookup; - -public class MDCStrLookupTest { - - @Test - public void testLookup() throws Exception { - MDC.put("key", "value"); - MDC.put("number", "2"); - MDCStrLookup lookup = new MDCStrLookup(); - assertEquals("value", lookup.lookup("key")); - assertEquals("2", lookup.lookup("number")); - assertEquals(null, lookup.lookup(null)); - assertEquals(null, lookup.lookup("")); - assertEquals(null, lookup.lookup("other")); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.dummyExt; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.slf4j.MDC; +import org.slf4j.ext.MDCStrLookup; + +public class MDCStrLookupTest { + + @Test + public void testLookup() throws Exception { + MDC.put("key", "value"); + MDC.put("number", "2"); + MDCStrLookup lookup = new MDCStrLookup(); + assertEquals("value", lookup.lookup("key")); + assertEquals("2", lookup.lookup("number")); + assertEquals(null, lookup.lookup(null)); + assertEquals(null, lookup.lookup("")); + assertEquals(null, lookup.lookup("other")); + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/dummyExt/PackageTest.java b/slf4j-ext/src/test/java/org/slf4j/dummyExt/PackageTest.java index 8c9e39e..c4fba25 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/PackageTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/PackageTest.java @@ -1,34 +1,34 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.dummyExt; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ MDCStrLookupTest.class, XLoggerTest.class, EventLoggerTest.class }) -public class PackageTest { -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.dummyExt; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ MDCStrLookupTest.class, XLoggerTest.class }) +public class PackageTest { +} diff --git a/slf4j-ext/src/test/java/org/slf4j/dummyExt/XLoggerTest.java b/slf4j-ext/src/test/java/org/slf4j/dummyExt/XLoggerTest.java index a88fcca..9bb52bb 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/XLoggerTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/XLoggerTest.java @@ -1,155 +1,155 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.dummyExt; - -import static org.junit.Assert.assertEquals; - -import org.apache.log4j.spi.LocationInfo; -import org.apache.log4j.spi.LoggingEvent; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -public class XLoggerTest { - - ListAppender listAppender; - org.apache.log4j.Logger log4jRoot; - - final static String EXPECTED_FILE_NAME = "XLoggerTest.java"; - - @Before - public void setUp() throws Exception { - - // start from a clean slate for each test - - listAppender = new ListAppender(); - listAppender.extractLocationInfo = true; - log4jRoot = org.apache.log4j.Logger.getRootLogger(); - log4jRoot.addAppender(listAppender); - log4jRoot.setLevel(org.apache.log4j.Level.TRACE); - } - - void verify(LoggingEvent le, String expectedMsg) { - assertEquals(expectedMsg, le.getMessage()); - assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName()); - } - - void verifyWithException(LoggingEvent le, String expectedMsg, Throwable t) { - verify(le, expectedMsg); - assertEquals(t.toString(), le.getThrowableStrRep()[0]); - } - - void verifyWithLevelAndException(LoggingEvent le, XLogger.Level level, String expectedMsg, Throwable t) { - verify(le, expectedMsg); - assertEquals(t.toString(), le.getThrowableStrRep()[0]); - assertEquals(le.getLevel().toString(), level.toString()); - } - - @Test - public void testEntering() { - XLogger logger = XLoggerFactory.getXLogger("UnitTest"); - logger.entry(); - logger.entry(1); - logger.entry("test"); - logger.entry("a", "b", "c", "d"); - logger.entry("a", "b", "c", "d", "e"); - logger.entry("a", "b", "c", "d", "e", "f"); - - assertEquals(6, listAppender.list.size()); - verify((LoggingEvent) listAppender.list.get(0), "entry"); - verify((LoggingEvent) listAppender.list.get(1), "entry with (1)"); - verify((LoggingEvent) listAppender.list.get(2), "entry with (test)"); - } - - @Test - public void testExiting() { - XLogger logger = XLoggerFactory.getXLogger("UnitTest"); - logger.exit(); - assertEquals(Integer.valueOf(0), logger.exit(0)); - assertEquals(Boolean.FALSE, logger.exit(false)); - - assertEquals(3, listAppender.list.size()); - verify((LoggingEvent) listAppender.list.get(0), "exit"); - verify((LoggingEvent) listAppender.list.get(1), "exit with (0)"); - verify((LoggingEvent) listAppender.list.get(2), "exit with (false)"); - } - - @Test - public void testThrowing() { - XLogger logger = XLoggerFactory.getXLogger("UnitTest"); - Throwable t = new UnsupportedOperationException("Test"); - assertEquals(t, logger.throwing(t)); - assertEquals(t, logger.throwing(XLogger.Level.DEBUG, t)); - assertEquals(2, listAppender.list.size()); - verifyWithException((LoggingEvent) listAppender.list.get(0), "throwing", t); - LoggingEvent event = (LoggingEvent) listAppender.list.get(1); - verifyWithLevelAndException(event, XLogger.Level.DEBUG, "throwing", t); - } - - @Test - public void testCaught() { - XLogger logger = XLoggerFactory.getXLogger("UnitTest"); - long x = 5; - Throwable t = null; - try { - @SuppressWarnings("unused") - long y = x / 0; - } catch (Exception ex) { - t = ex; - logger.catching(ex); - logger.catching(XLogger.Level.DEBUG, ex); - } - verifyWithException((LoggingEvent) listAppender.list.get(0), "catching", t); - verifyWithLevelAndException((LoggingEvent) listAppender.list.get(1), XLogger.Level.DEBUG, "catching", t); - } - - // See http://jira.qos.ch/browse/SLF4J-105 - // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=114 - @Test - public void testLocationExtraction_Bug114() { - XLogger logger = XLoggerFactory.getXLogger("UnitTest"); - int line = 135; // requires update if line numbers change - logger.exit(); - logger.debug("hello"); - - assertEquals(2, listAppender.list.size()); - - { - LoggingEvent e = listAppender.list.get(0); - LocationInfo li = e.getLocationInformation(); - assertEquals(this.getClass().getName(), li.getClassName()); - assertEquals("" + line, li.getLineNumber()); - } - - { - LoggingEvent e = listAppender.list.get(1); - LocationInfo li = e.getLocationInformation(); - assertEquals(this.getClass().getName(), li.getClassName()); - assertEquals("" + (line + 1), li.getLineNumber()); - } - - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.dummyExt; + +import static org.junit.Assert.assertEquals; + +import org.apache.log4j.spi.LocationInfo; +import org.apache.log4j.spi.LoggingEvent; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +public class XLoggerTest { + + ListAppender listAppender; + org.apache.log4j.Logger log4jRoot; + + final static String EXPECTED_FILE_NAME = "XLoggerTest.java"; + + @Before + public void setUp() throws Exception { + + // start from a clean slate for each test + + listAppender = new ListAppender(); + listAppender.extractLocationInfo = true; + log4jRoot = org.apache.log4j.Logger.getRootLogger(); + log4jRoot.addAppender(listAppender); + log4jRoot.setLevel(org.apache.log4j.Level.TRACE); + } + + void verify(LoggingEvent le, String expectedMsg) { + assertEquals(expectedMsg, le.getMessage()); + assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName()); + } + + void verifyWithException(LoggingEvent le, String expectedMsg, Throwable t) { + verify(le, expectedMsg); + assertEquals(t.toString(), le.getThrowableStrRep()[0]); + } + + void verifyWithLevelAndException(LoggingEvent le, XLogger.Level level, String expectedMsg, Throwable t) { + verify(le, expectedMsg); + assertEquals(t.toString(), le.getThrowableStrRep()[0]); + assertEquals(le.getLevel().toString(), level.toString()); + } + + @Test + public void testEntering() { + XLogger logger = XLoggerFactory.getXLogger("UnitTest"); + logger.entry(); + logger.entry(1); + logger.entry("test"); + logger.entry("a", "b", "c", "d"); + logger.entry("a", "b", "c", "d", "e"); + logger.entry("a", "b", "c", "d", "e", "f"); + + assertEquals(6, listAppender.list.size()); + verify((LoggingEvent) listAppender.list.get(0), "entry"); + verify((LoggingEvent) listAppender.list.get(1), "entry with (1)"); + verify((LoggingEvent) listAppender.list.get(2), "entry with (test)"); + } + + @Test + public void testExiting() { + XLogger logger = XLoggerFactory.getXLogger("UnitTest"); + logger.exit(); + assertEquals(Integer.valueOf(0), logger.exit(0)); + assertEquals(Boolean.FALSE, logger.exit(false)); + + assertEquals(3, listAppender.list.size()); + verify((LoggingEvent) listAppender.list.get(0), "exit"); + verify((LoggingEvent) listAppender.list.get(1), "exit with (0)"); + verify((LoggingEvent) listAppender.list.get(2), "exit with (false)"); + } + + @Test + public void testThrowing() { + XLogger logger = XLoggerFactory.getXLogger("UnitTest"); + Throwable t = new UnsupportedOperationException("Test"); + assertEquals(t, logger.throwing(t)); + assertEquals(t, logger.throwing(XLogger.Level.DEBUG, t)); + assertEquals(2, listAppender.list.size()); + verifyWithException((LoggingEvent) listAppender.list.get(0), "throwing", t); + LoggingEvent event = (LoggingEvent) listAppender.list.get(1); + verifyWithLevelAndException(event, XLogger.Level.DEBUG, "throwing", t); + } + + @Test + public void testCaught() { + XLogger logger = XLoggerFactory.getXLogger("UnitTest"); + long x = 5; + Throwable t = null; + try { + @SuppressWarnings("unused") + long y = x / 0; + } catch (Exception ex) { + t = ex; + logger.catching(ex); + logger.catching(XLogger.Level.DEBUG, ex); + } + verifyWithException((LoggingEvent) listAppender.list.get(0), "catching", t); + verifyWithLevelAndException((LoggingEvent) listAppender.list.get(1), XLogger.Level.DEBUG, "catching", t); + } + + // See http://jira.qos.ch/browse/SLF4J-105 + // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=114 + @Test + public void testLocationExtraction_Bug114() { + XLogger logger = XLoggerFactory.getXLogger("UnitTest"); + int line = 135; // requires update if line numbers change + logger.exit(); + logger.debug("hello"); + + assertEquals(2, listAppender.list.size()); + + { + LoggingEvent e = listAppender.list.get(0); + LocationInfo li = e.getLocationInformation(); + assertEquals(this.getClass().getName(), li.getClassName()); + assertEquals("" + line, li.getLineNumber()); + } + + { + LoggingEvent e = listAppender.list.get(1); + LocationInfo li = e.getLocationInformation(); + assertEquals(this.getClass().getName(), li.getClassName()); + assertEquals("" + (line + 1), li.getLineNumber()); + } + + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/dummyExt/package.html b/slf4j-ext/src/test/java/org/slf4j/dummyExt/package.html old file mode 100644 new file mode 100755 index 3742f3d..be198fb 100755 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/package.html +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/package.html @@ -1,8 +1,8 @@ - - -Tests related to the org.slf4j.ext package. However, location information code -required the caller class (XLogger) to have a different prefix than -the test class XLoggerTest. This is ensured by having the test class -placed in a different package. - + + +Tests related to the org.slf4j.ext package. However, location information code +required the caller class (XLogger) to have a different prefix than +the test class XLoggerTest. This is ensured by having the test class +placed in a different package. + diff --git a/slf4j-ext/src/test/java/org/slf4j/instrumentation/ToStringHelperTest.java b/slf4j-ext/src/test/java/org/slf4j/instrumentation/ToStringHelperTest.java index 9e8a63e..81723c0 100644 --- a/slf4j-ext/src/test/java/org/slf4j/instrumentation/ToStringHelperTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/instrumentation/ToStringHelperTest.java @@ -1,68 +1,68 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.instrumentation; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class ToStringHelperTest { - - @Test - public void testRenderer() { - assertEquals("", "null", ToStringHelper.render(null)); - assertEquals("", "a", ToStringHelper.render("a")); - assertEquals("", "[]", ToStringHelper.render(new String[0])); - - assertEquals("", "[a]", ToStringHelper.render(new String[] { "a" })); - - assertEquals("", "[a, b]", ToStringHelper.render(new String[] { "a", "b" })); - - assertEquals("", "[a, b, c]", ToStringHelper.render(new String[] { "a", "b", "c" })); - - assertEquals("", "[[a], [b, c]]", ToStringHelper.render(new String[][] { { "a" }, { "b", "c" } })); - - assertEquals("", "[0, [a], [b, c]]", ToStringHelper.render(new Object[] { "0", new String[] { "a" }, new Object[] { "b", "c" } })); - - assertEquals("", "[1]", ToStringHelper.render(new int[] { 1 })); - - assertEquals("", "[1, 2, 3]", ToStringHelper.render(new int[] { 1, 2, 3 })); - - assertEquals("", "[1, 2, 3]", ToStringHelper.render(new long[] { 1, 2, 3 })); - - assertEquals("", "[1, 2, 3]", ToStringHelper.render(new short[] { 1, 2, 3 })); - - assertEquals("", "[[1, 2], [], [3, 4]]", ToStringHelper.render(new byte[][] { { 1, 2 }, {}, { 3, 4 } })); - - assertEquals("", "[1.0, 2.0, 3.0]", ToStringHelper.render(new float[] { 1, 2, 3 })); - - assertEquals("", "[1.0, 2.0, 3.0]", ToStringHelper.render(new double[] { 1, 2, 3 })); - - assertEquals("", "[[1.0, 2.0, 3.0]]", ToStringHelper.render(new double[][] { { 1, 2, 3 } })); - - assertEquals("", "[true, false, true]", ToStringHelper.render(new boolean[] { true, false, true })); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.instrumentation; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class ToStringHelperTest { + + @Test + public void testRenderer() { + assertEquals("", "null", ToStringHelper.render(null)); + assertEquals("", "a", ToStringHelper.render("a")); + assertEquals("", "[]", ToStringHelper.render(new String[0])); + + assertEquals("", "[a]", ToStringHelper.render(new String[] { "a" })); + + assertEquals("", "[a, b]", ToStringHelper.render(new String[] { "a", "b" })); + + assertEquals("", "[a, b, c]", ToStringHelper.render(new String[] { "a", "b", "c" })); + + assertEquals("", "[[a], [b, c]]", ToStringHelper.render(new String[][] { { "a" }, { "b", "c" } })); + + assertEquals("", "[0, [a], [b, c]]", ToStringHelper.render(new Object[] { "0", new String[] { "a" }, new Object[] { "b", "c" } })); + + assertEquals("", "[1]", ToStringHelper.render(new int[] { 1 })); + + assertEquals("", "[1, 2, 3]", ToStringHelper.render(new int[] { 1, 2, 3 })); + + assertEquals("", "[1, 2, 3]", ToStringHelper.render(new long[] { 1, 2, 3 })); + + assertEquals("", "[1, 2, 3]", ToStringHelper.render(new short[] { 1, 2, 3 })); + + assertEquals("", "[[1, 2], [], [3, 4]]", ToStringHelper.render(new byte[][] { { 1, 2 }, {}, { 3, 4 } })); + + assertEquals("", "[1.0, 2.0, 3.0]", ToStringHelper.render(new float[] { 1, 2, 3 })); + + assertEquals("", "[1.0, 2.0, 3.0]", ToStringHelper.render(new double[] { 1, 2, 3 })); + + assertEquals("", "[[1.0, 2.0, 3.0]]", ToStringHelper.render(new double[][] { { 1, 2, 3 } })); + + assertEquals("", "[true, false, true]", ToStringHelper.render(new boolean[] { true, false, true })); + } + +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/BasicProfilerDemo.java b/slf4j-ext/src/test/java/org/slf4j/profiler/BasicProfilerDemo.java index f04fa91..ad8f07e 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/BasicProfilerDemo.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/BasicProfilerDemo.java @@ -1,87 +1,87 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -/** - * - * This demo illustrates usage of SLF4J profilers. - * - *

- * We have been given the task of generating a large number, say N, of random - * integers. We need to transform that array into a smaller array containing - * only prime numbers. The new array has to be sorted. - * - *

- * While tackling this problem, we would like to measure the time spent in each - * subtask. - * - *

- * A typical output for this demo would be: - * - *

-   + Profiler [BASIC]
-   |-- elapsed time                      [A]   213.186 milliseconds.
-   |-- elapsed time                      [B]  2499.107 milliseconds.
-   |-- elapsed time                  [OTHER]  3300.752 milliseconds.
-   |-- Total                         [BASIC]  6014.161 milliseconds.
-  
- * - * @author Ceki Gulcu - */ -public class BasicProfilerDemo { - - public static void main(String[] args) { - // create a profiler called "BASIC" - Profiler profiler = new Profiler("BASIC"); - profiler.start("A"); - doA(); - - profiler.start("B"); - doB(); - - profiler.start("OTHER"); - doOther(); - profiler.stop().print(); - } - - static private void doA() { - delay(200); - } - - static private void doB() { - delay(2500); - } - - static private void doOther() { - delay(3300); - } - - static private void delay(int millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +/** + * + * This demo illustrates usage of SLF4J profilers. + * + *

+ * We have been given the task of generating a large number, say N, of random + * integers. We need to transform that array into a smaller array containing + * only prime numbers. The new array has to be sorted. + * + *

+ * While tackling this problem, we would like to measure the time spent in each + * subtask. + * + *

+ * A typical output for this demo would be: + * + *

+   + Profiler [BASIC]
+   |-- elapsed time                      [A]   213.186 milliseconds.
+   |-- elapsed time                      [B]  2499.107 milliseconds.
+   |-- elapsed time                  [OTHER]  3300.752 milliseconds.
+   |-- Total                         [BASIC]  6014.161 milliseconds.
+  
+ * + * @author Ceki Gulcu + */ +public class BasicProfilerDemo { + + public static void main(String[] args) { + // create a profiler called "BASIC" + Profiler profiler = new Profiler("BASIC"); + profiler.start("A"); + doA(); + + profiler.start("B"); + doB(); + + profiler.start("OTHER"); + doOther(); + profiler.stop().print(); + } + + static private void doA() { + delay(200); + } + + static private void doB() { + delay(2500); + } + + static private void doOther() { + delay(3300); + } + + static private void delay(int millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + } + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo.java b/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo.java index a465345..a21e573 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo.java @@ -1,84 +1,84 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -/** - * - * This demo illustrates usage of SLF4J profilers. - * - *

- * We have been given the task of generating a large number, say N, - * of random integers. We need to transform that array into a smaller array - * containing only prime numbers. The new array has to be sorted. - * - *

- * While tackling this problem, we would like to measure the - * time spent in each subtask. - * - *

- * A typical output for this demo would be: -

- + Profiler [DEMO]
-|-- elapsed time                       [RANDOM]     0.089  seconds.
-|---+ Profiler [SORT_AND_PRUNE]
-    |-- elapsed time                         [SORT]     0.221  seconds.
-    |-- elapsed time             [PRUNE_COMPOSITES]    11.567  seconds.
-    |-- Subtotal                   [SORT_AND_PRUNE]    11.788  seconds.
-|-- elapsed time               [SORT_AND_PRUNE]    11.788  seconds.
-|-- Total                                [DEMO]    11.877  seconds.
-
- * - * @author Ceki Gulcu - */ -public class NestedProfilerDemo { - - public static void main(String[] args) { - // create a profiler called "DEMO" - Profiler profiler = new Profiler("DEMO"); - - // register this profiler in the thread context's profiler registry - ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); - profiler.registerWith(profilerRegistry); - - // start a stopwatch called "RANDOM" - profiler.start("RANDOM"); - RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator(); - int n = 10 * 1000; - int[] randomArray = riaGenerator.generate(n); - - // create and start a nested profiler called "SORT_AND_PRUNE" - // By virtue of its parent-child relationship with the "DEMO" - // profiler, and the previous registration of the parent profiler, - // this nested profiler will be automatically registered - // with the thread context's profiler registry - profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME); - - SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray); - pruner.sortAndPruneComposites(); - - // stop and print the "DEMO" printer - profiler.stop().print(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +/** + * + * This demo illustrates usage of SLF4J profilers. + * + *

+ * We have been given the task of generating a large number, say N, + * of random integers. We need to transform that array into a smaller array + * containing only prime numbers. The new array has to be sorted. + * + *

+ * While tackling this problem, we would like to measure the + * time spent in each subtask. + * + *

+ * A typical output for this demo would be: +

+ + Profiler [DEMO]
+|-- elapsed time                       [RANDOM]     0.089  seconds.
+|---+ Profiler [SORT_AND_PRUNE]
+    |-- elapsed time                         [SORT]     0.221  seconds.
+    |-- elapsed time             [PRUNE_COMPOSITES]    11.567  seconds.
+    |-- Subtotal                   [SORT_AND_PRUNE]    11.788  seconds.
+|-- elapsed time               [SORT_AND_PRUNE]    11.788  seconds.
+|-- Total                                [DEMO]    11.877  seconds.
+
+ * + * @author Ceki Gulcu + */ +public class NestedProfilerDemo { + + public static void main(String[] args) { + // create a profiler called "DEMO" + Profiler profiler = new Profiler("DEMO"); + + // register this profiler in the thread context's profiler registry + ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); + profiler.registerWith(profilerRegistry); + + // start a stopwatch called "RANDOM" + profiler.start("RANDOM"); + RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator(); + int n = 10 * 1000; + int[] randomArray = riaGenerator.generate(n); + + // create and start a nested profiler called "SORT_AND_PRUNE" + // By virtue of its parent-child relationship with the "DEMO" + // profiler, and the previous registration of the parent profiler, + // this nested profiler will be automatically registered + // with the thread context's profiler registry + profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME); + + SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray); + pruner.sortAndPruneComposites(); + + // stop and print the "DEMO" printer + profiler.stop().print(); + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java b/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java index 4de2182..678aa06 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java @@ -1,64 +1,64 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * This demo illustrates usage of SLF4J profilers. It is almost identical to - * the first NestProfilerDemo, except that it uses a logger instead of - * printing its output on the console. - * - - * @author Ceki Gulcu - */ -public class NestedProfilerDemo2 { - - static Logger logger = LoggerFactory.getLogger(NestedProfilerDemo2.class); - - public static void main(String[] args) { - Profiler profiler = new Profiler("DEMO"); - // associate a logger with the profiler - profiler.setLogger(logger); - - ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); - profiler.registerWith(profilerRegistry); - - profiler.start("RANDOM"); - RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator(); - int n = 10 * 1000; - int[] randomArray = riaGenerator.generate(n); - - profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME); - - SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray); - pruner.sortAndPruneComposites(); - - // stop and log - profiler.stop().log(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * This demo illustrates usage of SLF4J profilers. It is almost identical to + * the first NestProfilerDemo, except that it uses a logger instead of + * printing its output on the console. + * + + * @author Ceki Gulcu + */ +public class NestedProfilerDemo2 { + + static Logger logger = LoggerFactory.getLogger(NestedProfilerDemo2.class); + + public static void main(String[] args) { + Profiler profiler = new Profiler("DEMO"); + // associate a logger with the profiler + profiler.setLogger(logger); + + ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); + profiler.registerWith(profilerRegistry); + + profiler.start("RANDOM"); + RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator(); + int n = 10 * 1000; + int[] randomArray = riaGenerator.generate(n); + + profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME); + + SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray); + pruner.sortAndPruneComposites(); + + // stop and log + profiler.stop().log(); + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/PackageTest.java b/slf4j-ext/src/test/java/org/slf4j/profiler/PackageTest.java index a0963b0..40b8365 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/PackageTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/PackageTest.java @@ -1,35 +1,35 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ UtilTest.class, ProfilerTest.class }) -public class PackageTest { - +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ UtilTest.class, ProfilerTest.class }) +public class PackageTest { + }diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/ProfilerTest.java b/slf4j-ext/src/test/java/org/slf4j/profiler/ProfilerTest.java index 13d557d..fef09a5 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/ProfilerTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/ProfilerTest.java @@ -1,140 +1,140 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ProfilerTest { - - Logger logger = LoggerFactory.getLogger(ProfilerTest.class); - - @Test - public void testSmoke() { - Profiler profiler = new Profiler("SMOKE"); - profiler.stop(); - StopWatch gSW = profiler.globalStopWatch; - - // verify - profiler.sanityCheck(); - assertEquals(TimeInstrumentStatus.STOPPED, gSW.status); - assertEquals(0, profiler.childTimeInstrumentList.size()); - assertNull(profiler.getLastTimeInstrument()); - } - - @Test - public void testBasicProfiling() { - Profiler profiler = new Profiler("BAS"); - - profiler.start("doX"); - doX(1); - - profiler.start("doY"); - doY(10); - - profiler.start("doZ"); - doZ(2); - profiler.stop(); - - // verify - profiler.sanityCheck(); - StopWatch gSW = profiler.globalStopWatch; - assertEquals(TimeInstrumentStatus.STOPPED, gSW.status); - assertEquals(3, profiler.childTimeInstrumentList.size()); - assertNotNull(profiler.getLastTimeInstrument()); - assertEquals("doZ", profiler.getLastTimeInstrument().getName()); - } - - // + Profiler [BAS] - // |-- elapsed time [doX] 1.272 milliseconds. - // |-- elapsed time [doYYYYY] 25.398 milliseconds. - // |--+ Profiler [subtask] - // |-- elapsed time [n1] 1.434 milliseconds. - // |-- elapsed time [n2] 5.855 milliseconds. - // |-- Total elapsed time [subtask] 7.321 milliseconds. - // |-- elapsed time [doZ] 3.211 milliseconds. - // |-- Total elapsed time [BAS] 30.317 milliseconds. - @Test - public void testNestedProfiling() { - - Profiler profiler = new Profiler("BAS"); - profiler.setLogger(logger); - profiler.start("doX"); - doX(1); - - profiler.start("doYYYYY"); - for (int i = 0; i < 5; i++) { - doY(i); - } - Profiler nested = profiler.startNested("subtask"); - doSubtask(nested); - profiler.start("doZ"); - doZ(2); - profiler.stop(); - - // verify - profiler.sanityCheck(); - StopWatch gSW = profiler.globalStopWatch; - assertEquals(TimeInstrumentStatus.STOPPED, gSW.status); - // assertEquals(3, profiler.stopwatchList.size()); - assertEquals(4, profiler.childTimeInstrumentList.size()); - assertNotNull(profiler.getLastTimeInstrument()); - assertEquals("doZ", profiler.getLastTimeInstrument().getName()); - - } - - private void doX(int millis) { - delay(millis); - } - - private void doY(int millis) { - delay(millis); - } - - private void doZ(int millis) { - delay(millis); - } - - public void doSubtask(Profiler nested) { - nested.start("n1"); - doX(1); - - nested.start("n2"); - doX(5); - nested.stop(); - } - - void delay(int millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ProfilerTest { + + Logger logger = LoggerFactory.getLogger(ProfilerTest.class); + + @Test + public void testSmoke() { + Profiler profiler = new Profiler("SMOKE"); + profiler.stop(); + StopWatch gSW = profiler.globalStopWatch; + + // verify + profiler.sanityCheck(); + assertEquals(TimeInstrumentStatus.STOPPED, gSW.status); + assertEquals(0, profiler.childTimeInstrumentList.size()); + assertNull(profiler.getLastTimeInstrument()); + } + + @Test + public void testBasicProfiling() { + Profiler profiler = new Profiler("BAS"); + + profiler.start("doX"); + doX(1); + + profiler.start("doY"); + doY(10); + + profiler.start("doZ"); + doZ(2); + profiler.stop(); + + // verify + profiler.sanityCheck(); + StopWatch gSW = profiler.globalStopWatch; + assertEquals(TimeInstrumentStatus.STOPPED, gSW.status); + assertEquals(3, profiler.childTimeInstrumentList.size()); + assertNotNull(profiler.getLastTimeInstrument()); + assertEquals("doZ", profiler.getLastTimeInstrument().getName()); + } + + // + Profiler [BAS] + // |-- elapsed time [doX] 1.272 milliseconds. + // |-- elapsed time [doYYYYY] 25.398 milliseconds. + // |--+ Profiler [subtask] + // |-- elapsed time [n1] 1.434 milliseconds. + // |-- elapsed time [n2] 5.855 milliseconds. + // |-- Total elapsed time [subtask] 7.321 milliseconds. + // |-- elapsed time [doZ] 3.211 milliseconds. + // |-- Total elapsed time [BAS] 30.317 milliseconds. + @Test + public void testNestedProfiling() { + + Profiler profiler = new Profiler("BAS"); + profiler.setLogger(logger); + profiler.start("doX"); + doX(1); + + profiler.start("doYYYYY"); + for (int i = 0; i < 5; i++) { + doY(i); + } + Profiler nested = profiler.startNested("subtask"); + doSubtask(nested); + profiler.start("doZ"); + doZ(2); + profiler.stop(); + + // verify + profiler.sanityCheck(); + StopWatch gSW = profiler.globalStopWatch; + assertEquals(TimeInstrumentStatus.STOPPED, gSW.status); + // assertEquals(3, profiler.stopwatchList.size()); + assertEquals(4, profiler.childTimeInstrumentList.size()); + assertNotNull(profiler.getLastTimeInstrument()); + assertEquals("doZ", profiler.getLastTimeInstrument().getName()); + + } + + private void doX(int millis) { + delay(millis); + } + + private void doY(int millis) { + delay(millis); + } + + private void doZ(int millis) { + delay(millis); + } + + public void doSubtask(Profiler nested) { + nested.start("n1"); + doX(1); + + nested.start("n2"); + doX(5); + nested.stop(); + } + + void delay(int millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + } + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/RandomIntegerArrayGenerator.java b/slf4j-ext/src/test/java/org/slf4j/profiler/RandomIntegerArrayGenerator.java index 4e675fa..b660747 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/RandomIntegerArrayGenerator.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/RandomIntegerArrayGenerator.java @@ -1,40 +1,40 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -import java.util.Random; - -public class RandomIntegerArrayGenerator { - Random rand = new Random(11); - - int[] generate(int size) { - int[] result = new int[size]; - for (int i = 0; i < size; i++) { - int r = rand.nextInt(); - result[i] = r; - } - return result; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +import java.util.Random; + +public class RandomIntegerArrayGenerator { + Random rand = new Random(11); + + int[] generate(int size) { + int[] result = new int[size]; + for (int i = 0; i < size; i++) { + int r = rand.nextInt(); + result[i] = r; + } + return result; + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/SortAndPruneComposites.java b/slf4j-ext/src/test/java/org/slf4j/profiler/SortAndPruneComposites.java index 0a88086..867bb60 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/SortAndPruneComposites.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/SortAndPruneComposites.java @@ -1,96 +1,96 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -import java.util.ArrayList; -import java.util.Arrays; - -public class SortAndPruneComposites { - - static String NESTED_PROFILER_NAME = "SORT_AND_PRUNE"; - - final int[] originalArray; - final int originalArrrayLength; - - public SortAndPruneComposites(int[] randomArray) { - this.originalArray = randomArray; - this.originalArrrayLength = randomArray.length; - - } - - public int[] sortAndPruneComposites() { - // retrieve previously registered profiler named "SORT_AND_PRUNE" - ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); - Profiler sortProfiler = profilerRegistry.get(NESTED_PROFILER_NAME); - - // start a new stopwatch called SORT - sortProfiler.start("SORT"); - int[] sortedArray = sort(); - // start a new stopwatch called PRUNE_COMPOSITES - sortProfiler.start("PRUNE_COMPOSITES"); - int result[] = pruneComposites(sortedArray); - - return result; - } - - private int[] sort() { - int[] sortedArray = new int[originalArrrayLength]; - System.arraycopy(originalArray, 0, sortedArray, 0, originalArrrayLength); - Arrays.sort(sortedArray); - return sortedArray; - } - - int[] pruneComposites(int[] sortedArray) { - ArrayList primesArray = new ArrayList(); - for (int i = 0; i < originalArrrayLength; i++) { - int n = sortedArray[i]; - if (isPrime(n)) { - primesArray.add(n); - } - } - int resultSize = primesArray.size(); - int[] result = new int[resultSize]; - - for (int i = 0; i < resultSize; i++) { - result[i] = primesArray.get(i); - } - return result; - } - - public boolean isPrime(int n) { - if (n < 2) { - return false; - } - if (n % 2 == 0) { - return false; - } - for (int i = 3; i * i <= n; i += 2) { - if (n % i == 0) { - return false; - } - } - return true; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +import java.util.ArrayList; +import java.util.Arrays; + +public class SortAndPruneComposites { + + static String NESTED_PROFILER_NAME = "SORT_AND_PRUNE"; + + final int[] originalArray; + final int originalArrrayLength; + + public SortAndPruneComposites(int[] randomArray) { + this.originalArray = randomArray; + this.originalArrrayLength = randomArray.length; + + } + + public int[] sortAndPruneComposites() { + // retrieve previously registered profiler named "SORT_AND_PRUNE" + ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); + Profiler sortProfiler = profilerRegistry.get(NESTED_PROFILER_NAME); + + // start a new stopwatch called SORT + sortProfiler.start("SORT"); + int[] sortedArray = sort(); + // start a new stopwatch called PRUNE_COMPOSITES + sortProfiler.start("PRUNE_COMPOSITES"); + int result[] = pruneComposites(sortedArray); + + return result; + } + + private int[] sort() { + int[] sortedArray = new int[originalArrrayLength]; + System.arraycopy(originalArray, 0, sortedArray, 0, originalArrrayLength); + Arrays.sort(sortedArray); + return sortedArray; + } + + int[] pruneComposites(int[] sortedArray) { + ArrayList primesArray = new ArrayList(); + for (int i = 0; i < originalArrrayLength; i++) { + int n = sortedArray[i]; + if (isPrime(n)) { + primesArray.add(n); + } + } + int resultSize = primesArray.size(); + int[] result = new int[resultSize]; + + for (int i = 0; i < resultSize; i++) { + result[i] = primesArray.get(i); + } + return result; + } + + public boolean isPrime(int n) { + if (n < 2) { + return false; + } + if (n % 2 == 0) { + return false; + } + for (int i = 3; i * i <= n; i += 2) { + if (n % i == 0) { + return false; + } + } + return true; + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/UtilTest.java b/slf4j-ext/src/test/java/org/slf4j/profiler/UtilTest.java index 5af271e..fc30251 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/UtilTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/UtilTest.java @@ -1,43 +1,43 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.profiler; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class UtilTest { - - @Test - public void testSelectDurationUnitForDisplay() throws InterruptedException { - assertEquals(DurationUnit.NANOSECOND, Util.selectDurationUnitForDisplay(10)); - assertEquals(DurationUnit.NANOSECOND, Util.selectDurationUnitForDisplay(9 * Util.NANOS_IN_ONE_MICROSECOND)); - assertEquals(DurationUnit.MICROSECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_MICROSECOND)); - assertEquals(DurationUnit.MICROSECOND, Util.selectDurationUnitForDisplay(9 * Util.NANOS_IN_ONE_MILLISECOND)); - assertEquals(DurationUnit.MILLISSECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_MILLISECOND)); - assertEquals(DurationUnit.SECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_SECOND)); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.profiler; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class UtilTest { + + @Test + public void testSelectDurationUnitForDisplay() throws InterruptedException { + assertEquals(DurationUnit.NANOSECOND, Util.selectDurationUnitForDisplay(10)); + assertEquals(DurationUnit.NANOSECOND, Util.selectDurationUnitForDisplay(9 * Util.NANOS_IN_ONE_MICROSECOND)); + assertEquals(DurationUnit.MICROSECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_MICROSECOND)); + assertEquals(DurationUnit.MICROSECOND, Util.selectDurationUnitForDisplay(9 * Util.NANOS_IN_ONE_MILLISECOND)); + assertEquals(DurationUnit.MILLISSECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_MILLISECOND)); + assertEquals(DurationUnit.SECOND, Util.selectDurationUnitForDisplay(11 * Util.NANOS_IN_ONE_SECOND)); + } + +} diff --git a/slf4j-ext/src/test/resources/log4j.properties b/slf4j-ext/src/test/resources/log4j.properties index bac0aa4..10c1170 100644 --- a/slf4j-ext/src/test/resources/log4j.properties +++ b/slf4j-ext/src/test/resources/log4j.properties @@ -1,6 +1,6 @@ - -log4j.rootLogger=DEBUG, CONSOLE - -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n + +log4j.rootLogger=DEBUG, CONSOLE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n diff --git a/slf4j-ext/src/test/resources/months_en.properties b/slf4j-ext/src/test/resources/months_en.properties index e3e20a1..fca46d4 100644 --- a/slf4j-ext/src/test/resources/months_en.properties +++ b/slf4j-ext/src/test/resources/months_en.properties @@ -1,6 +1,6 @@ -JAN=January -FEB=February -MAR=March -APR=April -MAY=May -JUN=June +JAN=January +FEB=February +MAR=March +APR=April +MAY=May +JUN=June diff --git a/slf4j-ext/src/test/resources/production_en_UK.properties b/slf4j-ext/src/test/resources/production_en_UK.properties index 1ed999f..65b8f56 100644 --- a/slf4j-ext/src/test/resources/production_en_UK.properties +++ b/slf4j-ext/src/test/resources/production_en_UK.properties @@ -1,4 +1,4 @@ -APPLICATION_STARTED=APPLICATION_STARTED -APPLICATION_STOPPED=APPLICATION_STOPPED -DB_CONNECTION=DB_CONNECTION +APPLICATION_STARTED=APPLICATION_STARTED +APPLICATION_STOPPED=APPLICATION_STOPPED +DB_CONNECTION=DB_CONNECTION DB_CONNECTION_FAILURE=DB_CONNECTION_FAILUREdiff --git a/slf4j-ext/src/test/resources/production_fr.properties b/slf4j-ext/src/test/resources/production_fr.properties index 1ed999f..65b8f56 100644 --- a/slf4j-ext/src/test/resources/production_fr.properties +++ b/slf4j-ext/src/test/resources/production_fr.properties @@ -1,4 +1,4 @@ -APPLICATION_STARTED=APPLICATION_STARTED -APPLICATION_STOPPED=APPLICATION_STOPPED -DB_CONNECTION=DB_CONNECTION +APPLICATION_STARTED=APPLICATION_STARTED +APPLICATION_STOPPED=APPLICATION_STOPPED +DB_CONNECTION=DB_CONNECTION DB_CONNECTION_FAILURE=DB_CONNECTION_FAILUREdiff --git a/slf4j-jcl/LICENSE.txt b/slf4j-jcl/LICENSE.txt new file mode 100644 index 0000000..508a272 --- /dev/null +++ b/slf4j-jcl/LICENSE.txt @@ -0,0 +1,24 @@ +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-jcl/pom.xml b/slf4j-jcl/pom.xml old file mode 100644 new file mode 100755 index 9e313ca..1ad7e9e 100755 --- a/slf4j-jcl/pom.xml +++ b/slf4j-jcl/pom.xml @@ -1,32 +1,32 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - slf4j-jcl - jar - SLF4J JCL Binding - SLF4J JCL Binding - - http://www.slf4j.org - - - - org.slf4j - slf4j-api - - - commons-logging - commons-logging - 1.1.1 - - - + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + slf4j-jcl + jar + SLF4J JCL Binding + SLF4J JCL Binding + + http://www.slf4j.org + + + + org.slf4j + slf4j-api + + + commons-logging + commons-logging + 1.1.1 + + + diff --git a/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java b/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java index d0901db..ad07520 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java @@ -1,531 +1,531 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -package org.slf4j.impl; - -import org.apache.commons.logging.Log; -import org.slf4j.Logger; -import org.slf4j.helpers.FormattingTuple; -import org.slf4j.helpers.MarkerIgnoringBase; -import org.slf4j.helpers.MessageFormatter; - -/** - * A wrapper over {@link org.apache.commons.logging.Log - * org.apache.commons.logging.Log} in conformance with the {@link Logger} - * interface. - * - * @author Ceki Gülcü - */ -public final class JCLLoggerAdapter extends MarkerIgnoringBase { - - private static final long serialVersionUID = 4141593417490482209L; - final Log log; - - // WARN: JCLLoggerAdapter constructor should have only package access so - // that only JCLLoggerFactory be able to create one. - JCLLoggerAdapter(Log log, String name) { - this.log = log; - this.name = name; - } - - /** - * Delegates to the {@link Log#isTraceEnabled} method of the underlying - * {@link Log} instance. - */ - public boolean isTraceEnabled() { - return log.isTraceEnabled(); - } - - // - - /** - * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - * @param msg - the message object to be logged - */ - public void trace(String msg) { - log.trace(msg); - } - - /** - * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level TRACE. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void trace(String format, Object arg) { - if (log.isTraceEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log.trace(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level TRACE. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void trace(String format, Object arg1, Object arg2) { - if (log.isTraceEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - log.trace(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level TRACE. - *

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void trace(String format, Object... arguments) { - if (log.isTraceEnabled()) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - log.trace(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#trace(java.lang.Object, java.lang.Throwable)} method of - * the underlying {@link Log} instance. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void trace(String msg, Throwable t) { - log.trace(msg, t); - } - - /** - * Delegates to the {@link Log#isDebugEnabled} method of the underlying - * {@link Log} instance. - */ - public boolean isDebugEnabled() { - return log.isDebugEnabled(); - } - - // - - /** - * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - * @param msg - the message object to be logged - */ - public void debug(String msg) { - log.debug(msg); - } - - /** - * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level DEBUG. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void debug(String format, Object arg) { - if (log.isDebugEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log.debug(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level DEBUG. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void debug(String format, Object arg1, Object arg2) { - if (log.isDebugEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - log.debug(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level DEBUG. - *

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void debug(String format, Object... arguments) { - if (log.isDebugEnabled()) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - log.debug(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#debug(java.lang.Object, java.lang.Throwable)} method of - * the underlying {@link Log} instance. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void debug(String msg, Throwable t) { - log.debug(msg, t); - } - - /** - * Delegates to the {@link Log#isInfoEnabled} method of the underlying - * {@link Log} instance. - */ - public boolean isInfoEnabled() { - return log.isInfoEnabled(); - } - - /** - * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - * @param msg - the message object to be logged - */ - public void info(String msg) { - log.info(msg); - } - - /** - * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level INFO. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - - public void info(String format, Object arg) { - if (log.isInfoEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log.info(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level INFO. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void info(String format, Object arg1, Object arg2) { - if (log.isInfoEnabled()) { - - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - log.info(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level INFO. - *

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void info(String format, Object... arguments) { - if (log.isInfoEnabled()) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - log.info(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#info(java.lang.Object, java.lang.Throwable)} method of - * the underlying {@link Log} instance. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void info(String msg, Throwable t) { - log.info(msg, t); - } - - /** - * Delegates to the {@link Log#isWarnEnabled} method of the underlying - * {@link Log} instance. - */ - public boolean isWarnEnabled() { - return log.isWarnEnabled(); - } - - /** - * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - * @param msg - the message object to be logged - */ - public void warn(String msg) { - log.warn(msg); - } - - /** - * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level WARN. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void warn(String format, Object arg) { - if (log.isWarnEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log.warn(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level WARN. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void warn(String format, Object arg1, Object arg2) { - if (log.isWarnEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - log.warn(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level WARN. - *

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void warn(String format, Object... arguments) { - if (log.isWarnEnabled()) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - log.warn(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#warn(java.lang.Object, java.lang.Throwable)} method of - * the underlying {@link Log} instance. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - - public void warn(String msg, Throwable t) { - log.warn(msg, t); - } - - /** - * Delegates to the {@link Log#isErrorEnabled} method of the underlying - * {@link Log} instance. - */ - public boolean isErrorEnabled() { - return log.isErrorEnabled(); - } - - /** - * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - * @param msg - the message object to be logged - */ - public void error(String msg) { - log.error(msg); - } - - /** - * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level ERROR. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void error(String format, Object arg) { - if (log.isErrorEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log.error(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level ERROR. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void error(String format, Object arg1, Object arg2) { - if (log.isErrorEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - log.error(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

- * However, this form avoids superfluous object creation when the logger is disabled - * for level ERROR. - *

- * - * @param format the format string - * @param arguments a list of 3 or more arguments - */ - public void error(String format, Object... arguments) { - if (log.isErrorEnabled()) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - log.error(ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Delegates to the {@link Log#error(java.lang.Object, java.lang.Throwable)} method of - * the underlying {@link Log} instance. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - - public void error(String msg, Throwable t) { - log.error(msg, t); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +package org.slf4j.impl; + +import org.apache.commons.logging.Log; +import org.slf4j.Logger; +import org.slf4j.helpers.FormattingTuple; +import org.slf4j.helpers.MarkerIgnoringBase; +import org.slf4j.helpers.MessageFormatter; + +/** + * A wrapper over {@link org.apache.commons.logging.Log + * org.apache.commons.logging.Log} in conformance with the {@link Logger} + * interface. + * + * @author Ceki Gülcü + */ +public final class JCLLoggerAdapter extends MarkerIgnoringBase { + + private static final long serialVersionUID = 4141593417490482209L; + final Log log; + + // WARN: JCLLoggerAdapter constructor should have only package access so + // that only JCLLoggerFactory be able to create one. + JCLLoggerAdapter(Log log, String name) { + this.log = log; + this.name = name; + } + + /** + * Delegates to the {@link Log#isTraceEnabled} method of the underlying + * {@link Log} instance. + */ + public boolean isTraceEnabled() { + return log.isTraceEnabled(); + } + + // + + /** + * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + * @param msg - the message object to be logged + */ + public void trace(String msg) { + log.trace(msg); + } + + /** + * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level TRACE. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void trace(String format, Object arg) { + if (log.isTraceEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log.trace(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level TRACE. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void trace(String format, Object arg1, Object arg2) { + if (log.isTraceEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + log.trace(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level TRACE. + *

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void trace(String format, Object... arguments) { + if (log.isTraceEnabled()) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + log.trace(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#trace(java.lang.Object, java.lang.Throwable)} method of + * the underlying {@link Log} instance. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void trace(String msg, Throwable t) { + log.trace(msg, t); + } + + /** + * Delegates to the {@link Log#isDebugEnabled} method of the underlying + * {@link Log} instance. + */ + public boolean isDebugEnabled() { + return log.isDebugEnabled(); + } + + // + + /** + * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + * @param msg - the message object to be logged + */ + public void debug(String msg) { + log.debug(msg); + } + + /** + * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level DEBUG. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void debug(String format, Object arg) { + if (log.isDebugEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log.debug(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level DEBUG. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void debug(String format, Object arg1, Object arg2) { + if (log.isDebugEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + log.debug(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level DEBUG. + *

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void debug(String format, Object... arguments) { + if (log.isDebugEnabled()) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + log.debug(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#debug(java.lang.Object, java.lang.Throwable)} method of + * the underlying {@link Log} instance. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void debug(String msg, Throwable t) { + log.debug(msg, t); + } + + /** + * Delegates to the {@link Log#isInfoEnabled} method of the underlying + * {@link Log} instance. + */ + public boolean isInfoEnabled() { + return log.isInfoEnabled(); + } + + /** + * Delegates to the {@link Log#debug(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + * @param msg - the message object to be logged + */ + public void info(String msg) { + log.info(msg); + } + + /** + * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level INFO. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + + public void info(String format, Object arg) { + if (log.isInfoEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log.info(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level INFO. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void info(String format, Object arg1, Object arg2) { + if (log.isInfoEnabled()) { + + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + log.info(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#info(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level INFO. + *

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void info(String format, Object... arguments) { + if (log.isInfoEnabled()) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + log.info(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#info(java.lang.Object, java.lang.Throwable)} method of + * the underlying {@link Log} instance. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void info(String msg, Throwable t) { + log.info(msg, t); + } + + /** + * Delegates to the {@link Log#isWarnEnabled} method of the underlying + * {@link Log} instance. + */ + public boolean isWarnEnabled() { + return log.isWarnEnabled(); + } + + /** + * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + * @param msg - the message object to be logged + */ + public void warn(String msg) { + log.warn(msg); + } + + /** + * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level WARN. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void warn(String format, Object arg) { + if (log.isWarnEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log.warn(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level WARN. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void warn(String format, Object arg1, Object arg2) { + if (log.isWarnEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + log.warn(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#warn(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level WARN. + *

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void warn(String format, Object... arguments) { + if (log.isWarnEnabled()) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + log.warn(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#warn(java.lang.Object, java.lang.Throwable)} method of + * the underlying {@link Log} instance. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + + public void warn(String msg, Throwable t) { + log.warn(msg, t); + } + + /** + * Delegates to the {@link Log#isErrorEnabled} method of the underlying + * {@link Log} instance. + */ + public boolean isErrorEnabled() { + return log.isErrorEnabled(); + } + + /** + * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + * @param msg - the message object to be logged + */ + public void error(String msg) { + log.error(msg); + } + + /** + * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level ERROR. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void error(String format, Object arg) { + if (log.isErrorEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log.error(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level ERROR. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void error(String format, Object arg1, Object arg2) { + if (log.isErrorEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + log.error(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#error(java.lang.Object)} method of the underlying + * {@link Log} instance. + * + *

+ * However, this form avoids superfluous object creation when the logger is disabled + * for level ERROR. + *

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + public void error(String format, Object... arguments) { + if (log.isErrorEnabled()) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + log.error(ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Delegates to the {@link Log#error(java.lang.Object, java.lang.Throwable)} method of + * the underlying {@link Log} instance. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + + public void error(String msg, Throwable t) { + log.error(msg, t); + } + +} diff --git a/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerFactory.java b/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerFactory.java index 024e80a..79be104 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerFactory.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerFactory.java @@ -1,83 +1,83 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.apache.commons.logging.LogFactory; -import org.slf4j.ILoggerFactory; -import org.slf4j.Logger; -import org.slf4j.helpers.Util; - -/** - * JCLLoggerFactory is an implementation of {@link ILoggerFactory} returning the - * appropriately named {@link JCLLoggerAdapter} instance. - * - * @author Ceki Gülcü - */ -public class JCLLoggerFactory implements ILoggerFactory { - - private static final String JCL_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#jclDelegationLoop"; - - // check for delegation loops - static { - try { - Class.forName("org.apache.commons.logging.impl.SLF4JLogFactory"); - String part1 = "Detected both jcl-over-slf4j.jar AND bound slf4j-jcl.jar on the class path, preempting StackOverflowError. "; - String part2 = "See also " + JCL_DELEGATION_LOOP_URL + " for more details."; - - Util.report(part1); - Util.report(part2); - throw new IllegalStateException(part1 + part2); - } catch (ClassNotFoundException e) { - // this is the good case - } - } - - // key: name (String), value: a JCLLoggerAdapter; - final ConcurrentMap loggerMap; - - public JCLLoggerFactory() { - loggerMap = new ConcurrentHashMap(); - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) - */ - public Logger getLogger(String name) { - Logger slf4jLogger = loggerMap.get(name); - if (slf4jLogger != null) { - return slf4jLogger; - } else { - org.apache.commons.logging.Log jclLogger = LogFactory.getLog(name); - Logger newInstance = new JCLLoggerAdapter(jclLogger, name); - Logger oldInstance = loggerMap.putIfAbsent(name, newInstance); - return oldInstance == null ? newInstance : oldInstance; - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.apache.commons.logging.LogFactory; +import org.slf4j.ILoggerFactory; +import org.slf4j.Logger; +import org.slf4j.helpers.Util; + +/** + * JCLLoggerFactory is an implementation of {@link ILoggerFactory} returning the + * appropriately named {@link JCLLoggerAdapter} instance. + * + * @author Ceki Gülcü + */ +public class JCLLoggerFactory implements ILoggerFactory { + + private static final String JCL_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#jclDelegationLoop"; + + // check for delegation loops + static { + try { + Class.forName("org.apache.commons.logging.impl.SLF4JLogFactory"); + String part1 = "Detected both jcl-over-slf4j.jar AND bound slf4j-jcl.jar on the class path, preempting StackOverflowError. "; + String part2 = "See also " + JCL_DELEGATION_LOOP_URL + " for more details."; + + Util.report(part1); + Util.report(part2); + throw new IllegalStateException(part1 + part2); + } catch (ClassNotFoundException e) { + // this is the good case + } + } + + // key: name (String), value: a JCLLoggerAdapter; + final ConcurrentMap loggerMap; + + public JCLLoggerFactory() { + loggerMap = new ConcurrentHashMap(); + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) + */ + public Logger getLogger(String name) { + Logger slf4jLogger = loggerMap.get(name); + if (slf4jLogger != null) { + return slf4jLogger; + } else { + org.apache.commons.logging.Log jclLogger = LogFactory.getLog(name); + Logger newInstance = new JCLLoggerAdapter(jclLogger, name); + Logger oldInstance = loggerMap.putIfAbsent(name, newInstance); + return oldInstance == null ? newInstance : oldInstance; + } + } +} diff --git a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index 70ef3c4..a2504cd 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,81 +1,81 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - /** - * Declare the version of the SLF4J API this implementation is compiled against. - * The value of this field is modified with each major release. - */ - // to avoid constant folding by the compiler, this field must *not* be final - public static String REQUESTED_API_VERSION = "1.6.99"; // !final - - // Binding specific code: - private static final String loggerFactoryClassStr = JCLLoggerFactory.class.getName(); - - /** - * The ILoggerFactory instance returned by the {@link #getLoggerFactory} - * method should always be the same object - */ - private final ILoggerFactory loggerFactory; - - private StaticLoggerBinder() { - // Binding specific code: - loggerFactory = new JCLLoggerFactory(); - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is modified with each major release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; // !final + + // Binding specific code: + private static final String loggerFactoryClassStr = JCLLoggerFactory.class.getName(); + + /** + * The ILoggerFactory instance returned by the {@link #getLoggerFactory} + * method should always be the same object + */ + private final ILoggerFactory loggerFactory; + + private StaticLoggerBinder() { + // Binding specific code: + loggerFactory = new JCLLoggerFactory(); + } + + public ILoggerFactory getLoggerFactory() { + return loggerFactory; + } + + public String getLoggerFactoryClassStr() { + return loggerFactoryClassStr; + } +} diff --git a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMDCBinder.java index 3a63ba8..d9945eb 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,69 +1,69 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.helpers.NOPMDCAdapter; -import org.slf4j.spi.MDCAdapter; - -/** - * This implementation is bound to {@link NOPMDCAdapter}. - * - * @author Ceki Gülcü - */ -public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - - private StaticMDCBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMDCBinder singleton - * @since 1.7.14 - */ - public static final StaticMDCBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link NOPMDCAdapter}. - * - * @return instance of NOPMDCAdapter - * @since 1.7.14 - */ - public MDCAdapter getMDCA() { - return new NOPMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return NOPMDCAdapter.class.getName(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.helpers.NOPMDCAdapter; +import org.slf4j.spi.MDCAdapter; + +/** + * This implementation is bound to {@link NOPMDCAdapter}. + * + * @author Ceki Gülcü + */ +public class StaticMDCBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMDCBinder singleton + * @since 1.7.14 + */ + public static final StaticMDCBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link NOPMDCAdapter}. + * + * @return instance of NOPMDCAdapter + * @since 1.7.14 + */ + public MDCAdapter getMDCA() { + return new NOPMDCAdapter(); + } + + public String getMDCAdapterClassStr() { + return NOPMDCAdapter.class.getName(); + } +} diff --git a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMarkerBinder.java b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMarkerBinder.java index 21a48df..c37af78 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,77 +1,77 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMarkerBinder singleton - * @since 1.7.14 - */ - public static StaticMarkerBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMarkerBinder singleton + * @since 1.7.14 + */ + public static StaticMarkerBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + +} diff --git a/slf4j-jcl/src/main/resources/META-INF/MANIFEST.MF b/slf4j-jcl/src/main/resources/META-INF/MANIFEST.MF index 694ff1c..a9ee90e 100644 --- a/slf4j-jcl/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-jcl/src/main/resources/META-INF/MANIFEST.MF @@ -1,10 +1,10 @@ -Implementation-Title: slf4j-jcl -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.jcl -Bundle-Name: slf4j-jcl -Bundle-Vendor: SLF4J.ORG -Require-Bundle: slf4j.api -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, org.apache.commons.logging +Implementation-Title: slf4j-jcl +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.jcl +Bundle-Name: slf4j-jcl +Bundle-Vendor: SLF4J.ORG +Require-Bundle: slf4j.api +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, org.apache.commons.logging Fragment-Host: slf4j.apidiff --git a/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java b/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java index 50b74d7..1ce3f9b 100644 --- a/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java @@ -1,130 +1,130 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import static org.junit.Assert.assertNull; - -import java.util.logging.Level; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - * - */ -public class InvocationTest { - - Level oldLevel; - java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); - - @Before - public void setUp() throws Exception { - oldLevel = root.getLevel(); - root.setLevel(Level.OFF); - } - - @After - public void tearDown() throws Exception { - root.setLevel(oldLevel); - } - - @Test - public void test1() { - Logger logger = LoggerFactory.getLogger("test1"); - logger.debug("Hello world."); - } - - @Test - public void test2() { - Integer i1 = new Integer(1); - Integer i2 = new Integer(2); - Integer i3 = new Integer(3); - Exception e = new Exception("This is a test exception."); - Logger logger = LoggerFactory.getLogger("test2"); - - logger.debug("Hello world 1."); - logger.debug("Hello world {}", i1); - logger.debug("val={} val={}", i1, i2); - logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); - - logger.debug("Hello world 2", e); - logger.info("Hello world 2."); - - logger.warn("Hello world 3."); - logger.warn("Hello world 3", e); - - logger.error("Hello world 4."); - logger.error("Hello world {}", new Integer(3)); - logger.error("Hello world 4.", e); - } - - @Test - public void testNull() { - Logger logger = LoggerFactory.getLogger("testNull"); - logger.debug(null); - logger.info(null); - logger.warn(null); - logger.error(null); - - Exception e = new Exception("This is a test exception."); - logger.debug(null, e); - logger.info(null, e); - logger.warn(null, e); - logger.error(null, e); - } - - @Test - public void testMarker() { - Logger logger = LoggerFactory.getLogger("testMarker"); - Marker blue = MarkerFactory.getMarker("BLUE"); - logger.debug(blue, "hello"); - logger.info(blue, "hello"); - logger.warn(blue, "hello"); - logger.error(blue, "hello"); - - logger.debug(blue, "hello {}", "world"); - logger.info(blue, "hello {}", "world"); - logger.warn(blue, "hello {}", "world"); - logger.error(blue, "hello {}", "world"); - - logger.debug(blue, "hello {} and {} ", "world", "universe"); - logger.info(blue, "hello {} and {} ", "world", "universe"); - logger.warn(blue, "hello {} and {} ", "world", "universe"); - logger.error(blue, "hello {} and {} ", "world", "universe"); - } - - @Test - public void testMDC() { - MDC.put("k", "v"); - assertNull(MDC.get("k")); - MDC.remove("k"); - assertNull(MDC.get("k")); - MDC.clear(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import static org.junit.Assert.assertNull; + +import java.util.logging.Level; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * Test whether invoking the SLF4J API causes problems or not. + * + * @author Ceki Gulcu + * + */ +public class InvocationTest { + + Level oldLevel; + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); + + @Before + public void setUp() throws Exception { + oldLevel = root.getLevel(); + root.setLevel(Level.OFF); + } + + @After + public void tearDown() throws Exception { + root.setLevel(oldLevel); + } + + @Test + public void test1() { + Logger logger = LoggerFactory.getLogger("test1"); + logger.debug("Hello world."); + } + + @Test + public void test2() { + Integer i1 = new Integer(1); + Integer i2 = new Integer(2); + Integer i3 = new Integer(3); + Exception e = new Exception("This is a test exception."); + Logger logger = LoggerFactory.getLogger("test2"); + + logger.debug("Hello world 1."); + logger.debug("Hello world {}", i1); + logger.debug("val={} val={}", i1, i2); + logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); + + logger.debug("Hello world 2", e); + logger.info("Hello world 2."); + + logger.warn("Hello world 3."); + logger.warn("Hello world 3", e); + + logger.error("Hello world 4."); + logger.error("Hello world {}", new Integer(3)); + logger.error("Hello world 4.", e); + } + + @Test + public void testNull() { + Logger logger = LoggerFactory.getLogger("testNull"); + logger.debug(null); + logger.info(null); + logger.warn(null); + logger.error(null); + + Exception e = new Exception("This is a test exception."); + logger.debug(null, e); + logger.info(null, e); + logger.warn(null, e); + logger.error(null, e); + } + + @Test + public void testMarker() { + Logger logger = LoggerFactory.getLogger("testMarker"); + Marker blue = MarkerFactory.getMarker("BLUE"); + logger.debug(blue, "hello"); + logger.info(blue, "hello"); + logger.warn(blue, "hello"); + logger.error(blue, "hello"); + + logger.debug(blue, "hello {}", "world"); + logger.info(blue, "hello {}", "world"); + logger.warn(blue, "hello {}", "world"); + logger.error(blue, "hello {}", "world"); + + logger.debug(blue, "hello {} and {} ", "world", "universe"); + logger.info(blue, "hello {} and {} ", "world", "universe"); + logger.warn(blue, "hello {} and {} ", "world", "universe"); + logger.error(blue, "hello {} and {} ", "world", "universe"); + } + + @Test + public void testMDC() { + MDC.put("k", "v"); + assertNull(MDC.get("k")); + MDC.remove("k"); + assertNull(MDC.get("k")); + MDC.clear(); + } +} diff --git a/slf4j-jdk14/LICENSE.txt b/slf4j-jdk14/LICENSE.txt new file mode 100644 index 0000000..508a272 --- /dev/null +++ b/slf4j-jdk14/LICENSE.txt @@ -0,0 +1,24 @@ +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-jdk14/pom.xml b/slf4j-jdk14/pom.xml old file mode 100644 new file mode 100755 index a165a71..90d375f 100755 --- a/slf4j-jdk14/pom.xml +++ b/slf4j-jdk14/pom.xml @@ -1,34 +1,35 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - slf4j-jdk14 - jar - SLF4J JDK14 Binding - SLF4J JDK14 Binding - http://www.slf4j.org - - - - org.slf4j - slf4j-api - - - - org.slf4j - slf4j-api - test-jar - ${project.version} - test - - - - \ No newline at end of file + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + slf4j-jdk14 + jar + SLF4J JDK14 Binding + SLF4J JDK14 Binding + http://www.slf4j.org + + + + org.slf4j + slf4j-api + + + + org.slf4j + slf4j-api + test-jar + ${project.version} + test + + + + + diff --git a/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerAdapter.java b/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerAdapter.java old file mode 100644 new file mode 100755 index 7cfafc8..1fb2022 100755 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerAdapter.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerAdapter.java @@ -1,694 +1,694 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import java.util.logging.Level; -import java.util.logging.LogRecord; - -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.event.EventConstants; -import org.slf4j.event.LoggingEvent; -import org.slf4j.helpers.FormattingTuple; -import org.slf4j.helpers.MarkerIgnoringBase; -import org.slf4j.helpers.MessageFormatter; -import org.slf4j.spi.LocationAwareLogger; - -/** - * A wrapper over {@link java.util.logging.Logger java.util.logging.Logger} in - * conformity with the {@link Logger} interface. Note that the logging levels - * mentioned in this class refer to those defined in the java.util.logging - * package. - * - * @author Ceki Gülcü - * @author Peter Royal - */ -public final class JDK14LoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger { - - private static final long serialVersionUID = -8053026990503422791L; - - transient final java.util.logging.Logger logger; - - // WARN: JDK14LoggerAdapter constructor should have only package access so - // that only JDK14LoggerFactory be able to create one. - JDK14LoggerAdapter(java.util.logging.Logger logger) { - this.logger = logger; - this.name = logger.getName(); - } - - /** - * Is this logger instance enabled for the FINEST level? - * - * @return True if this Logger is enabled for level FINEST, false otherwise. - */ - public boolean isTraceEnabled() { - return logger.isLoggable(Level.FINEST); - } - - /** - * Log a message object at level FINEST. - * - * @param msg - * - the message object to be logged - */ - public void trace(String msg) { - if (logger.isLoggable(Level.FINEST)) { - log(SELF, Level.FINEST, msg, null); - } - } - - /** - * Log a message at level FINEST according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for level FINEST. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void trace(String format, Object arg) { - if (logger.isLoggable(Level.FINEST)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level FINEST according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the FINEST level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void trace(String format, Object arg1, Object arg2) { - if (logger.isLoggable(Level.FINEST)) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level FINEST according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the FINEST level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void trace(String format, Object... argArray) { - if (logger.isLoggable(Level.FINEST)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at level FINEST with an accompanying message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void trace(String msg, Throwable t) { - if (logger.isLoggable(Level.FINEST)) { - log(SELF, Level.FINEST, msg, t); - } - } - - /** - * Is this logger instance enabled for the FINE level? - * - * @return True if this Logger is enabled for level FINE, false otherwise. - */ - public boolean isDebugEnabled() { - return logger.isLoggable(Level.FINE); - } - - /** - * Log a message object at level FINE. - * - * @param msg - * - the message object to be logged - */ - public void debug(String msg) { - if (logger.isLoggable(Level.FINE)) { - log(SELF, Level.FINE, msg, null); - } - } - - /** - * Log a message at level FINE according to the specified format and argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for level FINE. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void debug(String format, Object arg) { - if (logger.isLoggable(Level.FINE)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level FINE according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the FINE level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void debug(String format, Object arg1, Object arg2) { - if (logger.isLoggable(Level.FINE)) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level FINE according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the FINE level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void debug(String format, Object... argArray) { - if (logger.isLoggable(Level.FINE)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at level FINE with an accompanying message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void debug(String msg, Throwable t) { - if (logger.isLoggable(Level.FINE)) { - log(SELF, Level.FINE, msg, t); - } - } - - /** - * Is this logger instance enabled for the INFO level? - * - * @return True if this Logger is enabled for the INFO level, false otherwise. - */ - public boolean isInfoEnabled() { - return logger.isLoggable(Level.INFO); - } - - /** - * Log a message object at the INFO level. - * - * @param msg - * - the message object to be logged - */ - public void info(String msg) { - if (logger.isLoggable(Level.INFO)) { - log(SELF, Level.INFO, msg, null); - } - } - - /** - * Log a message at level INFO according to the specified format and argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void info(String format, Object arg) { - if (logger.isLoggable(Level.INFO)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at the INFO level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void info(String format, Object arg1, Object arg2) { - if (logger.isLoggable(Level.INFO)) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level INFO according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void info(String format, Object... argArray) { - if (logger.isLoggable(Level.INFO)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at the INFO level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void info(String msg, Throwable t) { - if (logger.isLoggable(Level.INFO)) { - log(SELF, Level.INFO, msg, t); - } - } - - /** - * Is this logger instance enabled for the WARNING level? - * - * @return True if this Logger is enabled for the WARNING level, false - * otherwise. - */ - public boolean isWarnEnabled() { - return logger.isLoggable(Level.WARNING); - } - - /** - * Log a message object at the WARNING level. - * - * @param msg - * - the message object to be logged - */ - public void warn(String msg) { - if (logger.isLoggable(Level.WARNING)) { - log(SELF, Level.WARNING, msg, null); - } - } - - /** - * Log a message at the WARNING level according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARNING level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void warn(String format, Object arg) { - if (logger.isLoggable(Level.WARNING)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at the WARNING level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARNING level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void warn(String format, Object arg1, Object arg2) { - if (logger.isLoggable(Level.WARNING)) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level WARNING according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARNING level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void warn(String format, Object... argArray) { - if (logger.isLoggable(Level.WARNING)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at the WARNING level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void warn(String msg, Throwable t) { - if (logger.isLoggable(Level.WARNING)) { - log(SELF, Level.WARNING, msg, t); - } - } - - /** - * Is this logger instance enabled for level SEVERE? - * - * @return True if this Logger is enabled for level SEVERE, false otherwise. - */ - public boolean isErrorEnabled() { - return logger.isLoggable(Level.SEVERE); - } - - /** - * Log a message object at the SEVERE level. - * - * @param msg - * - the message object to be logged - */ - public void error(String msg) { - if (logger.isLoggable(Level.SEVERE)) { - log(SELF, Level.SEVERE, msg, null); - } - } - - /** - * Log a message at the SEVERE level according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the SEVERE level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void error(String format, Object arg) { - if (logger.isLoggable(Level.SEVERE)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at the SEVERE level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the SEVERE level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void error(String format, Object arg1, Object arg2) { - if (logger.isLoggable(Level.SEVERE)) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level SEVERE according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the SEVERE level. - *

- * - * @param format - * the format string - * @param arguments - * an array of arguments - */ - public void error(String format, Object... arguments) { - if (logger.isLoggable(Level.SEVERE)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at the SEVERE level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void error(String msg, Throwable t) { - if (logger.isLoggable(Level.SEVERE)) { - log(SELF, Level.SEVERE, msg, t); - } - } - - /** - * Log the message at the specified level with the specified throwable if any. - * This method creates a LogRecord and fills in caller date before calling - * this instance's JDK14 logger. - * - * See bug report #13 for more details. - * - * @param level - * @param msg - * @param t - */ - private void log(String callerFQCN, Level level, String msg, Throwable t) { - // millis and thread are filled by the constructor - LogRecord record = new LogRecord(level, msg); - record.setLoggerName(getName()); - record.setThrown(t); - // Note: parameters in record are not set because SLF4J only - // supports a single formatting style - fillCallerData(callerFQCN, record); - logger.log(record); - } - - static String SELF = JDK14LoggerAdapter.class.getName(); - static String SUPER = MarkerIgnoringBase.class.getName(); - - /** - * Fill in caller data if possible. - * - * @param record - * The record to update - */ - final private void fillCallerData(String callerFQCN, LogRecord record) { - StackTraceElement[] steArray = new Throwable().getStackTrace(); - - int selfIndex = -1; - for (int i = 0; i < steArray.length; i++) { - final String className = steArray[i].getClassName(); - if (className.equals(callerFQCN) || className.equals(SUPER)) { - selfIndex = i; - break; - } - } - - int found = -1; - for (int i = selfIndex + 1; i < steArray.length; i++) { - final String className = steArray[i].getClassName(); - if (!(className.equals(callerFQCN) || className.equals(SUPER))) { - found = i; - break; - } - } - - if (found != -1) { - StackTraceElement ste = steArray[found]; - // setting the class name has the side effect of setting - // the needToInferCaller variable to false. - record.setSourceClassName(ste.getClassName()); - record.setSourceMethodName(ste.getMethodName()); - } - } - - public void log(Marker marker, String callerFQCN, int level, String message, Object[] argArray, Throwable t) { - Level julLevel = slf4jLevelIntToJULLevel(level); - // the logger.isLoggable check avoids the unconditional - // construction of location data for disabled log - // statements. As of 2008-07-31, callers of this method - // do not perform this check. See also - // http://jira.qos.ch/browse/SLF4J-81 - if (logger.isLoggable(julLevel)) { - log(callerFQCN, julLevel, message, t); - } - } - - private Level slf4jLevelIntToJULLevel(int slf4jLevelInt) { - Level julLevel; - switch (slf4jLevelInt) { - case LocationAwareLogger.TRACE_INT: - julLevel = Level.FINEST; - break; - case LocationAwareLogger.DEBUG_INT: - julLevel = Level.FINE; - break; - case LocationAwareLogger.INFO_INT: - julLevel = Level.INFO; - break; - case LocationAwareLogger.WARN_INT: - julLevel = Level.WARNING; - break; - case LocationAwareLogger.ERROR_INT: - julLevel = Level.SEVERE; - break; - default: - throw new IllegalStateException("Level number " + slf4jLevelInt + " is not recognized."); - } - return julLevel; - } - - /** - * @since 1.7.15 - */ - public void log(LoggingEvent event) { - Level julLevel = slf4jLevelIntToJULLevel(event.getLevel().toInt()); - if (logger.isLoggable(julLevel)) { - LogRecord record = eventToRecord(event, julLevel); - logger.log(record); - } - } - - private LogRecord eventToRecord(LoggingEvent event, Level julLevel) { - String format = event.getMessage(); - Object[] arguments = event.getArgumentArray(); - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - if (ft.getThrowable() != null && event.getThrowable() != null) { - throw new IllegalArgumentException("both last element in argument array and last argument are of type Throwable"); - } - - Throwable t = event.getThrowable(); - if (ft.getThrowable() != null) { - t = ft.getThrowable(); - throw new IllegalStateException("fix above code"); - } - - LogRecord record = new LogRecord(julLevel, ft.getMessage()); - record.setLoggerName(event.getLoggerName()); - record.setMillis(event.getTimeStamp()); - record.setSourceClassName(EventConstants.NA_SUBST); - record.setSourceMethodName(EventConstants.NA_SUBST); - - record.setThrown(t); - return record; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.event.EventConstants; +import org.slf4j.event.LoggingEvent; +import org.slf4j.helpers.FormattingTuple; +import org.slf4j.helpers.MarkerIgnoringBase; +import org.slf4j.helpers.MessageFormatter; +import org.slf4j.spi.LocationAwareLogger; + +/** + * A wrapper over {@link java.util.logging.Logger java.util.logging.Logger} in + * conformity with the {@link Logger} interface. Note that the logging levels + * mentioned in this class refer to those defined in the java.util.logging + * package. + * + * @author Ceki Gülcü + * @author Peter Royal + */ +public final class JDK14LoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger { + + private static final long serialVersionUID = -8053026990503422791L; + + transient final java.util.logging.Logger logger; + + // WARN: JDK14LoggerAdapter constructor should have only package access so + // that only JDK14LoggerFactory be able to create one. + JDK14LoggerAdapter(java.util.logging.Logger logger) { + this.logger = logger; + this.name = logger.getName(); + } + + /** + * Is this logger instance enabled for the FINEST level? + * + * @return True if this Logger is enabled for level FINEST, false otherwise. + */ + public boolean isTraceEnabled() { + return logger.isLoggable(Level.FINEST); + } + + /** + * Log a message object at level FINEST. + * + * @param msg + * - the message object to be logged + */ + public void trace(String msg) { + if (logger.isLoggable(Level.FINEST)) { + log(SELF, Level.FINEST, msg, null); + } + } + + /** + * Log a message at level FINEST according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for level FINEST. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void trace(String format, Object arg) { + if (logger.isLoggable(Level.FINEST)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level FINEST according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the FINEST level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void trace(String format, Object arg1, Object arg2) { + if (logger.isLoggable(Level.FINEST)) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level FINEST according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the FINEST level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void trace(String format, Object... argArray) { + if (logger.isLoggable(Level.FINEST)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at level FINEST with an accompanying message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void trace(String msg, Throwable t) { + if (logger.isLoggable(Level.FINEST)) { + log(SELF, Level.FINEST, msg, t); + } + } + + /** + * Is this logger instance enabled for the FINE level? + * + * @return True if this Logger is enabled for level FINE, false otherwise. + */ + public boolean isDebugEnabled() { + return logger.isLoggable(Level.FINE); + } + + /** + * Log a message object at level FINE. + * + * @param msg + * - the message object to be logged + */ + public void debug(String msg) { + if (logger.isLoggable(Level.FINE)) { + log(SELF, Level.FINE, msg, null); + } + } + + /** + * Log a message at level FINE according to the specified format and argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for level FINE. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void debug(String format, Object arg) { + if (logger.isLoggable(Level.FINE)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level FINE according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the FINE level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void debug(String format, Object arg1, Object arg2) { + if (logger.isLoggable(Level.FINE)) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level FINE according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the FINE level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void debug(String format, Object... argArray) { + if (logger.isLoggable(Level.FINE)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at level FINE with an accompanying message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void debug(String msg, Throwable t) { + if (logger.isLoggable(Level.FINE)) { + log(SELF, Level.FINE, msg, t); + } + } + + /** + * Is this logger instance enabled for the INFO level? + * + * @return True if this Logger is enabled for the INFO level, false otherwise. + */ + public boolean isInfoEnabled() { + return logger.isLoggable(Level.INFO); + } + + /** + * Log a message object at the INFO level. + * + * @param msg + * - the message object to be logged + */ + public void info(String msg) { + if (logger.isLoggable(Level.INFO)) { + log(SELF, Level.INFO, msg, null); + } + } + + /** + * Log a message at level INFO according to the specified format and argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void info(String format, Object arg) { + if (logger.isLoggable(Level.INFO)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at the INFO level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void info(String format, Object arg1, Object arg2) { + if (logger.isLoggable(Level.INFO)) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level INFO according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void info(String format, Object... argArray) { + if (logger.isLoggable(Level.INFO)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at the INFO level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void info(String msg, Throwable t) { + if (logger.isLoggable(Level.INFO)) { + log(SELF, Level.INFO, msg, t); + } + } + + /** + * Is this logger instance enabled for the WARNING level? + * + * @return True if this Logger is enabled for the WARNING level, false + * otherwise. + */ + public boolean isWarnEnabled() { + return logger.isLoggable(Level.WARNING); + } + + /** + * Log a message object at the WARNING level. + * + * @param msg + * - the message object to be logged + */ + public void warn(String msg) { + if (logger.isLoggable(Level.WARNING)) { + log(SELF, Level.WARNING, msg, null); + } + } + + /** + * Log a message at the WARNING level according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARNING level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void warn(String format, Object arg) { + if (logger.isLoggable(Level.WARNING)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at the WARNING level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARNING level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void warn(String format, Object arg1, Object arg2) { + if (logger.isLoggable(Level.WARNING)) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level WARNING according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARNING level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void warn(String format, Object... argArray) { + if (logger.isLoggable(Level.WARNING)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at the WARNING level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void warn(String msg, Throwable t) { + if (logger.isLoggable(Level.WARNING)) { + log(SELF, Level.WARNING, msg, t); + } + } + + /** + * Is this logger instance enabled for level SEVERE? + * + * @return True if this Logger is enabled for level SEVERE, false otherwise. + */ + public boolean isErrorEnabled() { + return logger.isLoggable(Level.SEVERE); + } + + /** + * Log a message object at the SEVERE level. + * + * @param msg + * - the message object to be logged + */ + public void error(String msg) { + if (logger.isLoggable(Level.SEVERE)) { + log(SELF, Level.SEVERE, msg, null); + } + } + + /** + * Log a message at the SEVERE level according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the SEVERE level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void error(String format, Object arg) { + if (logger.isLoggable(Level.SEVERE)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at the SEVERE level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the SEVERE level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void error(String format, Object arg1, Object arg2) { + if (logger.isLoggable(Level.SEVERE)) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level SEVERE according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the SEVERE level. + *

+ * + * @param format + * the format string + * @param arguments + * an array of arguments + */ + public void error(String format, Object... arguments) { + if (logger.isLoggable(Level.SEVERE)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at the SEVERE level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void error(String msg, Throwable t) { + if (logger.isLoggable(Level.SEVERE)) { + log(SELF, Level.SEVERE, msg, t); + } + } + + /** + * Log the message at the specified level with the specified throwable if any. + * This method creates a LogRecord and fills in caller date before calling + * this instance's JDK14 logger. + * + * See bug report #13 for more details. + * + * @param level + * @param msg + * @param t + */ + private void log(String callerFQCN, Level level, String msg, Throwable t) { + // millis and thread are filled by the constructor + LogRecord record = new LogRecord(level, msg); + record.setLoggerName(getName()); + record.setThrown(t); + // Note: parameters in record are not set because SLF4J only + // supports a single formatting style + fillCallerData(callerFQCN, record); + logger.log(record); + } + + static String SELF = JDK14LoggerAdapter.class.getName(); + static String SUPER = MarkerIgnoringBase.class.getName(); + + /** + * Fill in caller data if possible. + * + * @param record + * The record to update + */ + final private void fillCallerData(String callerFQCN, LogRecord record) { + StackTraceElement[] steArray = new Throwable().getStackTrace(); + + int selfIndex = -1; + for (int i = 0; i < steArray.length; i++) { + final String className = steArray[i].getClassName(); + if (className.equals(callerFQCN) || className.equals(SUPER)) { + selfIndex = i; + break; + } + } + + int found = -1; + for (int i = selfIndex + 1; i < steArray.length; i++) { + final String className = steArray[i].getClassName(); + if (!(className.equals(callerFQCN) || className.equals(SUPER))) { + found = i; + break; + } + } + + if (found != -1) { + StackTraceElement ste = steArray[found]; + // setting the class name has the side effect of setting + // the needToInferCaller variable to false. + record.setSourceClassName(ste.getClassName()); + record.setSourceMethodName(ste.getMethodName()); + } + } + + public void log(Marker marker, String callerFQCN, int level, String message, Object[] argArray, Throwable t) { + Level julLevel = slf4jLevelIntToJULLevel(level); + // the logger.isLoggable check avoids the unconditional + // construction of location data for disabled log + // statements. As of 2008-07-31, callers of this method + // do not perform this check. See also + // http://jira.qos.ch/browse/SLF4J-81 + if (logger.isLoggable(julLevel)) { + log(callerFQCN, julLevel, message, t); + } + } + + private Level slf4jLevelIntToJULLevel(int slf4jLevelInt) { + Level julLevel; + switch (slf4jLevelInt) { + case LocationAwareLogger.TRACE_INT: + julLevel = Level.FINEST; + break; + case LocationAwareLogger.DEBUG_INT: + julLevel = Level.FINE; + break; + case LocationAwareLogger.INFO_INT: + julLevel = Level.INFO; + break; + case LocationAwareLogger.WARN_INT: + julLevel = Level.WARNING; + break; + case LocationAwareLogger.ERROR_INT: + julLevel = Level.SEVERE; + break; + default: + throw new IllegalStateException("Level number " + slf4jLevelInt + " is not recognized."); + } + return julLevel; + } + + /** + * @since 1.7.15 + */ + public void log(LoggingEvent event) { + Level julLevel = slf4jLevelIntToJULLevel(event.getLevel().toInt()); + if (logger.isLoggable(julLevel)) { + LogRecord record = eventToRecord(event, julLevel); + logger.log(record); + } + } + + private LogRecord eventToRecord(LoggingEvent event, Level julLevel) { + String format = event.getMessage(); + Object[] arguments = event.getArgumentArray(); + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + if (ft.getThrowable() != null && event.getThrowable() != null) { + throw new IllegalArgumentException("both last element in argument array and last argument are of type Throwable"); + } + + Throwable t = event.getThrowable(); + if (ft.getThrowable() != null) { + t = ft.getThrowable(); + throw new IllegalStateException("fix above code"); + } + + LogRecord record = new LogRecord(julLevel, ft.getMessage()); + record.setLoggerName(event.getLoggerName()); + record.setMillis(event.getTimeStamp()); + record.setSourceClassName(EventConstants.NA_SUBST); + record.setSourceMethodName(EventConstants.NA_SUBST); + + record.setThrown(t); + return record; + } +} diff --git a/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerFactory.java b/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerFactory.java index 59c6755..e907652 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerFactory.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerFactory.java @@ -1,72 +1,72 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.Logger; -import org.slf4j.ILoggerFactory; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * JDK14LoggerFactory is an implementation of {@link ILoggerFactory} returning - * the appropriately named {@link JDK14LoggerAdapter} instance. - * - * @author Ceki Gülcü - */ -public class JDK14LoggerFactory implements ILoggerFactory { - - // key: name (String), value: a JDK14LoggerAdapter; - ConcurrentMap loggerMap; - - public JDK14LoggerFactory() { - loggerMap = new ConcurrentHashMap(); - // ensure jul initialization. see SLF4J-359 - // note that call to java.util.logging.LogManager.getLogManager() fails on the Google App Engine platform. See SLF4J-363 - java.util.logging.Logger.getLogger(""); - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) - */ - public Logger getLogger(String name) { - // the root logger is called "" in JUL - if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) { - name = ""; - } - - Logger slf4jLogger = loggerMap.get(name); - if (slf4jLogger != null) - return slf4jLogger; - else { - java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(name); - Logger newInstance = new JDK14LoggerAdapter(julLogger); - Logger oldInstance = loggerMap.putIfAbsent(name, newInstance); - return oldInstance == null ? newInstance : oldInstance; - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.Logger; +import org.slf4j.ILoggerFactory; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * JDK14LoggerFactory is an implementation of {@link ILoggerFactory} returning + * the appropriately named {@link JDK14LoggerAdapter} instance. + * + * @author Ceki Gülcü + */ +public class JDK14LoggerFactory implements ILoggerFactory { + + // key: name (String), value: a JDK14LoggerAdapter; + ConcurrentMap loggerMap; + + public JDK14LoggerFactory() { + loggerMap = new ConcurrentHashMap(); + // ensure jul initialization. see SLF4J-359 + // note that call to java.util.logging.LogManager.getLogManager() fails on the Google App Engine platform. See SLF4J-363 + java.util.logging.Logger.getLogger(""); + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) + */ + public Logger getLogger(String name) { + // the root logger is called "" in JUL + if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) { + name = ""; + } + + Logger slf4jLogger = loggerMap.get(name); + if (slf4jLogger != null) + return slf4jLogger; + else { + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(name); + Logger newInstance = new JDK14LoggerAdapter(julLogger); + Logger oldInstance = loggerMap.putIfAbsent(name, newInstance); + return oldInstance == null ? newInstance : oldInstance; + } + } +} diff --git a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index ebf8ae1..74c1893 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,80 +1,80 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - * - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - /** - * Declare the version of the SLF4J API this implementation is compiled against. - * The value of this field is modified with each major release. - */ - // to avoid constant folding by the compiler, this field must *not* be final - public static String REQUESTED_API_VERSION = "1.6.99"; // !final - - private static final String loggerFactoryClassStr = org.slf4j.impl.JDK14LoggerFactory.class.getName(); - - /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method - * should always be the same object - */ - private final ILoggerFactory loggerFactory; - - private StaticLoggerBinder() { - // Note: JCL gets substituted at build time by an appropriate Ant task - loggerFactory = new org.slf4j.impl.JDK14LoggerFactory(); - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + * + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is modified with each major release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; // !final + + private static final String loggerFactoryClassStr = org.slf4j.impl.JDK14LoggerFactory.class.getName(); + + /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method + * should always be the same object + */ + private final ILoggerFactory loggerFactory; + + private StaticLoggerBinder() { + // Note: JCL gets substituted at build time by an appropriate Ant task + loggerFactory = new org.slf4j.impl.JDK14LoggerFactory(); + } + + public ILoggerFactory getLoggerFactory() { + return loggerFactory; + } + + public String getLoggerFactoryClassStr() { + return loggerFactoryClassStr; + } +} diff --git a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMDCBinder.java index 0a1dcb4..865fee9 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,68 +1,68 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.helpers.BasicMDCAdapter; -import org.slf4j.spi.MDCAdapter; - -/** - * This implementation is bound to {@link BasicMDCAdapter}. - * - * @author Ceki Gülcü - */ -public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - - private StaticMDCBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMDCBinder singleton - * @since 1.7.14 - */ - public static final StaticMDCBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link BasicMDCAdapter}. - */ - public MDCAdapter getMDCA() { - // note that this method is invoked only from within the static initializer of - // the org.slf4j.MDC class. - return new BasicMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return BasicMDCAdapter.class.getName(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.helpers.BasicMDCAdapter; +import org.slf4j.spi.MDCAdapter; + +/** + * This implementation is bound to {@link BasicMDCAdapter}. + * + * @author Ceki Gülcü + */ +public class StaticMDCBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMDCBinder singleton + * @since 1.7.14 + */ + public static final StaticMDCBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link BasicMDCAdapter}. + */ + public MDCAdapter getMDCA() { + // note that this method is invoked only from within the static initializer of + // the org.slf4j.MDC class. + return new BasicMDCAdapter(); + } + + public String getMDCAdapterClassStr() { + return BasicMDCAdapter.class.getName(); + } +} diff --git a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMarkerBinder.java b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMarkerBinder.java index 21a48df..c37af78 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,77 +1,77 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMarkerBinder singleton - * @since 1.7.14 - */ - public static StaticMarkerBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMarkerBinder singleton + * @since 1.7.14 + */ + public static StaticMarkerBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + +} diff --git a/slf4j-jdk14/src/main/resources/META-INF/MANIFEST.MF b/slf4j-jdk14/src/main/resources/META-INF/MANIFEST.MF old file mode 100644 new file mode 100755 index f7334d1..05056de 100755 --- a/slf4j-jdk14/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-jdk14/src/main/resources/META-INF/MANIFEST.MF @@ -1,12 +1,12 @@ -Implementation-Title: slf4j-jdk14 -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.jdk14 -Bundle-Name: slf4j-jdk14 -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, - org.slf4j.spi;version=${parsedVersion.osgiVersion}, - org.slf4j.helpers;version=${parsedVersion.osgiVersion}, - org.slf4j.event;version=${parsedVersion.osgiVersion} +Implementation-Title: slf4j-jdk14 +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.jdk14 +Bundle-Name: slf4j-jdk14 +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, + org.slf4j.spi;version=${parsedVersion.osgiVersion}, + org.slf4j.helpers;version=${parsedVersion.osgiVersion}, + org.slf4j.event;version=${parsedVersion.osgiVersion} Fragment-Host: slf4j.apidiff --git a/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java b/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java old file mode 100644 new file mode 100755 index e3558c1..3db5936 100755 --- a/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java @@ -1,203 +1,203 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - */ -public class InvocationTest { - - Level oldLevel; - java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); - - ListHandler listHandler = new ListHandler(); - - @Before - public void setUp() throws Exception { - oldLevel = root.getLevel(); - root.setLevel(Level.FINE); - // removeAllHandlers(root); - root.addHandler(listHandler); - } - - @After - public void tearDown() throws Exception { - root.setLevel(oldLevel); - removeListHandlers(root); - } - - @Test - public void test1() { - Logger logger = LoggerFactory.getLogger("test1"); - logger.debug("Hello world."); - assertLogMessage("Hello world.", 0); - } - - @Test - public void verifyMessageFormatting() { - Integer i1 = new Integer(1); - Integer i2 = new Integer(2); - Integer i3 = new Integer(3); - Exception e = new Exception("This is a test exception."); - Logger logger = LoggerFactory.getLogger("test2"); - - int index = 0; - logger.debug("Hello world"); - assertLogMessage("Hello world", index++); - - logger.debug("Hello world {}", i1); - assertLogMessage("Hello world " + i1, index++); - - logger.debug("val={} val={}", i1, i2); - assertLogMessage("val=1 val=2", index++); - - logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); - assertLogMessage("val=1 val=2 val=3", index++); - - logger.debug("Hello world 2", e); - assertLogMessage("Hello world 2", index); - assertException(e.getClass(), index++); - logger.info("Hello world 2."); - - logger.warn("Hello world 3."); - logger.warn("Hello world 3", e); - - logger.error("Hello world 4."); - logger.error("Hello world {}", new Integer(3)); - logger.error("Hello world 4.", e); - } - - @Test - public void testNull() { - Logger logger = LoggerFactory.getLogger("testNull"); - logger.debug(null); - logger.info(null); - logger.warn(null); - logger.error(null); - - Exception e = new Exception("This is a test exception."); - logger.debug(null, e); - logger.info(null, e); - logger.warn(null, e); - logger.error(null, e); - } - - @Test - public void testMarker() { - Logger logger = LoggerFactory.getLogger("testMarker"); - Marker blue = MarkerFactory.getMarker("BLUE"); - logger.debug(blue, "hello"); - logger.info(blue, "hello"); - logger.warn(blue, "hello"); - logger.error(blue, "hello"); - - logger.debug(blue, "hello {}", "world"); - logger.info(blue, "hello {}", "world"); - logger.warn(blue, "hello {}", "world"); - logger.error(blue, "hello {}", "world"); - - logger.debug(blue, "hello {} and {} ", "world", "universe"); - logger.info(blue, "hello {} and {} ", "world", "universe"); - logger.warn(blue, "hello {} and {} ", "world", "universe"); - logger.error(blue, "hello {} and {} ", "world", "universe"); - } - - @Test - public void testMDC() { - MDC.put("k", "v"); - assertNotNull(MDC.get("k")); - assertEquals("v", MDC.get("k")); - - MDC.remove("k"); - assertNull(MDC.get("k")); - - MDC.put("k1", "v1"); - assertEquals("v1", MDC.get("k1")); - MDC.clear(); - assertNull(MDC.get("k1")); - - try { - MDC.put(null, "x"); - fail("null keys are invalid"); - } catch (IllegalArgumentException e) { - } - } - - private void assertLogMessage(String expected, int index) { - LogRecord logRecord = listHandler.recordList.get(index); - Assert.assertNotNull(logRecord); - assertEquals(expected, logRecord.getMessage()); - } - - private void assertException(Class exceptionType, int index) { - LogRecord logRecord = listHandler.recordList.get(index); - Assert.assertNotNull(logRecord); - assertEquals(exceptionType, logRecord.getThrown().getClass()); - } - - void removeListHandlers(java.util.logging.Logger logger) { - Handler[] handlers = logger.getHandlers(); - for (Handler h : handlers) { - if (h instanceof ListHandler) - logger.removeHandler(h); - } - } - - static private class ListHandler extends java.util.logging.Handler { - - List recordList = new ArrayList(); - - @Override - public void publish(LogRecord record) { - recordList.add(record); - } - - @Override - public void flush() { - } - - @Override - public void close() throws SecurityException { - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * Test whether invoking the SLF4J API causes problems or not. + * + * @author Ceki Gulcu + */ +public class InvocationTest { + + Level oldLevel; + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); + + ListHandler listHandler = new ListHandler(); + + @Before + public void setUp() throws Exception { + oldLevel = root.getLevel(); + root.setLevel(Level.FINE); + // removeAllHandlers(root); + root.addHandler(listHandler); + } + + @After + public void tearDown() throws Exception { + root.setLevel(oldLevel); + removeListHandlers(root); + } + + @Test + public void test1() { + Logger logger = LoggerFactory.getLogger("test1"); + logger.debug("Hello world."); + assertLogMessage("Hello world.", 0); + } + + @Test + public void verifyMessageFormatting() { + Integer i1 = new Integer(1); + Integer i2 = new Integer(2); + Integer i3 = new Integer(3); + Exception e = new Exception("This is a test exception."); + Logger logger = LoggerFactory.getLogger("test2"); + + int index = 0; + logger.debug("Hello world"); + assertLogMessage("Hello world", index++); + + logger.debug("Hello world {}", i1); + assertLogMessage("Hello world " + i1, index++); + + logger.debug("val={} val={}", i1, i2); + assertLogMessage("val=1 val=2", index++); + + logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); + assertLogMessage("val=1 val=2 val=3", index++); + + logger.debug("Hello world 2", e); + assertLogMessage("Hello world 2", index); + assertException(e.getClass(), index++); + logger.info("Hello world 2."); + + logger.warn("Hello world 3."); + logger.warn("Hello world 3", e); + + logger.error("Hello world 4."); + logger.error("Hello world {}", new Integer(3)); + logger.error("Hello world 4.", e); + } + + @Test + public void testNull() { + Logger logger = LoggerFactory.getLogger("testNull"); + logger.debug(null); + logger.info(null); + logger.warn(null); + logger.error(null); + + Exception e = new Exception("This is a test exception."); + logger.debug(null, e); + logger.info(null, e); + logger.warn(null, e); + logger.error(null, e); + } + + @Test + public void testMarker() { + Logger logger = LoggerFactory.getLogger("testMarker"); + Marker blue = MarkerFactory.getMarker("BLUE"); + logger.debug(blue, "hello"); + logger.info(blue, "hello"); + logger.warn(blue, "hello"); + logger.error(blue, "hello"); + + logger.debug(blue, "hello {}", "world"); + logger.info(blue, "hello {}", "world"); + logger.warn(blue, "hello {}", "world"); + logger.error(blue, "hello {}", "world"); + + logger.debug(blue, "hello {} and {} ", "world", "universe"); + logger.info(blue, "hello {} and {} ", "world", "universe"); + logger.warn(blue, "hello {} and {} ", "world", "universe"); + logger.error(blue, "hello {} and {} ", "world", "universe"); + } + + @Test + public void testMDC() { + MDC.put("k", "v"); + assertNotNull(MDC.get("k")); + assertEquals("v", MDC.get("k")); + + MDC.remove("k"); + assertNull(MDC.get("k")); + + MDC.put("k1", "v1"); + assertEquals("v1", MDC.get("k1")); + MDC.clear(); + assertNull(MDC.get("k1")); + + try { + MDC.put(null, "x"); + fail("null keys are invalid"); + } catch (IllegalArgumentException e) { + } + } + + private void assertLogMessage(String expected, int index) { + LogRecord logRecord = listHandler.recordList.get(index); + Assert.assertNotNull(logRecord); + assertEquals(expected, logRecord.getMessage()); + } + + private void assertException(Class exceptionType, int index) { + LogRecord logRecord = listHandler.recordList.get(index); + Assert.assertNotNull(logRecord); + assertEquals(exceptionType, logRecord.getThrown().getClass()); + } + + void removeListHandlers(java.util.logging.Logger logger) { + Handler[] handlers = logger.getHandlers(); + for (Handler h : handlers) { + if (h instanceof ListHandler) + logger.removeHandler(h); + } + } + + static private class ListHandler extends java.util.logging.Handler { + + List recordList = new ArrayList(); + + @Override + public void publish(LogRecord record) { + recordList.add(record); + } + + @Override + public void flush() { + } + + @Override + public void close() throws SecurityException { + } + } +} diff --git a/slf4j-jdk14/src/test/java/org/slf4j/LoggerFactoryFriend.java b/slf4j-jdk14/src/test/java/org/slf4j/LoggerFactoryFriend.java old file mode 100644 new file mode 100755 index edf5fcf..4398d3b 100755 --- a/slf4j-jdk14/src/test/java/org/slf4j/LoggerFactoryFriend.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/LoggerFactoryFriend.java @@ -1,7 +1,7 @@ -package org.slf4j; - -public class LoggerFactoryFriend { - static public void reset() { - LoggerFactory.reset(); - } -} +package org.slf4j; + +public class LoggerFactoryFriend { + static public void reset() { + LoggerFactory.reset(); + } +} diff --git a/slf4j-jdk14/src/test/java/org/slf4j/helpers/CountingHandler.java b/slf4j-jdk14/src/test/java/org/slf4j/helpers/CountingHandler.java index 33c36b9..7524b87 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/helpers/CountingHandler.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/helpers/CountingHandler.java @@ -1,24 +1,24 @@ -package org.slf4j.helpers; - -import java.util.concurrent.atomic.AtomicLong; -import java.util.logging.Handler; -import java.util.logging.LogRecord; - -public class CountingHandler extends Handler { - - final AtomicLong eventCount = new AtomicLong(0); - - @Override - public void publish(LogRecord record) { - eventCount.getAndIncrement(); - } - - @Override - public void flush() { - } - - @Override - public void close() throws SecurityException { - } - -} +package org.slf4j.helpers; + +import java.util.concurrent.atomic.AtomicLong; +import java.util.logging.Handler; +import java.util.logging.LogRecord; + +public class CountingHandler extends Handler { + + final AtomicLong eventCount = new AtomicLong(0); + + @Override + public void publish(LogRecord record) { + eventCount.getAndIncrement(); + } + + @Override + public void flush() { + } + + @Override + public void close() throws SecurityException { + } + +} diff --git a/slf4j-jdk14/src/test/java/org/slf4j/helpers/JDK14MultithreadedInitializationTest.java b/slf4j-jdk14/src/test/java/org/slf4j/helpers/JDK14MultithreadedInitializationTest.java index cbcbcf5..6582a76 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/helpers/JDK14MultithreadedInitializationTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/helpers/JDK14MultithreadedInitializationTest.java @@ -1,76 +1,76 @@ -/** - * Copyright (c) 2004-2016 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import static org.junit.Assert.fail; - -import java.util.logging.Handler; - -import org.junit.After; -import org.junit.Before; - -public class JDK14MultithreadedInitializationTest extends MultithreadedInitializationTest { - - java.util.logging.Logger julRootLogger = java.util.logging.Logger.getLogger(""); - java.util.logging.Logger julOrgLogger = java.util.logging.Logger.getLogger("org"); - - @Before - public void addRecordingHandler() { - System.out.println("THREAD_COUNT=" + THREAD_COUNT); - removeAllHandlers(julRootLogger); - removeAllHandlers(julOrgLogger); - julOrgLogger.addHandler(new CountingHandler()); - } - - private void removeAllHandlers(java.util.logging.Logger logger) { - Handler[] handlers = logger.getHandlers(); - for (int i = 0; i < handlers.length; i++) { - logger.removeHandler(handlers[i]); - } - } - - @After - public void tearDown() throws Exception { - removeAllHandlers(julOrgLogger); - } - - protected long getRecordedEventCount() { - CountingHandler ra = findRecordingHandler(); - if (ra == null) { - fail("failed to fing RecordingHandler"); - } - return ra.eventCount.get(); - } - - private CountingHandler findRecordingHandler() { - Handler[] handlers = julOrgLogger.getHandlers(); - for (Handler h : handlers) { - if (h instanceof CountingHandler) - return (CountingHandler) h; - } - return null; - } - -} +/** + * Copyright (c) 2004-2016 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import static org.junit.Assert.fail; + +import java.util.logging.Handler; + +import org.junit.After; +import org.junit.Before; + +public class JDK14MultithreadedInitializationTest extends MultithreadedInitializationTest { + + java.util.logging.Logger julRootLogger = java.util.logging.Logger.getLogger(""); + java.util.logging.Logger julOrgLogger = java.util.logging.Logger.getLogger("org"); + + @Before + public void addRecordingHandler() { + System.out.println("THREAD_COUNT=" + THREAD_COUNT); + removeAllHandlers(julRootLogger); + removeAllHandlers(julOrgLogger); + julOrgLogger.addHandler(new CountingHandler()); + } + + private void removeAllHandlers(java.util.logging.Logger logger) { + Handler[] handlers = logger.getHandlers(); + for (int i = 0; i < handlers.length; i++) { + logger.removeHandler(handlers[i]); + } + } + + @After + public void tearDown() throws Exception { + removeAllHandlers(julOrgLogger); + } + + protected long getRecordedEventCount() { + CountingHandler ra = findRecordingHandler(); + if (ra == null) { + fail("failed to fing RecordingHandler"); + } + return ra.eventCount.get(); + } + + private CountingHandler findRecordingHandler() { + Handler[] handlers = julOrgLogger.getHandlers(); + for (Handler h : handlers) { + if (h instanceof CountingHandler) + return (CountingHandler) h; + } + return null; + } + +} diff --git a/slf4j-jdk14/src/test/java/org/slf4j/impl/JDK14AdapterLoggerNameTest.java b/slf4j-jdk14/src/test/java/org/slf4j/impl/JDK14AdapterLoggerNameTest.java index 4e5273b..118f5f8 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/impl/JDK14AdapterLoggerNameTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/impl/JDK14AdapterLoggerNameTest.java @@ -1,106 +1,106 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import static org.junit.Assert.assertNotNull; - -import java.util.Random; -import java.util.logging.Handler; -import java.util.logging.LogRecord; -import java.util.logging.Logger; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class JDK14AdapterLoggerNameTest { - private MockHandler mockHandler; - static Random random = new Random(System.currentTimeMillis()); - long diff = random.nextInt(10000); - String loggerName = "JDK14AdapterLoggerNameTest"+diff; - - Logger logger = Logger.getLogger(loggerName); - - @Before - public void setUp() throws Exception { - Logger logger = Logger.getLogger(loggerName); - addMockHandler(logger); - } - - - - @After - public void tearDown() throws Exception { - removeHandlers(Logger.getLogger(loggerName)); - } - - @Test - public void testLoggerNameUsingJdkLogging() throws Exception { - logger.info("test message"); - assertCorrectLoggerName(); - } - - @Test - public void testLoggerNameUsingSlf4j() throws Exception { - JDK14LoggerFactory factory = new JDK14LoggerFactory(); - org.slf4j.Logger logger = factory.getLogger(loggerName); - logger.info("test message"); - assertCorrectLoggerName(); - } - - private void addMockHandler(Logger logger) { - mockHandler = new MockHandler(); - removeHandlers(logger); - logger.addHandler(mockHandler); - } - - private void removeHandlers(Logger logger) { - logger.setUseParentHandlers(false); - Handler[] handlers = logger.getHandlers(); - for (int i = 0; i < handlers.length; i++) { - logger.removeHandler(handlers[i]); - } - } - - private void assertCorrectLoggerName() { - assertNotNull("no log record", mockHandler.record); - assertNotNull("missing logger name", mockHandler.record.getLoggerName()); - } - - private class MockHandler extends java.util.logging.Handler { - public LogRecord record; - - public void close() throws SecurityException { - } - - public void flush() { - } - - public void publish(LogRecord record) { - this.record = record; - } - - } +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import static org.junit.Assert.assertNotNull; + +import java.util.Random; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class JDK14AdapterLoggerNameTest { + private MockHandler mockHandler; + static Random random = new Random(System.currentTimeMillis()); + long diff = random.nextInt(10000); + String loggerName = "JDK14AdapterLoggerNameTest"+diff; + + Logger logger = Logger.getLogger(loggerName); + + @Before + public void setUp() throws Exception { + Logger logger = Logger.getLogger(loggerName); + addMockHandler(logger); + } + + + + @After + public void tearDown() throws Exception { + removeHandlers(Logger.getLogger(loggerName)); + } + + @Test + public void testLoggerNameUsingJdkLogging() throws Exception { + logger.info("test message"); + assertCorrectLoggerName(); + } + + @Test + public void testLoggerNameUsingSlf4j() throws Exception { + JDK14LoggerFactory factory = new JDK14LoggerFactory(); + org.slf4j.Logger logger = factory.getLogger(loggerName); + logger.info("test message"); + assertCorrectLoggerName(); + } + + private void addMockHandler(Logger logger) { + mockHandler = new MockHandler(); + removeHandlers(logger); + logger.addHandler(mockHandler); + } + + private void removeHandlers(Logger logger) { + logger.setUseParentHandlers(false); + Handler[] handlers = logger.getHandlers(); + for (int i = 0; i < handlers.length; i++) { + logger.removeHandler(handlers[i]); + } + } + + private void assertCorrectLoggerName() { + assertNotNull("no log record", mockHandler.record); + assertNotNull("missing logger name", mockHandler.record.getLoggerName()); + } + + private class MockHandler extends java.util.logging.Handler { + public LogRecord record; + + public void close() throws SecurityException { + } + + public void flush() { + } + + public void publish(LogRecord record) { + this.record = record; + } + + } }diff --git a/slf4j-jdk14/src/test/java/org/slf4j/impl/PerfTest.java b/slf4j-jdk14/src/test/java/org/slf4j/impl/PerfTest.java index 9ff72d5..8aa4a31 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/impl/PerfTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/impl/PerfTest.java @@ -1,66 +1,66 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.helpers.BogoPerf; - -@Ignore -public class PerfTest { - - static long REFERENCE_BIPS = 9000; - - @Test - public void issue63() { - - int LEN = 1000 * 1000 * 10; - debugLoop(LEN); // warm up - double avg = debugLoop(LEN); - long referencePerf = 93; - BogoPerf.assertDuration(avg, referencePerf, REFERENCE_BIPS); - - // when the code is guarded by a logger.isLoggable condition, - // duration is about 16 *micro*seconds for 1000 iterations - // when it is not guarded the figure is 90 milliseconds, - // i.e. a ration of 1 to 5000 - } - - double debugLoop(int len) { - Logger logger = LoggerFactory.getLogger(PerfTest.class); - long start = System.currentTimeMillis(); - for (int i = 0; i < len; i++) { - logger.debug("hello"); - } - - long end = System.currentTimeMillis(); - - long duration = end - start; - return duration; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.helpers.BogoPerf; + +@Ignore +public class PerfTest { + + static long REFERENCE_BIPS = 9000; + + @Test + public void issue63() { + + int LEN = 1000 * 1000 * 10; + debugLoop(LEN); // warm up + double avg = debugLoop(LEN); + long referencePerf = 93; + BogoPerf.assertDuration(avg, referencePerf, REFERENCE_BIPS); + + // when the code is guarded by a logger.isLoggable condition, + // duration is about 16 *micro*seconds for 1000 iterations + // when it is not guarded the figure is 90 milliseconds, + // i.e. a ration of 1 to 5000 + } + + double debugLoop(int len) { + Logger logger = LoggerFactory.getLogger(PerfTest.class); + long start = System.currentTimeMillis(); + for (int i = 0; i < len; i++) { + logger.debug("hello"); + } + + long end = System.currentTimeMillis(); + + long duration = end - start; + return duration; + } + +} diff --git a/slf4j-jdk14/src/test/java/org/slf4j/issue/LoggerSerializationTest.java b/slf4j-jdk14/src/test/java/org/slf4j/issue/LoggerSerializationTest.java index a408b93..a324f20 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/issue/LoggerSerializationTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/issue/LoggerSerializationTest.java @@ -1,84 +1,84 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.issue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * See http://jira.qos.ch/browse/SLF4J-252 - * @author Thorbjorn Ravn Andersen - */ -public class LoggerSerializationTest { - - static class LoggerHolder implements Serializable { - private static final long serialVersionUID = 1L; - - private Logger log = LoggerFactory.getLogger(LoggerHolder.class); - - public String toString() { - return "log=" + getLog(); - } - - public Logger getLog() { - return log; - } - } - - @Test - public void testCanLoggerBeSerialized() throws IOException, ClassNotFoundException { - - LoggerHolder lh1 = new LoggerHolder(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject(lh1); - out.close(); - - lh1 = null; - - byte[] serializedLoggerHolder = baos.toByteArray(); - - InputStream is = new ByteArrayInputStream(serializedLoggerHolder); - ObjectInputStream in = new ObjectInputStream(is); - LoggerHolder lh2 = (LoggerHolder) in.readObject(); - - assertNotNull(lh2); - assertNotNull(lh2.getLog()); - lh2.getLog().info("You must see this message as a log message"); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.issue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * See http://jira.qos.ch/browse/SLF4J-252 + * @author Thorbjorn Ravn Andersen + */ +public class LoggerSerializationTest { + + static class LoggerHolder implements Serializable { + private static final long serialVersionUID = 1L; + + private Logger log = LoggerFactory.getLogger(LoggerHolder.class); + + public String toString() { + return "log=" + getLog(); + } + + public Logger getLog() { + return log; + } + } + + @Test + public void testCanLoggerBeSerialized() throws IOException, ClassNotFoundException { + + LoggerHolder lh1 = new LoggerHolder(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(baos); + out.writeObject(lh1); + out.close(); + + lh1 = null; + + byte[] serializedLoggerHolder = baos.toByteArray(); + + InputStream is = new ByteArrayInputStream(serializedLoggerHolder); + ObjectInputStream in = new ObjectInputStream(is); + LoggerHolder lh2 = (LoggerHolder) in.readObject(); + + assertNotNull(lh2); + assertNotNull(lh2.getLog()); + lh2.getLog().info("You must see this message as a log message"); + } + +} diff --git a/slf4j-log4j12/LICENSE.txt b/slf4j-log4j12/LICENSE.txt new file mode 100644 index 0000000..508a272 --- /dev/null +++ b/slf4j-log4j12/LICENSE.txt @@ -0,0 +1,24 @@ +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-log4j12/pom.xml b/slf4j-log4j12/pom.xml old file mode 100644 new file mode 100755 index 7d0657f..afdfc41 100755 --- a/slf4j-log4j12/pom.xml +++ b/slf4j-log4j12/pom.xml @@ -1,40 +1,41 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - slf4j-log4j12 - - jar - SLF4J LOG4J-12 Binding - SLF4J LOG4J-12 Binding - http://www.slf4j.org - - - - org.slf4j - slf4j-api - - - - log4j - log4j - - - - org.slf4j - slf4j-api - test-jar - ${project.version} - test - - - - \ No newline at end of file + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + slf4j-log4j12 + + jar + SLF4J LOG4J-12 Binding + SLF4J LOG4J-12 Binding + http://www.slf4j.org + + + + org.slf4j + slf4j-api + + + + log4j + log4j + + + + org.slf4j + slf4j-api + test-jar + ${project.version} + test + + + + + diff --git a/slf4j-log4j12/src/main/java/org/apache/log4j/MDCFriend.java b/slf4j-log4j12/src/main/java/org/apache/log4j/MDCFriend.java old file mode 100644 new file mode 100755 index f14daaf..3b36be7 100755 --- a/slf4j-log4j12/src/main/java/org/apache/log4j/MDCFriend.java +++ b/slf4j-log4j12/src/main/java/org/apache/log4j/MDCFriend.java @@ -1,33 +1,33 @@ -package org.apache.log4j; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -import org.apache.log4j.helpers.ThreadLocalMap; - -public class MDCFriend { - - public static void fixForJava9() { - if (MDC.mdc.tlm == null) { - MDC.mdc.tlm = new ThreadLocalMap(); - MDC.mdc.java1 = false; - setRemoveMethod(MDC.mdc); - } - - } - - private static void setRemoveMethod(MDC mdc) { - try { - Method removeMethod = ThreadLocal.class.getMethod("remove"); - Field removeMethodField = MDC.class.getDeclaredField("removeMethod"); - removeMethodField.setAccessible(true); - removeMethodField.set(mdc, removeMethod); - } catch (NoSuchMethodException e) { - } catch (SecurityException e) { - } catch (NoSuchFieldException e) { - } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { - } - - } -} +package org.apache.log4j; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import org.apache.log4j.helpers.ThreadLocalMap; + +public class MDCFriend { + + public static void fixForJava9() { + if (MDC.mdc.tlm == null) { + MDC.mdc.tlm = new ThreadLocalMap(); + MDC.mdc.java1 = false; + setRemoveMethod(MDC.mdc); + } + + } + + private static void setRemoveMethod(MDC mdc) { + try { + Method removeMethod = ThreadLocal.class.getMethod("remove"); + Field removeMethodField = MDC.class.getDeclaredField("removeMethod"); + removeMethodField.setAccessible(true); + removeMethodField.set(mdc, removeMethod); + } catch (NoSuchMethodException e) { + } catch (SecurityException e) { + } catch (NoSuchFieldException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalAccessException e) { + } + + } +} diff --git a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerAdapter.java b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerAdapter.java old file mode 100644 new file mode 100755 index ebd568e..6d65b80 100755 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerAdapter.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerAdapter.java @@ -1,635 +1,635 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import static org.slf4j.event.EventConstants.NA_SUBST; - -import java.io.Serializable; - -import org.apache.log4j.Level; -import org.apache.log4j.spi.LocationInfo; -import org.apache.log4j.spi.ThrowableInformation; -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.event.LoggingEvent; -import org.slf4j.helpers.FormattingTuple; -import org.slf4j.helpers.MarkerIgnoringBase; -import org.slf4j.helpers.MessageFormatter; -import org.slf4j.spi.LocationAwareLogger; - -/** - * A wrapper over {@link org.apache.log4j.Logger org.apache.log4j.Logger} in - * conforming to the {@link Logger} interface. - * - *

- * Note that the logging levels mentioned in this class refer to those defined - * in the - * org.apache.log4j.Level class. - * - *

- * The TRACE level was introduced in log4j version 1.2.12. In order to avoid - * crashing the host application, in the case the log4j version in use predates - * 1.2.12, the TRACE level will be mapped as DEBUG. See also SLF4J-59. - * - * @author Ceki Gülcü - */ -public final class Log4jLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger, Serializable { - - private static final long serialVersionUID = 6182834493563598289L; - - final transient org.apache.log4j.Logger logger; - - /** - * Following the pattern discussed in pages 162 through 168 of "The complete - * log4j manual". - */ - final static String FQCN = Log4jLoggerAdapter.class.getName(); - - // Does the log4j version in use recognize the TRACE level? - // The trace level was introduced in log4j 1.2.12. - final boolean traceCapable; - - // WARN: Log4jLoggerAdapter constructor should have only package access so - // that - // only Log4jLoggerFactory be able to create one. - Log4jLoggerAdapter(org.apache.log4j.Logger logger) { - this.logger = logger; - this.name = logger.getName(); - traceCapable = isTraceCapable(); - } - - private boolean isTraceCapable() { - try { - logger.isTraceEnabled(); - return true; - } catch (NoSuchMethodError e) { - return false; - } - } - - /** - * Is this logger instance enabled for the TRACE level? - * - * @return True if this Logger is enabled for level TRACE, false otherwise. - */ - public boolean isTraceEnabled() { - if (traceCapable) { - return logger.isTraceEnabled(); - } else { - return logger.isDebugEnabled(); - } - } - - /** - * Log a message object at level TRACE. - * - * @param msg - * - the message object to be logged - */ - public void trace(String msg) { - logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, null); - } - - /** - * Log a message at level TRACE according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for level TRACE. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void trace(String format, Object arg) { - if (isTraceEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg); - logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level TRACE according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the TRACE level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void trace(String format, Object arg1, Object arg2) { - if (isTraceEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level TRACE according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the TRACE level. - *

- * - * @param format - * the format string - * @param arguments - * an array of arguments - */ - public void trace(String format, Object... arguments) { - if (isTraceEnabled()) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at level TRACE with an accompanying message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void trace(String msg, Throwable t) { - logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, t); - } - - /** - * Is this logger instance enabled for the DEBUG level? - * - * @return True if this Logger is enabled for level DEBUG, false otherwise. - */ - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - /** - * Log a message object at level DEBUG. - * - * @param msg - * - the message object to be logged - */ - public void debug(String msg) { - logger.log(FQCN, Level.DEBUG, msg, null); - } - - /** - * Log a message at level DEBUG according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for level DEBUG. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void debug(String format, Object arg) { - if (logger.isDebugEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg); - logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level DEBUG according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the DEBUG level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void debug(String format, Object arg1, Object arg2) { - if (logger.isDebugEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level DEBUG according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the DEBUG level. - *

- * - * @param format - * the format string - * @param arguments an array of arguments - */ - public void debug(String format, Object... arguments) { - if (logger.isDebugEnabled()) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at level DEBUG with an accompanying message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void debug(String msg, Throwable t) { - logger.log(FQCN, Level.DEBUG, msg, t); - } - - /** - * Is this logger instance enabled for the INFO level? - * - * @return True if this Logger is enabled for the INFO level, false otherwise. - */ - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - /** - * Log a message object at the INFO level. - * - * @param msg - * - the message object to be logged - */ - public void info(String msg) { - logger.log(FQCN, Level.INFO, msg, null); - } - - /** - * Log a message at level INFO according to the specified format and argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void info(String format, Object arg) { - if (logger.isInfoEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg); - logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at the INFO level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void info(String format, Object arg1, Object arg2) { - if (logger.isInfoEnabled()) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level INFO according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the INFO level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void info(String format, Object... argArray) { - if (logger.isInfoEnabled()) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at the INFO level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void info(String msg, Throwable t) { - logger.log(FQCN, Level.INFO, msg, t); - } - - /** - * Is this logger instance enabled for the WARN level? - * - * @return True if this Logger is enabled for the WARN level, false otherwise. - */ - public boolean isWarnEnabled() { - return logger.isEnabledFor(Level.WARN); - } - - /** - * Log a message object at the WARN level. - * - * @param msg - * - the message object to be logged - */ - public void warn(String msg) { - logger.log(FQCN, Level.WARN, msg, null); - } - - /** - * Log a message at the WARN level according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARN level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void warn(String format, Object arg) { - if (logger.isEnabledFor(Level.WARN)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at the WARN level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARN level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void warn(String format, Object arg1, Object arg2) { - if (logger.isEnabledFor(Level.WARN)) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level WARN according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the WARN level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void warn(String format, Object... argArray) { - if (logger.isEnabledFor(Level.WARN)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at the WARN level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void warn(String msg, Throwable t) { - logger.log(FQCN, Level.WARN, msg, t); - } - - /** - * Is this logger instance enabled for level ERROR? - * - * @return True if this Logger is enabled for level ERROR, false otherwise. - */ - public boolean isErrorEnabled() { - return logger.isEnabledFor(Level.ERROR); - } - - /** - * Log a message object at the ERROR level. - * - * @param msg - * - the message object to be logged - */ - public void error(String msg) { - logger.log(FQCN, Level.ERROR, msg, null); - } - - /** - * Log a message at the ERROR level according to the specified format and - * argument. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the ERROR level. - *

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void error(String format, Object arg) { - if (logger.isEnabledFor(Level.ERROR)) { - FormattingTuple ft = MessageFormatter.format(format, arg); - logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at the ERROR level according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the ERROR level. - *

- * - * @param format - * the format string - * @param arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void error(String format, Object arg1, Object arg2) { - if (logger.isEnabledFor(Level.ERROR)) { - FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); - logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log a message at level ERROR according to the specified format and - * arguments. - * - *

- * This form avoids superfluous object creation when the logger is disabled - * for the ERROR level. - *

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void error(String format, Object... argArray) { - if (logger.isEnabledFor(Level.ERROR)) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); - } - } - - /** - * Log an exception (throwable) at the ERROR level with an accompanying - * message. - * - * @param msg - * the message accompanying the exception - * @param t - * the exception (throwable) to log - */ - public void error(String msg, Throwable t) { - logger.log(FQCN, Level.ERROR, msg, t); - } - - public void log(Marker marker, String callerFQCN, int level, String msg, Object[] argArray, Throwable t) { - Level log4jLevel = toLog4jLevel(level); - logger.log(callerFQCN, log4jLevel, msg, t); - } - - private Level toLog4jLevel(int level) { - Level log4jLevel; - switch (level) { - case LocationAwareLogger.TRACE_INT: - log4jLevel = traceCapable ? Level.TRACE : Level.DEBUG; - break; - case LocationAwareLogger.DEBUG_INT: - log4jLevel = Level.DEBUG; - break; - case LocationAwareLogger.INFO_INT: - log4jLevel = Level.INFO; - break; - case LocationAwareLogger.WARN_INT: - log4jLevel = Level.WARN; - break; - case LocationAwareLogger.ERROR_INT: - log4jLevel = Level.ERROR; - break; - default: - throw new IllegalStateException("Level number " + level + " is not recognized."); - } - return log4jLevel; - } - - public void log(LoggingEvent event) { - Level log4jLevel = toLog4jLevel(event.getLevel().toInt()); - if (!logger.isEnabledFor(log4jLevel)) - return; - - org.apache.log4j.spi.LoggingEvent log4jevent = toLog4jEvent(event, log4jLevel); - logger.callAppenders(log4jevent); - - } - - private org.apache.log4j.spi.LoggingEvent toLog4jEvent(LoggingEvent event, Level log4jLevel) { - - FormattingTuple ft = MessageFormatter.format(event.getMessage(), event.getArgumentArray(), event.getThrowable()); - - LocationInfo locationInfo = new LocationInfo(NA_SUBST, NA_SUBST, NA_SUBST, "0"); - - ThrowableInformation ti = null; - Throwable t = ft.getThrowable(); - if (t != null) - ti = new ThrowableInformation(t); - - org.apache.log4j.spi.LoggingEvent log4jEvent = new org.apache.log4j.spi.LoggingEvent(FQCN, logger, event.getTimeStamp(), log4jLevel, ft.getMessage(), - event.getThreadName(), ti, null, locationInfo, null); - - return log4jEvent; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import static org.slf4j.event.EventConstants.NA_SUBST; + +import java.io.Serializable; + +import org.apache.log4j.Level; +import org.apache.log4j.spi.LocationInfo; +import org.apache.log4j.spi.ThrowableInformation; +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.event.LoggingEvent; +import org.slf4j.helpers.FormattingTuple; +import org.slf4j.helpers.MarkerIgnoringBase; +import org.slf4j.helpers.MessageFormatter; +import org.slf4j.spi.LocationAwareLogger; + +/** + * A wrapper over {@link org.apache.log4j.Logger org.apache.log4j.Logger} in + * conforming to the {@link Logger} interface. + * + *

+ * Note that the logging levels mentioned in this class refer to those defined + * in the + * org.apache.log4j.Level class. + * + *

+ * The TRACE level was introduced in log4j version 1.2.12. In order to avoid + * crashing the host application, in the case the log4j version in use predates + * 1.2.12, the TRACE level will be mapped as DEBUG. See also SLF4J-59. + * + * @author Ceki Gülcü + */ +public final class Log4jLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger, Serializable { + + private static final long serialVersionUID = 6182834493563598289L; + + final transient org.apache.log4j.Logger logger; + + /** + * Following the pattern discussed in pages 162 through 168 of "The complete + * log4j manual". + */ + final static String FQCN = Log4jLoggerAdapter.class.getName(); + + // Does the log4j version in use recognize the TRACE level? + // The trace level was introduced in log4j 1.2.12. + final boolean traceCapable; + + // WARN: Log4jLoggerAdapter constructor should have only package access so + // that + // only Log4jLoggerFactory be able to create one. + Log4jLoggerAdapter(org.apache.log4j.Logger logger) { + this.logger = logger; + this.name = logger.getName(); + traceCapable = isTraceCapable(); + } + + private boolean isTraceCapable() { + try { + logger.isTraceEnabled(); + return true; + } catch (NoSuchMethodError e) { + return false; + } + } + + /** + * Is this logger instance enabled for the TRACE level? + * + * @return True if this Logger is enabled for level TRACE, false otherwise. + */ + public boolean isTraceEnabled() { + if (traceCapable) { + return logger.isTraceEnabled(); + } else { + return logger.isDebugEnabled(); + } + } + + /** + * Log a message object at level TRACE. + * + * @param msg + * - the message object to be logged + */ + public void trace(String msg) { + logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, null); + } + + /** + * Log a message at level TRACE according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for level TRACE. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void trace(String format, Object arg) { + if (isTraceEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg); + logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level TRACE according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the TRACE level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void trace(String format, Object arg1, Object arg2) { + if (isTraceEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level TRACE according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the TRACE level. + *

+ * + * @param format + * the format string + * @param arguments + * an array of arguments + */ + public void trace(String format, Object... arguments) { + if (isTraceEnabled()) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at level TRACE with an accompanying message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void trace(String msg, Throwable t) { + logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msg, t); + } + + /** + * Is this logger instance enabled for the DEBUG level? + * + * @return True if this Logger is enabled for level DEBUG, false otherwise. + */ + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + /** + * Log a message object at level DEBUG. + * + * @param msg + * - the message object to be logged + */ + public void debug(String msg) { + logger.log(FQCN, Level.DEBUG, msg, null); + } + + /** + * Log a message at level DEBUG according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for level DEBUG. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void debug(String format, Object arg) { + if (logger.isDebugEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg); + logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level DEBUG according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the DEBUG level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void debug(String format, Object arg1, Object arg2) { + if (logger.isDebugEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level DEBUG according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the DEBUG level. + *

+ * + * @param format + * the format string + * @param arguments an array of arguments + */ + public void debug(String format, Object... arguments) { + if (logger.isDebugEnabled()) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + logger.log(FQCN, Level.DEBUG, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at level DEBUG with an accompanying message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void debug(String msg, Throwable t) { + logger.log(FQCN, Level.DEBUG, msg, t); + } + + /** + * Is this logger instance enabled for the INFO level? + * + * @return True if this Logger is enabled for the INFO level, false otherwise. + */ + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + /** + * Log a message object at the INFO level. + * + * @param msg + * - the message object to be logged + */ + public void info(String msg) { + logger.log(FQCN, Level.INFO, msg, null); + } + + /** + * Log a message at level INFO according to the specified format and argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void info(String format, Object arg) { + if (logger.isInfoEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg); + logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at the INFO level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void info(String format, Object arg1, Object arg2) { + if (logger.isInfoEnabled()) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level INFO according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void info(String format, Object... argArray) { + if (logger.isInfoEnabled()) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + logger.log(FQCN, Level.INFO, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at the INFO level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void info(String msg, Throwable t) { + logger.log(FQCN, Level.INFO, msg, t); + } + + /** + * Is this logger instance enabled for the WARN level? + * + * @return True if this Logger is enabled for the WARN level, false otherwise. + */ + public boolean isWarnEnabled() { + return logger.isEnabledFor(Level.WARN); + } + + /** + * Log a message object at the WARN level. + * + * @param msg + * - the message object to be logged + */ + public void warn(String msg) { + logger.log(FQCN, Level.WARN, msg, null); + } + + /** + * Log a message at the WARN level according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARN level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void warn(String format, Object arg) { + if (logger.isEnabledFor(Level.WARN)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at the WARN level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARN level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void warn(String format, Object arg1, Object arg2) { + if (logger.isEnabledFor(Level.WARN)) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level WARN according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARN level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void warn(String format, Object... argArray) { + if (logger.isEnabledFor(Level.WARN)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + logger.log(FQCN, Level.WARN, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at the WARN level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void warn(String msg, Throwable t) { + logger.log(FQCN, Level.WARN, msg, t); + } + + /** + * Is this logger instance enabled for level ERROR? + * + * @return True if this Logger is enabled for level ERROR, false otherwise. + */ + public boolean isErrorEnabled() { + return logger.isEnabledFor(Level.ERROR); + } + + /** + * Log a message object at the ERROR level. + * + * @param msg + * - the message object to be logged + */ + public void error(String msg) { + logger.log(FQCN, Level.ERROR, msg, null); + } + + /** + * Log a message at the ERROR level according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the ERROR level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void error(String format, Object arg) { + if (logger.isEnabledFor(Level.ERROR)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at the ERROR level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the ERROR level. + *

+ * + * @param format + * the format string + * @param arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void error(String format, Object arg1, Object arg2) { + if (logger.isEnabledFor(Level.ERROR)) { + FormattingTuple ft = MessageFormatter.format(format, arg1, arg2); + logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level ERROR according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the ERROR level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void error(String format, Object... argArray) { + if (logger.isEnabledFor(Level.ERROR)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + logger.log(FQCN, Level.ERROR, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at the ERROR level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + public void error(String msg, Throwable t) { + logger.log(FQCN, Level.ERROR, msg, t); + } + + public void log(Marker marker, String callerFQCN, int level, String msg, Object[] argArray, Throwable t) { + Level log4jLevel = toLog4jLevel(level); + logger.log(callerFQCN, log4jLevel, msg, t); + } + + private Level toLog4jLevel(int level) { + Level log4jLevel; + switch (level) { + case LocationAwareLogger.TRACE_INT: + log4jLevel = traceCapable ? Level.TRACE : Level.DEBUG; + break; + case LocationAwareLogger.DEBUG_INT: + log4jLevel = Level.DEBUG; + break; + case LocationAwareLogger.INFO_INT: + log4jLevel = Level.INFO; + break; + case LocationAwareLogger.WARN_INT: + log4jLevel = Level.WARN; + break; + case LocationAwareLogger.ERROR_INT: + log4jLevel = Level.ERROR; + break; + default: + throw new IllegalStateException("Level number " + level + " is not recognized."); + } + return log4jLevel; + } + + public void log(LoggingEvent event) { + Level log4jLevel = toLog4jLevel(event.getLevel().toInt()); + if (!logger.isEnabledFor(log4jLevel)) + return; + + org.apache.log4j.spi.LoggingEvent log4jevent = toLog4jEvent(event, log4jLevel); + logger.callAppenders(log4jevent); + + } + + private org.apache.log4j.spi.LoggingEvent toLog4jEvent(LoggingEvent event, Level log4jLevel) { + + FormattingTuple ft = MessageFormatter.format(event.getMessage(), event.getArgumentArray(), event.getThrowable()); + + LocationInfo locationInfo = new LocationInfo(NA_SUBST, NA_SUBST, NA_SUBST, "0"); + + ThrowableInformation ti = null; + Throwable t = ft.getThrowable(); + if (t != null) + ti = new ThrowableInformation(t); + + org.apache.log4j.spi.LoggingEvent log4jEvent = new org.apache.log4j.spi.LoggingEvent(FQCN, logger, event.getTimeStamp(), log4jLevel, ft.getMessage(), + event.getThreadName(), ti, null, locationInfo, null); + + return log4jEvent; + } + +} diff --git a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerFactory.java b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerFactory.java index 6327965..f020d10 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerFactory.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerFactory.java @@ -1,90 +1,90 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.apache.log4j.LogManager; -import org.slf4j.ILoggerFactory; -import org.slf4j.Logger; -import org.slf4j.helpers.Util; - -/** - * Log4jLoggerFactory is an implementation of {@link ILoggerFactory} returning - * the appropriate named {@link Log4jLoggerAdapter} instance. - * - * @author Ceki Gülcü - */ -public class Log4jLoggerFactory implements ILoggerFactory { - - private static final String LOG4J_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#log4jDelegationLoop"; - - // check for delegation loops - static { - try { - Class.forName("org.apache.log4j.Log4jLoggerFactory"); - String part1 = "Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path, preempting StackOverflowError. "; - String part2 = "See also " + LOG4J_DELEGATION_LOOP_URL + " for more details."; - - Util.report(part1); - Util.report(part2); - throw new IllegalStateException(part1 + part2); - } catch (ClassNotFoundException e) { - // this is the good case - } - } - - // key: name (String), value: a Log4jLoggerAdapter; - ConcurrentMap loggerMap; - - public Log4jLoggerFactory() { - loggerMap = new ConcurrentHashMap(); - // force log4j to initialize - org.apache.log4j.LogManager.getRootLogger(); - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) - */ - public Logger getLogger(String name) { - Logger slf4jLogger = loggerMap.get(name); - if (slf4jLogger != null) { - return slf4jLogger; - } else { - org.apache.log4j.Logger log4jLogger; - if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) - log4jLogger = LogManager.getRootLogger(); - else - log4jLogger = LogManager.getLogger(name); - - Logger newInstance = new Log4jLoggerAdapter(log4jLogger); - Logger oldInstance = loggerMap.putIfAbsent(name, newInstance); - return oldInstance == null ? newInstance : oldInstance; - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.apache.log4j.LogManager; +import org.slf4j.ILoggerFactory; +import org.slf4j.Logger; +import org.slf4j.helpers.Util; + +/** + * Log4jLoggerFactory is an implementation of {@link ILoggerFactory} returning + * the appropriate named {@link Log4jLoggerAdapter} instance. + * + * @author Ceki Gülcü + */ +public class Log4jLoggerFactory implements ILoggerFactory { + + private static final String LOG4J_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#log4jDelegationLoop"; + + // check for delegation loops + static { + try { + Class.forName("org.apache.log4j.Log4jLoggerFactory"); + String part1 = "Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path, preempting StackOverflowError. "; + String part2 = "See also " + LOG4J_DELEGATION_LOOP_URL + " for more details."; + + Util.report(part1); + Util.report(part2); + throw new IllegalStateException(part1 + part2); + } catch (ClassNotFoundException e) { + // this is the good case + } + } + + // key: name (String), value: a Log4jLoggerAdapter; + ConcurrentMap loggerMap; + + public Log4jLoggerFactory() { + loggerMap = new ConcurrentHashMap(); + // force log4j to initialize + org.apache.log4j.LogManager.getRootLogger(); + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) + */ + public Logger getLogger(String name) { + Logger slf4jLogger = loggerMap.get(name); + if (slf4jLogger != null) { + return slf4jLogger; + } else { + org.apache.log4j.Logger log4jLogger; + if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) + log4jLogger = LogManager.getRootLogger(); + else + log4jLogger = LogManager.getLogger(name); + + Logger newInstance = new Log4jLoggerAdapter(log4jLogger); + Logger oldInstance = loggerMap.putIfAbsent(name, newInstance); + return oldInstance == null ? newInstance : oldInstance; + } + } +} diff --git a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jMDCAdapter.java b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jMDCAdapter.java index 36c0bcc..43afe0d 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jMDCAdapter.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jMDCAdapter.java @@ -1,98 +1,98 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.apache.log4j.MDCFriend; -import org.slf4j.spi.MDCAdapter; - -public class Log4jMDCAdapter implements MDCAdapter { - - static { - if (VersionUtil.getJavaMajorVersion() >= 9) { - MDCFriend.fixForJava9(); - } - } - - public void clear() { - @SuppressWarnings("rawtypes") - Map map = org.apache.log4j.MDC.getContext(); - if (map != null) { - map.clear(); - } - } - - public String get(String key) { - return (String) org.apache.log4j.MDC.get(key); - } - - /** - * Put a context value (the val parameter) as identified with - * the key parameter into the current thread's context map. The - * key parameter cannot be null. Log4j does not - * support null for the val parameter. - * - *

- * This method delegates all work to log4j's MDC. - * - * @throws IllegalArgumentException - * in case the "key" or "val" parameter is null - */ - public void put(String key, String val) { - org.apache.log4j.MDC.put(key, val); - } - - public void remove(String key) { - org.apache.log4j.MDC.remove(key); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Map getCopyOfContextMap() { - Map old = org.apache.log4j.MDC.getContext(); - if (old != null) { - return new HashMap(old); - } else { - return null; - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void setContextMap(Map contextMap) { - Map old = org.apache.log4j.MDC.getContext(); - if (old == null) { - Iterator entrySetIterator = contextMap.entrySet().iterator(); - while (entrySetIterator.hasNext()) { - Map.Entry mapEntry = (Map.Entry) entrySetIterator.next(); - org.apache.log4j.MDC.put((String) mapEntry.getKey(), mapEntry.getValue()); - } - } else { - old.clear(); - old.putAll(contextMap); - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.apache.log4j.MDCFriend; +import org.slf4j.spi.MDCAdapter; + +public class Log4jMDCAdapter implements MDCAdapter { + + static { + if (VersionUtil.getJavaMajorVersion() >= 9) { + MDCFriend.fixForJava9(); + } + } + + public void clear() { + @SuppressWarnings("rawtypes") + Map map = org.apache.log4j.MDC.getContext(); + if (map != null) { + map.clear(); + } + } + + public String get(String key) { + return (String) org.apache.log4j.MDC.get(key); + } + + /** + * Put a context value (the val parameter) as identified with + * the key parameter into the current thread's context map. The + * key parameter cannot be null. Log4j does not + * support null for the val parameter. + * + *

+ * This method delegates all work to log4j's MDC. + * + * @throws IllegalArgumentException + * in case the "key" or "val" parameter is null + */ + public void put(String key, String val) { + org.apache.log4j.MDC.put(key, val); + } + + public void remove(String key) { + org.apache.log4j.MDC.remove(key); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Map getCopyOfContextMap() { + Map old = org.apache.log4j.MDC.getContext(); + if (old != null) { + return new HashMap(old); + } else { + return null; + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void setContextMap(Map contextMap) { + Map old = org.apache.log4j.MDC.getContext(); + if (old == null) { + Iterator entrySetIterator = contextMap.entrySet().iterator(); + while (entrySetIterator.hasNext()) { + Map.Entry mapEntry = (Map.Entry) entrySetIterator.next(); + org.apache.log4j.MDC.put((String) mapEntry.getKey(), mapEntry.getValue()); + } + } else { + old.clear(); + old.putAll(contextMap); + } + } +} diff --git a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index c2da612..2ed8c6e 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,88 +1,88 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.apache.log4j.Level; -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.helpers.Util; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - * - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - /** - * Declare the version of the SLF4J API this implementation is compiled against. - * The value of this field is modified with each major release. - */ - // to avoid constant folding by the compiler, this field must *not* be final - public static String REQUESTED_API_VERSION = "1.6.99"; // !final - - private static final String loggerFactoryClassStr = Log4jLoggerFactory.class.getName(); - - /** - * The ILoggerFactory instance returned by the {@link #getLoggerFactory} - * method should always be the same object - */ - private final ILoggerFactory loggerFactory; - - private StaticLoggerBinder() { - loggerFactory = new Log4jLoggerFactory(); - try { - @SuppressWarnings("unused") - Level level = Level.TRACE; - } catch (NoSuchFieldError nsfe) { - Util.report("This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version"); - } - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.apache.log4j.Level; +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.helpers.Util; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + * + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is modified with each major release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; // !final + + private static final String loggerFactoryClassStr = Log4jLoggerFactory.class.getName(); + + /** + * The ILoggerFactory instance returned by the {@link #getLoggerFactory} + * method should always be the same object + */ + private final ILoggerFactory loggerFactory; + + private StaticLoggerBinder() { + loggerFactory = new Log4jLoggerFactory(); + try { + @SuppressWarnings("unused") + Level level = Level.TRACE; + } catch (NoSuchFieldError nsfe) { + Util.report("This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version"); + } + } + + public ILoggerFactory getLoggerFactory() { + return loggerFactory; + } + + public String getLoggerFactoryClassStr() { + return loggerFactoryClassStr; + } +} diff --git a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMDCBinder.java index aab9ee6..2f64065 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,65 +1,65 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.spi.MDCAdapter; - -/** - * This implementation is bound to {@link Log4jMDCAdapter}. - * - * @author Ceki Gülcü - */ -public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - - private StaticMDCBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMDCBinder singleton - * @since 1.7.14 - */ - public static final StaticMDCBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link StaticMDCBinder}. - */ - public MDCAdapter getMDCA() { - return new Log4jMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return Log4jMDCAdapter.class.getName(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.spi.MDCAdapter; + +/** + * This implementation is bound to {@link Log4jMDCAdapter}. + * + * @author Ceki Gülcü + */ +public class StaticMDCBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMDCBinder singleton + * @since 1.7.14 + */ + public static final StaticMDCBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link StaticMDCBinder}. + */ + public MDCAdapter getMDCA() { + return new Log4jMDCAdapter(); + } + + public String getMDCAdapterClassStr() { + return Log4jMDCAdapter.class.getName(); + } +} diff --git a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMarkerBinder.java b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMarkerBinder.java index 21a48df..c37af78 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,77 +1,77 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMarkerBinder singleton - * @since 1.7.14 - */ - public static StaticMarkerBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMarkerBinder singleton + * @since 1.7.14 + */ + public static StaticMarkerBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + +} diff --git a/slf4j-log4j12/src/main/java/org/slf4j/impl/VersionUtil.java b/slf4j-log4j12/src/main/java/org/slf4j/impl/VersionUtil.java old file mode 100644 new file mode 100755 index ee913ed..2fa54d1 100755 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/VersionUtil.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/VersionUtil.java @@ -1,33 +1,33 @@ -package org.slf4j.impl; - -import java.lang.reflect.Method; - -import org.slf4j.helpers.Util; - -public class VersionUtil { - static final int MINIMAL_VERSION = 5; - - static public int getJavaMajorVersion() { - String javaVersionString = Util.safeGetSystemProperty("java.version"); - return getJavaMajorVersion(javaVersionString); - } - - static int getJavaMajorVersion(String versionString) { - if (versionString == null) - return MINIMAL_VERSION; - if (versionString.startsWith("1.")) { - return versionString.charAt(2) - '0'; - } else { - // we running under Java 9 or later - try { - Method versionMethod = Runtime.class.getMethod("version"); - Object versionObj = versionMethod.invoke(null); - Method majorMethod = versionObj.getClass().getMethod("major"); - Integer resultInteger = (Integer) majorMethod.invoke(versionObj); - return resultInteger.intValue(); - } catch (Exception e) { - return MINIMAL_VERSION; - } - } - } -} +package org.slf4j.impl; + +import java.lang.reflect.Method; + +import org.slf4j.helpers.Util; + +public class VersionUtil { + static final int MINIMAL_VERSION = 5; + + static public int getJavaMajorVersion() { + String javaVersionString = Util.safeGetSystemProperty("java.version"); + return getJavaMajorVersion(javaVersionString); + } + + static int getJavaMajorVersion(String versionString) { + if (versionString == null) + return MINIMAL_VERSION; + if (versionString.startsWith("1.")) { + return versionString.charAt(2) - '0'; + } else { + // we running under Java 9 or later + try { + Method versionMethod = Runtime.class.getMethod("version"); + Object versionObj = versionMethod.invoke(null); + Method majorMethod = versionObj.getClass().getMethod("major"); + Integer resultInteger = (Integer) majorMethod.invoke(versionObj); + return resultInteger.intValue(); + } catch (Exception e) { + return MINIMAL_VERSION; + } + } + } +} diff --git a/slf4j-log4j12/src/main/resources/META-INF/MANIFEST.MF b/slf4j-log4j12/src/main/resources/META-INF/MANIFEST.MF old file mode 100644 new file mode 100755 index 148ff62..f30e385 100755 --- a/slf4j-log4j12/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-log4j12/src/main/resources/META-INF/MANIFEST.MF @@ -1,13 +1,13 @@ -Implementation-Title: slf4j-log4j12 -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.log4j12 -Bundle-Name: slf4j-log4j12 -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, - org.slf4j.spi;version=${parsedVersion.osgiVersion}, - org.slf4j.helpers;version=${parsedVersion.osgiVersion}, - org.slf4j.event;version=${parsedVersion.osgiVersion}, - org.apache.log4j +Implementation-Title: slf4j-log4j12 +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.log4j12 +Bundle-Name: slf4j-log4j12 +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, + org.slf4j.spi;version=${parsedVersion.osgiVersion}, + org.slf4j.helpers;version=${parsedVersion.osgiVersion}, + org.slf4j.event;version=${parsedVersion.osgiVersion}, + org.apache.log4j Fragment-Host: slf4j.apidiff --git a/slf4j-log4j12/src/test/java/org/apache/log4j/MDCFriendTest.java b/slf4j-log4j12/src/test/java/org/apache/log4j/MDCFriendTest.java old file mode 100644 new file mode 100755 index ffa17f5..e487adf 100755 --- a/slf4j-log4j12/src/test/java/org/apache/log4j/MDCFriendTest.java +++ b/slf4j-log4j12/src/test/java/org/apache/log4j/MDCFriendTest.java @@ -1,32 +1,32 @@ -package org.apache.log4j; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import java.util.Random; - -import org.junit.Test; -import org.slf4j.impl.VersionUtil; - -public class MDCFriendTest { - - - private static Random random = new Random(); - int diff = random.nextInt(1024*8); - - @Test - public void smoke() { - if(VersionUtil.getJavaMajorVersion() < 9) - return; - - MDCFriend.fixForJava9(); - String key = "MDCFriendTest.smoke"+diff; - String val = "val"+diff; - MDC.put(key, val); - assertEquals(val, MDC.get(key)); - MDC.clear(); - assertNull(MDC.get(key)); - - } - -} +package org.apache.log4j; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.Random; + +import org.junit.Test; +import org.slf4j.impl.VersionUtil; + +public class MDCFriendTest { + + + private static Random random = new Random(); + int diff = random.nextInt(1024*8); + + @Test + public void smoke() { + if(VersionUtil.getJavaMajorVersion() < 9) + return; + + MDCFriend.fixForJava9(); + String key = "MDCFriendTest.smoke"+diff; + String val = "val"+diff; + MDC.put(key, val); + assertEquals(val, MDC.get(key)); + MDC.clear(); + assertNull(MDC.get(key)); + + } + +} diff --git a/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java b/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java index 6c71a11..f736f89 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java @@ -1,185 +1,185 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.spi.LoggingEvent; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - * - */ -public class InvocationTest { - - ListAppender listAppender = new ListAppender(); - org.apache.log4j.Logger root; - - @Before - public void setUp() throws Exception { - root = org.apache.log4j.Logger.getRootLogger(); - root.addAppender(listAppender); - } - - @After - public void tearDown() throws Exception { - root.getLoggerRepository().resetConfiguration(); - } - - @Test - public void test1() { - Logger logger = LoggerFactory.getLogger("test1"); - logger.debug("Hello world."); - assertEquals(1, listAppender.list.size()); - } - - @Test - public void test2() { - Integer i1 = Integer.valueOf(1); - Integer i2 = Integer.valueOf(2); - Integer i3 = Integer.valueOf(3); - Exception e = new Exception("This is a test exception."); - Logger logger = LoggerFactory.getLogger("test2"); - - logger.trace("Hello trace."); - - logger.debug("Hello world 1."); - logger.debug("Hello world {}", i1); - logger.debug("val={} val={}", i1, i2); - logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); - - logger.debug("Hello world 2", e); - logger.info("Hello world 2."); - - logger.warn("Hello world 3."); - logger.warn("Hello world 3", e); - - logger.error("Hello world 4."); - logger.error("Hello world {}", Integer.valueOf(3)); - logger.error("Hello world 4.", e); - assertEquals(11, listAppender.list.size()); - } - - @Test - public void testNull() { - Logger logger = LoggerFactory.getLogger("testNull"); - logger.trace(null); - logger.debug(null); - logger.info(null); - logger.warn(null); - logger.error(null); - - Exception e = new Exception("This is a test exception."); - logger.debug(null, e); - logger.info(null, e); - logger.warn(null, e); - logger.error(null, e); - assertEquals(8, listAppender.list.size()); - } - - // http://jira.qos.ch/browse/SLF4J-69 - // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=78 - @Test - public void testNullParameter_BUG78() { - Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78"); - String[] parameters = null; - String msg = "hello {}"; - - logger.debug(msg, (Object[]) parameters); - - assertEquals(1, listAppender.list.size()); - LoggingEvent e = (LoggingEvent) listAppender.list.get(0); - assertEquals(msg, e.getMessage()); - } - - @Test - public void testMarker() { - Logger logger = LoggerFactory.getLogger("testMarker"); - Marker blue = MarkerFactory.getMarker("BLUE"); - logger.trace(blue, "hello"); - logger.debug(blue, "hello"); - logger.info(blue, "hello"); - logger.warn(blue, "hello"); - logger.error(blue, "hello"); - - logger.debug(blue, "hello {}", "world"); - logger.info(blue, "hello {}", "world"); - logger.warn(blue, "hello {}", "world"); - logger.error(blue, "hello {}", "world"); - - logger.debug(blue, "hello {} and {} ", "world", "universe"); - logger.info(blue, "hello {} and {} ", "world", "universe"); - logger.warn(blue, "hello {} and {} ", "world", "universe"); - logger.error(blue, "hello {} and {} ", "world", "universe"); - assertEquals(12, listAppender.list.size()); - } - - @Test - public void testMDC() { - MDC.put("k", "v"); - assertNotNull(MDC.get("k")); - assertEquals("v", MDC.get("k")); - - MDC.remove("k"); - assertNull(MDC.get("k")); - - MDC.put("k1", "v1"); - assertEquals("v1", MDC.get("k1")); - MDC.clear(); - assertNull(MDC.get("k1")); - - try { - MDC.put(null, "x"); - fail("null keys are invalid"); - } catch (IllegalArgumentException e) { - } - } - - @Test - public void testMDCContextMapValues() { - Map map = new HashMap(); - map.put("ka", "va"); - map.put("kb", "vb"); - - MDC.put("k", "v"); - assertEquals("v", MDC.get("k")); - MDC.setContextMap(map); - assertNull(MDC.get("k")); - assertEquals("va", MDC.get("ka")); - assertEquals("vb", MDC.get("kb")); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * Test whether invoking the SLF4J API causes problems or not. + * + * @author Ceki Gulcu + * + */ +public class InvocationTest { + + ListAppender listAppender = new ListAppender(); + org.apache.log4j.Logger root; + + @Before + public void setUp() throws Exception { + root = org.apache.log4j.Logger.getRootLogger(); + root.addAppender(listAppender); + } + + @After + public void tearDown() throws Exception { + root.getLoggerRepository().resetConfiguration(); + } + + @Test + public void test1() { + Logger logger = LoggerFactory.getLogger("test1"); + logger.debug("Hello world."); + assertEquals(1, listAppender.list.size()); + } + + @Test + public void test2() { + Integer i1 = Integer.valueOf(1); + Integer i2 = Integer.valueOf(2); + Integer i3 = Integer.valueOf(3); + Exception e = new Exception("This is a test exception."); + Logger logger = LoggerFactory.getLogger("test2"); + + logger.trace("Hello trace."); + + logger.debug("Hello world 1."); + logger.debug("Hello world {}", i1); + logger.debug("val={} val={}", i1, i2); + logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); + + logger.debug("Hello world 2", e); + logger.info("Hello world 2."); + + logger.warn("Hello world 3."); + logger.warn("Hello world 3", e); + + logger.error("Hello world 4."); + logger.error("Hello world {}", Integer.valueOf(3)); + logger.error("Hello world 4.", e); + assertEquals(11, listAppender.list.size()); + } + + @Test + public void testNull() { + Logger logger = LoggerFactory.getLogger("testNull"); + logger.trace(null); + logger.debug(null); + logger.info(null); + logger.warn(null); + logger.error(null); + + Exception e = new Exception("This is a test exception."); + logger.debug(null, e); + logger.info(null, e); + logger.warn(null, e); + logger.error(null, e); + assertEquals(8, listAppender.list.size()); + } + + // http://jira.qos.ch/browse/SLF4J-69 + // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=78 + @Test + public void testNullParameter_BUG78() { + Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78"); + String[] parameters = null; + String msg = "hello {}"; + + logger.debug(msg, (Object[]) parameters); + + assertEquals(1, listAppender.list.size()); + LoggingEvent e = (LoggingEvent) listAppender.list.get(0); + assertEquals(msg, e.getMessage()); + } + + @Test + public void testMarker() { + Logger logger = LoggerFactory.getLogger("testMarker"); + Marker blue = MarkerFactory.getMarker("BLUE"); + logger.trace(blue, "hello"); + logger.debug(blue, "hello"); + logger.info(blue, "hello"); + logger.warn(blue, "hello"); + logger.error(blue, "hello"); + + logger.debug(blue, "hello {}", "world"); + logger.info(blue, "hello {}", "world"); + logger.warn(blue, "hello {}", "world"); + logger.error(blue, "hello {}", "world"); + + logger.debug(blue, "hello {} and {} ", "world", "universe"); + logger.info(blue, "hello {} and {} ", "world", "universe"); + logger.warn(blue, "hello {} and {} ", "world", "universe"); + logger.error(blue, "hello {} and {} ", "world", "universe"); + assertEquals(12, listAppender.list.size()); + } + + @Test + public void testMDC() { + MDC.put("k", "v"); + assertNotNull(MDC.get("k")); + assertEquals("v", MDC.get("k")); + + MDC.remove("k"); + assertNull(MDC.get("k")); + + MDC.put("k1", "v1"); + assertEquals("v1", MDC.get("k1")); + MDC.clear(); + assertNull(MDC.get("k1")); + + try { + MDC.put(null, "x"); + fail("null keys are invalid"); + } catch (IllegalArgumentException e) { + } + } + + @Test + public void testMDCContextMapValues() { + Map map = new HashMap(); + map.put("ka", "va"); + map.put("kb", "vb"); + + MDC.put("k", "v"); + assertEquals("v", MDC.get("k")); + MDC.setContextMap(map); + assertNull(MDC.get("k")); + assertEquals("va", MDC.get("ka")); + assertEquals("vb", MDC.get("kb")); + } + +} diff --git a/slf4j-log4j12/src/test/java/org/slf4j/ListAppender.java b/slf4j-log4j12/src/test/java/org/slf4j/ListAppender.java index a39d6d5..2959689 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/ListAppender.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/ListAppender.java @@ -1,53 +1,53 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.spi.LoggingEvent; - -public class ListAppender extends AppenderSkeleton { - - public List list = new ArrayList(); - - public boolean extractLocationInfo = false; - - protected void append(LoggingEvent event) { - list.add(event); - if (extractLocationInfo) { - event.getLocationInformation(); - } - } - - public void close() { - } - - public boolean requiresLayout() { - return false; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class ListAppender extends AppenderSkeleton { + + public List list = new ArrayList(); + + public boolean extractLocationInfo = false; + + protected void append(LoggingEvent event) { + list.add(event); + if (extractLocationInfo) { + event.getLocationInformation(); + } + } + + public void close() { + } + + public boolean requiresLayout() { + return false; + } + +} diff --git a/slf4j-log4j12/src/test/java/org/slf4j/impl/Log4j12MultithreadedInitializationTest.java b/slf4j-log4j12/src/test/java/org/slf4j/impl/Log4j12MultithreadedInitializationTest.java index 725b12b..a651e8f 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/impl/Log4j12MultithreadedInitializationTest.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/impl/Log4j12MultithreadedInitializationTest.java @@ -1,73 +1,73 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import java.util.List; - -import org.apache.log4j.LogManager; -import org.apache.log4j.spi.LoggingEvent; -import org.junit.After; -import org.junit.Before; -import static org.junit.Assert.assertNotNull; - -import org.slf4j.helpers.MultithreadedInitializationTest; - -public class Log4j12MultithreadedInitializationTest extends MultithreadedInitializationTest { - static int NUM_LINES_BY_RECURSIVE_APPENDER = 3; - - // value of LogManager.DEFAULT_CONFIGURATION_KEY; - static String CONFIG_FILE_KEY = "log4j.configuration"; - final String loggerName = this.getClass().getName(); - - @Before - public void setup() { - System.setProperty(CONFIG_FILE_KEY, "recursiveInitWithActivationDelay.properties"); - System.out.println("THREAD_COUNT=" + THREAD_COUNT); - } - - @After - public void tearDown() throws Exception { - System.clearProperty(CONFIG_FILE_KEY); - } - - protected long getRecordedEventCount() { - List eventList = getRecordedEvents(); - assertNotNull(eventList); - return eventList.size(); - } - - protected int extraLogEvents() { - return NUM_LINES_BY_RECURSIVE_APPENDER; - } - - private List getRecordedEvents() { - org.apache.log4j.Logger root = LogManager.getRootLogger(); - - RecursiveAppender ra = (RecursiveAppender) root.getAppender("RECURSIVE"); - assertNotNull(ra); - return ra.events; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import java.util.List; + +import org.apache.log4j.LogManager; +import org.apache.log4j.spi.LoggingEvent; +import org.junit.After; +import org.junit.Before; +import static org.junit.Assert.assertNotNull; + +import org.slf4j.helpers.MultithreadedInitializationTest; + +public class Log4j12MultithreadedInitializationTest extends MultithreadedInitializationTest { + static int NUM_LINES_BY_RECURSIVE_APPENDER = 3; + + // value of LogManager.DEFAULT_CONFIGURATION_KEY; + static String CONFIG_FILE_KEY = "log4j.configuration"; + final String loggerName = this.getClass().getName(); + + @Before + public void setup() { + System.setProperty(CONFIG_FILE_KEY, "recursiveInitWithActivationDelay.properties"); + System.out.println("THREAD_COUNT=" + THREAD_COUNT); + } + + @After + public void tearDown() throws Exception { + System.clearProperty(CONFIG_FILE_KEY); + } + + protected long getRecordedEventCount() { + List eventList = getRecordedEvents(); + assertNotNull(eventList); + return eventList.size(); + } + + protected int extraLogEvents() { + return NUM_LINES_BY_RECURSIVE_APPENDER; + } + + private List getRecordedEvents() { + org.apache.log4j.Logger root = LogManager.getRootLogger(); + + RecursiveAppender ra = (RecursiveAppender) root.getAppender("RECURSIVE"); + assertNotNull(ra); + return ra.events; + } + +} diff --git a/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveAppender.java b/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveAppender.java index 267e2b2..6c1e641 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveAppender.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveAppender.java @@ -1,88 +1,88 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.spi.LoggingEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RecursiveAppender extends AppenderSkeleton { - - int diff = new Random().nextInt(); - int activationDelay = 0; - String loggerName = "org.slf4j.impl.RecursiveAppender" + diff; - - List events = new ArrayList(); - - public RecursiveAppender() { - System.out.println("entering RecursiveAppender constructor"); - Logger logger = LoggerFactory.getLogger(loggerName); - logger.info("Calling a logger in the constructor"); - System.out.println("exiting RecursiveAppender constructor"); - } - - protected void append(LoggingEvent e) { - events.add(e); - } - - public void close() { - } - - public boolean requiresLayout() { - return false; - } - - @Override - public void activateOptions() { - System.out.println("entering RecursiveAppender.activateOptions"); - if (activationDelay > 0) { - Logger logger = LoggerFactory.getLogger(loggerName); - logger.info("About to wait {} millis", activationDelay); - try { - Thread.sleep(activationDelay); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Done waiting {} millis", activationDelay); - } - super.activateOptions(); - - System.out.println("exiting RecursiveAppender.activateOptions"); - } - - public int getActivationDelay() { - return activationDelay; - } - - public void setActivationDelay(int activationDelay) { - this.activationDelay = activationDelay; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RecursiveAppender extends AppenderSkeleton { + + int diff = new Random().nextInt(); + int activationDelay = 0; + String loggerName = "org.slf4j.impl.RecursiveAppender" + diff; + + List events = new ArrayList(); + + public RecursiveAppender() { + System.out.println("entering RecursiveAppender constructor"); + Logger logger = LoggerFactory.getLogger(loggerName); + logger.info("Calling a logger in the constructor"); + System.out.println("exiting RecursiveAppender constructor"); + } + + protected void append(LoggingEvent e) { + events.add(e); + } + + public void close() { + } + + public boolean requiresLayout() { + return false; + } + + @Override + public void activateOptions() { + System.out.println("entering RecursiveAppender.activateOptions"); + if (activationDelay > 0) { + Logger logger = LoggerFactory.getLogger(loggerName); + logger.info("About to wait {} millis", activationDelay); + try { + Thread.sleep(activationDelay); + } catch (InterruptedException e) { + e.printStackTrace(); + } + logger.info("Done waiting {} millis", activationDelay); + } + super.activateOptions(); + + System.out.println("exiting RecursiveAppender.activateOptions"); + } + + public int getActivationDelay() { + return activationDelay; + } + + public void setActivationDelay(int activationDelay) { + this.activationDelay = activationDelay; + } + +} diff --git a/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java b/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java old file mode 100644 new file mode 100755 index 3e02043..f6d485e 100755 --- a/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java @@ -1,54 +1,54 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import java.util.Random; - -import org.junit.After; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RecursiveInitializationTest { - - // value of LogManager.DEFAULT_CONFIGURATION_KEY; - static String CONFIG_FILE_KEY = "log4j.configuration"; - - int diff = new Random().nextInt(10000); - String loggerName = "org.slf4j.impl.RecursiveInitializationTest"; - - @After - public void tearDown() throws Exception { - System.clearProperty(CONFIG_FILE_KEY); - } - - @Test - public void loggingDuringInitialization() { - System.setProperty(CONFIG_FILE_KEY, "recursiveInit.properties"); - Logger logger = LoggerFactory.getLogger(loggerName + ".loggingDuringInitialization-" + diff); - logger.info("hello"); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import java.util.Random; + +import org.junit.After; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RecursiveInitializationTest { + + // value of LogManager.DEFAULT_CONFIGURATION_KEY; + static String CONFIG_FILE_KEY = "log4j.configuration"; + + int diff = new Random().nextInt(10000); + String loggerName = "org.slf4j.impl.RecursiveInitializationTest"; + + @After + public void tearDown() throws Exception { + System.clearProperty(CONFIG_FILE_KEY); + } + + @Test + public void loggingDuringInitialization() { + System.setProperty(CONFIG_FILE_KEY, "recursiveInit.properties"); + Logger logger = LoggerFactory.getLogger(loggerName + ".loggingDuringInitialization-" + diff); + logger.info("hello"); + } + +} diff --git a/slf4j-log4j12/src/test/java/org/slf4j/impl/UtilVersionTest.java b/slf4j-log4j12/src/test/java/org/slf4j/impl/UtilVersionTest.java old file mode 100644 new file mode 100755 index e84d5cf..934e6b4 100755 --- a/slf4j-log4j12/src/test/java/org/slf4j/impl/UtilVersionTest.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/impl/UtilVersionTest.java @@ -1,24 +1,24 @@ -package org.slf4j.impl; - -import static org.junit.Assert.*; - -import org.junit.Ignore; -import org.junit.Test; - -public class UtilVersionTest { - - @Test - public void test() { - System.out.println(System.getProperty("java.version")); - assertEquals(6, VersionUtil.getJavaMajorVersion("1.6")); - assertEquals(7, VersionUtil.getJavaMajorVersion("1.7.0_21-b11")); - assertEquals(8, VersionUtil.getJavaMajorVersion("1.8.0_25")); - } - - @Ignore - @Test // requires Java 9 to pass - public void testJava9() { - assertEquals(9, VersionUtil.getJavaMajorVersion("9ea")); - } - -} +package org.slf4j.impl; + +import static org.junit.Assert.*; + +import org.junit.Ignore; +import org.junit.Test; + +public class UtilVersionTest { + + @Test + public void test() { + System.out.println(System.getProperty("java.version")); + assertEquals(6, VersionUtil.getJavaMajorVersion("1.6")); + assertEquals(7, VersionUtil.getJavaMajorVersion("1.7.0_21-b11")); + assertEquals(8, VersionUtil.getJavaMajorVersion("1.8.0_25")); + } + + @Ignore + @Test // requires Java 9 to pass + public void testJava9() { + assertEquals(9, VersionUtil.getJavaMajorVersion("9ea")); + } + +} diff --git a/slf4j-log4j12/src/test/resources/recursiveInit.properties b/slf4j-log4j12/src/test/resources/recursiveInit.properties index 4903155..a8d5d76 100644 --- a/slf4j-log4j12/src/test/resources/recursiveInit.properties +++ b/slf4j-log4j12/src/test/resources/recursiveInit.properties @@ -1,8 +1,8 @@ -log4j.debug=true -log4j.rootLogger=DEBUG, RECURSIVE - -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%d [%t] %c - %m%n - +log4j.debug=true +log4j.rootLogger=DEBUG, RECURSIVE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d [%t] %c - %m%n + log4j.appender.RECURSIVE=org.slf4j.impl.RecursiveAppenderdiff --git a/slf4j-log4j12/src/test/resources/recursiveInitWithActivationDelay.properties b/slf4j-log4j12/src/test/resources/recursiveInitWithActivationDelay.properties old file mode 100644 new file mode 100755 index 91e93f6..4768562 100755 --- a/slf4j-log4j12/src/test/resources/recursiveInitWithActivationDelay.properties +++ b/slf4j-log4j12/src/test/resources/recursiveInitWithActivationDelay.properties @@ -1,9 +1,9 @@ -log4j.debug=true -log4j.rootLogger=DEBUG, CONSOLE, RECURSIVE - -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=CON %d [%t] %c - %m%n - -log4j.appender.RECURSIVE=org.slf4j.impl.RecursiveAppender +log4j.debug=true +log4j.rootLogger=DEBUG, CONSOLE, RECURSIVE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=CON %d [%t] %c - %m%n + +log4j.appender.RECURSIVE=org.slf4j.impl.RecursiveAppender log4j.appender.RECURSIVE.activationDelay=10diff --git a/slf4j-migrator/LIMITATIONS.txt b/slf4j-migrator/LIMITATIONS.txt new file mode 100755 index 0000000..39e5d02 --- /dev/null +++ b/slf4j-migrator/LIMITATIONS.txt @@ -0,0 +1,34 @@ + +The slf4j-migrator aims to + +General limitations +=================== + +- the FATAL level is not supported. + + This is limitation is not deemed serious because there are usually + very few log statements bearing the FATAL level. + + +- if a method declares multiple loggers on the same line, the conversion will not be complete. Example: + + + public void someMethod(Log l1, Log l2) { + ... + } + + will be converted as + + public void someMethod(Log l1, Logger l2) { + ... + } + + +When migrating from log4j +========================= + +- Since NDC is not supported by SLF4J, the migrator cannot properly handle + NDC statements. + +- Calls to PropertyConfigurator or DomConfigurator cannot be migrated since + SLF4J the equivalents. diff --git a/slf4j-migrator/jcl/jclcontent.java b/slf4j-migrator/jcl/jclcontent.java new file mode 100644 index 0000000..68ffd50 --- /dev/null +++ b/slf4j-migrator/jcl/jclcontent.java @@ -0,0 +1,22 @@ +/** +*This is not a class, just a sample of some jcl source code to convert +*/ +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; + + +Log l = LogFactory.getLog(MyClass.class); +Log mylog=LogFactory.getLog(MyClass.class); +Log mylog1 = LogFactory.getLog(MyClass.class); +Log mylog2 = LogFactory.getLog(MyClass.class); + +Log log3=LogFactory.getFactory().getInstance(MyClass.class); +Log mylog4 = LogFactory.getFactory().getInstance(MyClass.class); +Log mylog5 = LogFactory.getLog(MyClass.class); + +Log myLog6; + +log7=LogFactory.getFactory().getInstance(MyClass.class); +log8 =LogFactory.getFactory().getInstance(MyClass.class); +myLog9 = LogFactory.getLog(MyClass.class); + diff --git a/slf4j-migrator/pom.xml b/slf4j-migrator/pom.xml old file mode 100644 new file mode 100755 index 1762cc9..203ec8e 100755 --- a/slf4j-migrator/pom.xml +++ b/slf4j-migrator/pom.xml @@ -1,19 +1,19 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - slf4j-migrator - - jar - SLF4J Migrator - SLF4J Migrator - + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + slf4j-migrator + + jar + SLF4J Migrator + SLF4J Migrator + diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/Constant.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/Constant.java index 52e2862..120fa94 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/Constant.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/Constant.java @@ -1,36 +1,36 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -public class Constant { - - public final static int JCL_TO_SLF4J = 0; - public final static int LOG4J_TO_SLF4J = 1; - public final static int JUL_TO_SLF4J = 2; - public final static int NOP_TO_SLF4J = 3; - - public final static int NB_FILES_MAX = 1; - +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +public class Constant { + + public final static int JCL_TO_SLF4J = 0; + public final static int LOG4J_TO_SLF4J = 1; + public final static int JUL_TO_SLF4J = 2; + public final static int NOP_TO_SLF4J = 3; + + public final static int NB_FILES_MAX = 1; + }diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/ConversionException.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/ConversionException.java index 43d68bd..add4438 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/ConversionException.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/ConversionException.java @@ -1,63 +1,63 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -public class ConversionException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 498961799888576668L; - - private String detail; - - public static final String NOT_IMPLEMENTED = "Conversion mode not implemented yet"; - public static final String INVALID_DIRECTORY = "Invalid source directory"; - public static final String FILE_COPY = "Error during file copy"; - - public ConversionException(String message) { - super(message); - } - - public ConversionException(String message, String detail) { - super(message); - this.detail = detail; - } - - public String getDetail() { - return detail; - } - - public void setDetail(String detail) { - this.detail = detail; - } - - public void print() { - if (getMessage() != null) { - System.out.println(getMessage()); - } - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +public class ConversionException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 498961799888576668L; + + private String detail; + + public static final String NOT_IMPLEMENTED = "Conversion mode not implemented yet"; + public static final String INVALID_DIRECTORY = "Invalid source directory"; + public static final String FILE_COPY = "Error during file copy"; + + public ConversionException(String message) { + super(message); + } + + public ConversionException(String message, String detail) { + super(message); + this.detail = detail; + } + + public String getDetail() { + return detail; + } + + public void setDetail(String detail) { + this.detail = detail; + } + + public void print() { + if (getMessage() != null) { + System.out.println(getMessage()); + } + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/FileSelector.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/FileSelector.java index dfed4b7..71af29b 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/FileSelector.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/FileSelector.java @@ -1,69 +1,69 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.migrator.internal.ProgressListener; - -public class FileSelector { - - private List javaFileList = new ArrayList(); - - ProgressListener pl; - - FileSelector(ProgressListener pl) { - this.pl = pl; - } - - public List selectJavaFilesInFolder(File folder) { - if (folder.isDirectory()) { - selectFiles(folder); - return javaFileList; - } else { - throw new IllegalArgumentException("[" + folder + "] is not a directory"); - } - } - - private void selectFiles(File file) { - if (file.isDirectory()) { - pl.onDirectory(file); - File[] files = file.listFiles(); - if (files != null) { - for (int i = 0; i < files.length; i++) { - selectFiles(files[i]); - } - } - } else { - if (file.getName().endsWith(".java")) { - pl.onFileAddition(file); - javaFileList.add(file); - } - - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.migrator.internal.ProgressListener; + +public class FileSelector { + + private List javaFileList = new ArrayList(); + + ProgressListener pl; + + FileSelector(ProgressListener pl) { + this.pl = pl; + } + + public List selectJavaFilesInFolder(File folder) { + if (folder.isDirectory()) { + selectFiles(folder); + return javaFileList; + } else { + throw new IllegalArgumentException("[" + folder + "] is not a directory"); + } + } + + private void selectFiles(File file) { + if (file.isDirectory()) { + pl.onDirectory(file); + File[] files = file.listFiles(); + if (files != null) { + for (int i = 0; i < files.length; i++) { + selectFiles(files[i]); + } + } + } else { + if (file.getName().endsWith(".java")) { + pl.onFileAddition(file); + javaFileList.add(file); + } + + } + } +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java index 65eef71..d4bf3e6 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java @@ -1,110 +1,110 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; - -import org.slf4j.migrator.internal.ProgressListener; -import org.slf4j.migrator.line.LineConverter; -import org.slf4j.migrator.line.RuleSet; - -public class InplaceFileConverter { - - final static int BUFFER_LEN = 8 * 1024; - final LineConverter lineConverter; - final String lineTerminator; - final ProgressListener pl; - - InplaceFileConverter(RuleSet ruleSet, ProgressListener pl) { - this.lineConverter = new LineConverter(ruleSet); - lineTerminator = System.getProperty("line.separator"); - this.pl = pl; - } - - private byte[] readIntoByteArray(File file) throws IOException { - FileInputStream fis = new FileInputStream(file); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - int n = 0; - byte[] buffer = new byte[BUFFER_LEN]; - while ((n = fis.read(buffer)) != -1) { - // System.out.println("ba="+new String(buffer, "UTF-8")); - baos.write(buffer, 0, n); - } - fis.close(); - return baos.toByteArray(); - } - - void convert(File file) throws IOException { - byte[] originalBytes = readIntoByteArray(file); - byte[] convertedBytes = convertIntoTempByteArray(originalBytes); - if (lineConverter.atLeastOneMatchOccured()) { - // System.out.println("Converting ["+file+"]"); - writeConvertedBytesIntoFile(file, convertedBytes); - pl.onInplaceConversion(file); - } else { - // System.out.println("Not touching ["+file+"]"); - } - } - - private void writeConvertedBytesIntoFile(File file, byte[] convertedBytes) throws IOException { - FileOutputStream fos = new FileOutputStream(file); - fos.write(convertedBytes); - fos.flush(); - fos.close(); - } - - private byte[] convertIntoTempByteArray(byte[] input) throws IOException { - ByteArrayInputStream bais = new ByteArrayInputStream(input); - Reader reader = new InputStreamReader(bais); - BufferedReader breader = new BufferedReader(reader); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - while (true) { - String line = breader.readLine(); - if (line != null) { - String[] replacement = lineConverter.getReplacement(line); - writeReplacement(baos, replacement); - } else { - break; - } - } - return baos.toByteArray(); - } - - private void writeReplacement(OutputStream os, String[] replacement) throws IOException { - for (int i = 0; i < replacement.length; i++) { - os.write(replacement[i].getBytes()); - os.write(lineTerminator.getBytes()); - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; + +import org.slf4j.migrator.internal.ProgressListener; +import org.slf4j.migrator.line.LineConverter; +import org.slf4j.migrator.line.RuleSet; + +public class InplaceFileConverter { + + final static int BUFFER_LEN = 8 * 1024; + final LineConverter lineConverter; + final String lineTerminator; + final ProgressListener pl; + + InplaceFileConverter(RuleSet ruleSet, ProgressListener pl) { + this.lineConverter = new LineConverter(ruleSet); + lineTerminator = System.getProperty("line.separator"); + this.pl = pl; + } + + private byte[] readIntoByteArray(File file) throws IOException { + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + int n = 0; + byte[] buffer = new byte[BUFFER_LEN]; + while ((n = fis.read(buffer)) != -1) { + // System.out.println("ba="+new String(buffer, "UTF-8")); + baos.write(buffer, 0, n); + } + fis.close(); + return baos.toByteArray(); + } + + void convert(File file) throws IOException { + byte[] originalBytes = readIntoByteArray(file); + byte[] convertedBytes = convertIntoTempByteArray(originalBytes); + if (lineConverter.atLeastOneMatchOccured()) { + // System.out.println("Converting ["+file+"]"); + writeConvertedBytesIntoFile(file, convertedBytes); + pl.onInplaceConversion(file); + } else { + // System.out.println("Not touching ["+file+"]"); + } + } + + private void writeConvertedBytesIntoFile(File file, byte[] convertedBytes) throws IOException { + FileOutputStream fos = new FileOutputStream(file); + fos.write(convertedBytes); + fos.flush(); + fos.close(); + } + + private byte[] convertIntoTempByteArray(byte[] input) throws IOException { + ByteArrayInputStream bais = new ByteArrayInputStream(input); + Reader reader = new InputStreamReader(bais); + BufferedReader breader = new BufferedReader(reader); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + while (true) { + String line = breader.readLine(); + if (line != null) { + String[] replacement = lineConverter.getReplacement(line); + writeReplacement(baos, replacement); + } else { + break; + } + } + return baos.toByteArray(); + } + + private void writeReplacement(OutputStream os, String[] replacement) throws IOException { + for (int i = 0; i < replacement.length; i++) { + os.write(replacement[i].getBytes()); + os.write(lineTerminator.getBytes()); + } + } +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/Main.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/Main.java index b996295..5a94a41 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/Main.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/Main.java @@ -1,50 +1,50 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -package org.slf4j.migrator; - -import javax.swing.SwingUtilities; - -import org.slf4j.migrator.internal.MigratorFrame; - -/** - * Main entry point to the migrator. - * - * @author Ceki Gülcü - */ -public class Main { - - public static void main(String[] args) { - System.out.println("Starting SLF4J Migrator"); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - MigratorFrame inst = new MigratorFrame(); - inst.setLocationRelativeTo(null); - inst.setVisible(true); - } - }); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +package org.slf4j.migrator; + +import javax.swing.SwingUtilities; + +import org.slf4j.migrator.internal.MigratorFrame; + +/** + * Main entry point to the migrator. + * + * @author Ceki Gülcü + */ +public class Main { + + public static void main(String[] args) { + System.out.println("Starting SLF4J Migrator"); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + MigratorFrame inst = new MigratorFrame(); + inst.setLocationRelativeTo(null); + inst.setVisible(true); + } + }); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/ProjectConverter.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/ProjectConverter.java index 8f4a175..99f1a19 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/ProjectConverter.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/ProjectConverter.java @@ -1,126 +1,126 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.swing.SwingUtilities; - -import org.slf4j.migrator.internal.MigratorFrame; -import org.slf4j.migrator.internal.ProgressListener; -import org.slf4j.migrator.line.RuleSet; - -public class ProjectConverter { - - private RuleSet ruleSet; - private List exception; - - ProgressListener progressListener; - - public static void main(String[] args) throws IOException { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - MigratorFrame inst = new MigratorFrame(); - inst.setLocationRelativeTo(null); - inst.setVisible(true); - } - }); - } - - /** - * Ask for concrete matcher implementation depending on the conversion mode - * Ask for user confirmation to convert the selected source directory if valid - * Ask for user confirmation in case of number of files to convert > 1000 - * - * @param conversionType - * @param progressListener - */ - public ProjectConverter(int conversionType, ProgressListener progressListener) { - this.progressListener = progressListener; - ruleSet = RuleSetFactory.getMatcherImpl(conversionType); - if (ruleSet == null) { - addException(new ConversionException(ConversionException.NOT_IMPLEMENTED)); - } - } - - public void convertProject(File folder) { - FileSelector fs = new FileSelector(progressListener); - List fileList = fs.selectJavaFilesInFolder(folder); - scanFileList(fileList); - progressListener.onDone(); - } - - /** - * Convert a list of files - * - * @param lstFiles - */ - private void scanFileList(List lstFiles) { - progressListener.onFileScanBegin(); - Iterator itFile = lstFiles.iterator(); - while (itFile.hasNext()) { - File currentFile = itFile.next(); - progressListener.onFileScan(currentFile); - scanFile(currentFile); - } - } - - /** - * Convert the specified file Read each line and ask matcher implementation - * for conversion Rewrite the line returned by matcher - * - * @param file - */ - private void scanFile(File file) { - try { - InplaceFileConverter fc = new InplaceFileConverter(ruleSet, progressListener); - fc.convert(file); - } catch (IOException exc) { - addException(new ConversionException(exc.toString())); - } - } - - public void addException(ConversionException exc) { - if (exception == null) { - exception = new ArrayList(); - } - exception.add(exc); - } - - public void printException() { - if (exception != null) { - Iterator iterator = exception.iterator(); - while (iterator.hasNext()) { - ConversionException exc = (ConversionException) iterator.next(); - exc.print(); - } - exception = null; - } - } +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.swing.SwingUtilities; + +import org.slf4j.migrator.internal.MigratorFrame; +import org.slf4j.migrator.internal.ProgressListener; +import org.slf4j.migrator.line.RuleSet; + +public class ProjectConverter { + + private RuleSet ruleSet; + private List exception; + + ProgressListener progressListener; + + public static void main(String[] args) throws IOException { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + MigratorFrame inst = new MigratorFrame(); + inst.setLocationRelativeTo(null); + inst.setVisible(true); + } + }); + } + + /** + * Ask for concrete matcher implementation depending on the conversion mode + * Ask for user confirmation to convert the selected source directory if valid + * Ask for user confirmation in case of number of files to convert > 1000 + * + * @param conversionType + * @param progressListener + */ + public ProjectConverter(int conversionType, ProgressListener progressListener) { + this.progressListener = progressListener; + ruleSet = RuleSetFactory.getMatcherImpl(conversionType); + if (ruleSet == null) { + addException(new ConversionException(ConversionException.NOT_IMPLEMENTED)); + } + } + + public void convertProject(File folder) { + FileSelector fs = new FileSelector(progressListener); + List fileList = fs.selectJavaFilesInFolder(folder); + scanFileList(fileList); + progressListener.onDone(); + } + + /** + * Convert a list of files + * + * @param lstFiles + */ + private void scanFileList(List lstFiles) { + progressListener.onFileScanBegin(); + Iterator itFile = lstFiles.iterator(); + while (itFile.hasNext()) { + File currentFile = itFile.next(); + progressListener.onFileScan(currentFile); + scanFile(currentFile); + } + } + + /** + * Convert the specified file Read each line and ask matcher implementation + * for conversion Rewrite the line returned by matcher + * + * @param file + */ + private void scanFile(File file) { + try { + InplaceFileConverter fc = new InplaceFileConverter(ruleSet, progressListener); + fc.convert(file); + } catch (IOException exc) { + addException(new ConversionException(exc.toString())); + } + } + + public void addException(ConversionException exc) { + if (exception == null) { + exception = new ArrayList(); + } + exception.add(exc); + } + + public void printException() { + if (exception != null) { + Iterator iterator = exception.iterator(); + while (iterator.hasNext()) { + ConversionException exc = (ConversionException) iterator.next(); + exc.print(); + } + exception = null; + } + } }diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/RuleSetFactory.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/RuleSetFactory.java index d5151a5..a48038a 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/RuleSetFactory.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/RuleSetFactory.java @@ -1,62 +1,62 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -import org.slf4j.migrator.line.EmptyRuleSet; -import org.slf4j.migrator.line.JCLRuleSet; -import org.slf4j.migrator.line.JULRuleSet; -import org.slf4j.migrator.line.Log4jRuleSet; -import org.slf4j.migrator.line.RuleSet; - -/** - * This class runs Pattern matching with java.util.regex using Patterns defined - * in concrete implementations - * - * @author jean-noelcharpin - * - */ -public abstract class RuleSetFactory { - - /** - * Return matcher implementation depending on the conversion mode - * - * @param conversionType - * @return AbstractMatcher implementation - */ - public static RuleSet getMatcherImpl(int conversionType) { - switch (conversionType) { - case Constant.JCL_TO_SLF4J: - return new JCLRuleSet(); - case Constant.LOG4J_TO_SLF4J: - return new Log4jRuleSet(); - case Constant.JUL_TO_SLF4J: - return new JULRuleSet(); - case Constant.NOP_TO_SLF4J: - return new EmptyRuleSet(); - default: - return null; - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +import org.slf4j.migrator.line.EmptyRuleSet; +import org.slf4j.migrator.line.JCLRuleSet; +import org.slf4j.migrator.line.JULRuleSet; +import org.slf4j.migrator.line.Log4jRuleSet; +import org.slf4j.migrator.line.RuleSet; + +/** + * This class runs Pattern matching with java.util.regex using Patterns defined + * in concrete implementations + * + * @author jean-noelcharpin + * + */ +public abstract class RuleSetFactory { + + /** + * Return matcher implementation depending on the conversion mode + * + * @param conversionType + * @return AbstractMatcher implementation + */ + public static RuleSet getMatcherImpl(int conversionType) { + switch (conversionType) { + case Constant.JCL_TO_SLF4J: + return new JCLRuleSet(); + case Constant.LOG4J_TO_SLF4J: + return new Log4jRuleSet(); + case Constant.JUL_TO_SLF4J: + return new JULRuleSet(); + case Constant.NOP_TO_SLF4J: + return new EmptyRuleSet(); + default: + return null; + } + } +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/Abbreviator.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/Abbreviator.java index 3322642..34bebda 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/Abbreviator.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/Abbreviator.java @@ -1,89 +1,89 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.helper; - -public class Abbreviator { - static final String FILLER = "..."; - - final char folderSeparator; - final int invariantPrefixLength; - final int desiredLength; - - public Abbreviator(int invariantPrefixLength, int desiredLength, char folderSeparator) { - this.invariantPrefixLength = invariantPrefixLength; - this.desiredLength = desiredLength; - this.folderSeparator = folderSeparator; - } - - public String abbreviate(String filename) { - if (filename.length() <= desiredLength) { - return filename; - } else { - - int firstIndex = filename.indexOf(folderSeparator, invariantPrefixLength); - if (firstIndex == -1) { - // we cant't process this string - return filename; - } - StringBuilder buf = new StringBuilder(desiredLength); - buf.append(filename, 0, firstIndex + 1); - buf.append(FILLER); - int nextIndex = computeNextIndex(filename, firstIndex); - if (nextIndex != -1) { - buf.append(filename.substring(nextIndex)); - } else { - // better long than wrong - return filename; - } - - if (buf.length() < filename.length()) { - return buf.toString(); - } else { - // we tried our best but we are still could not shorten the input - return filename; - } - } - } - - int computeNextIndex(String filename, int firstIndex) { - int nextIndex = firstIndex + 1; - int hitCount = 0; - int minToRemove = filename.length() - desiredLength + FILLER.length(); - while (nextIndex < firstIndex + minToRemove) { - int tmpIndex = filename.indexOf(folderSeparator, nextIndex + 1); - if (tmpIndex == -1) { - if (hitCount == 0) { - return -1; - } else { - return nextIndex; - } - } else { - hitCount++; - nextIndex = tmpIndex; - } - } - return nextIndex; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.helper; + +public class Abbreviator { + static final String FILLER = "..."; + + final char folderSeparator; + final int invariantPrefixLength; + final int desiredLength; + + public Abbreviator(int invariantPrefixLength, int desiredLength, char folderSeparator) { + this.invariantPrefixLength = invariantPrefixLength; + this.desiredLength = desiredLength; + this.folderSeparator = folderSeparator; + } + + public String abbreviate(String filename) { + if (filename.length() <= desiredLength) { + return filename; + } else { + + int firstIndex = filename.indexOf(folderSeparator, invariantPrefixLength); + if (firstIndex == -1) { + // we cant't process this string + return filename; + } + StringBuilder buf = new StringBuilder(desiredLength); + buf.append(filename, 0, firstIndex + 1); + buf.append(FILLER); + int nextIndex = computeNextIndex(filename, firstIndex); + if (nextIndex != -1) { + buf.append(filename.substring(nextIndex)); + } else { + // better long than wrong + return filename; + } + + if (buf.length() < filename.length()) { + return buf.toString(); + } else { + // we tried our best but we are still could not shorten the input + return filename; + } + } + } + + int computeNextIndex(String filename, int firstIndex) { + int nextIndex = firstIndex + 1; + int hitCount = 0; + int minToRemove = filename.length() - desiredLength + FILLER.length(); + while (nextIndex < firstIndex + minToRemove) { + int tmpIndex = filename.indexOf(folderSeparator, nextIndex + 1); + if (tmpIndex == -1) { + if (hitCount == 0) { + return -1; + } else { + return nextIndex; + } + } else { + hitCount++; + nextIndex = tmpIndex; + } + } + return nextIndex; + } +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/SpringLayoutHelper.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/SpringLayoutHelper.java index 1363486..c438a98 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/SpringLayoutHelper.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/SpringLayoutHelper.java @@ -1,61 +1,61 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.helper; - -import java.awt.Component; - -import javax.swing.SpringLayout; - -public class SpringLayoutHelper { - - final SpringLayout sl; - final int basicPadding; - - public SpringLayoutHelper(SpringLayout springLayout, int basicPadding) { - sl = springLayout; - this.basicPadding = basicPadding; - } - - public void placeToTheRight(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) { - sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, SpringLayout.EAST, relativeTo); - - sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, SpringLayout.NORTH, relativeTo); - } - - public void placeToTheRight(Component relativeTo, Component componentToPlace) { - placeToTheRight(relativeTo, componentToPlace, basicPadding, 0); - } - - public void placeBelow(Component relativeTo, Component componentToPlace) { - placeBelow(relativeTo, componentToPlace, 0, basicPadding); - } - - public void placeBelow(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) { - sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, SpringLayout.WEST, relativeTo); - - sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, SpringLayout.SOUTH, relativeTo); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.helper; + +import java.awt.Component; + +import javax.swing.SpringLayout; + +public class SpringLayoutHelper { + + final SpringLayout sl; + final int basicPadding; + + public SpringLayoutHelper(SpringLayout springLayout, int basicPadding) { + sl = springLayout; + this.basicPadding = basicPadding; + } + + public void placeToTheRight(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) { + sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, SpringLayout.EAST, relativeTo); + + sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, SpringLayout.NORTH, relativeTo); + } + + public void placeToTheRight(Component relativeTo, Component componentToPlace) { + placeToTheRight(relativeTo, componentToPlace, basicPadding, 0); + } + + public void placeBelow(Component relativeTo, Component componentToPlace) { + placeBelow(relativeTo, componentToPlace, 0, basicPadding); + } + + public void placeBelow(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) { + sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, SpringLayout.WEST, relativeTo); + + sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, SpringLayout.SOUTH, relativeTo); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ConversionTask.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ConversionTask.java index 92b8c7a..a6590ab 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ConversionTask.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ConversionTask.java @@ -1,56 +1,56 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.internal; - -import java.io.File; - -import org.slf4j.migrator.ProjectConverter; - -public class ConversionTask implements Runnable { - - final File folder; - final MigratorFrame frame; - final int conversionType; - - ConversionTask(File folder, MigratorFrame frame, int conversionType) { - this.folder = folder; - this.frame = frame; - this.conversionType = conversionType; - } - - public void run() { - ProgressListener pl = new ProgressListenerImpl(folder, frame); - pl.onMigrationBegin(); - ProjectConverter converter = new ProjectConverter(conversionType, pl); - converter.convertProject(folder); - } - - public void launch() { - Thread t = new Thread(this); - t.setDaemon(true); - t.start(); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.internal; + +import java.io.File; + +import org.slf4j.migrator.ProjectConverter; + +public class ConversionTask implements Runnable { + + final File folder; + final MigratorFrame frame; + final int conversionType; + + ConversionTask(File folder, MigratorFrame frame, int conversionType) { + this.folder = folder; + this.frame = frame; + this.conversionType = conversionType; + } + + public void run() { + ProgressListener pl = new ProgressListenerImpl(folder, frame); + pl.onMigrationBegin(); + ProjectConverter converter = new ProjectConverter(conversionType, pl); + converter.convertProject(folder); + } + + public void launch() { + Thread t = new Thread(this); + t.setDaemon(true); + t.start(); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/MigratorFrame.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/MigratorFrame.java index aa37d40..a820943 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/MigratorFrame.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/MigratorFrame.java @@ -1,363 +1,363 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.internal; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JProgressBar; -import javax.swing.JRadioButton; -import javax.swing.JTextField; -import javax.swing.SpringLayout; -import javax.swing.WindowConstants; - -import org.slf4j.migrator.Constant; -import org.slf4j.migrator.helper.SpringLayoutHelper; - -public class MigratorFrame extends JFrame implements ActionListener { - private static final long serialVersionUID = 1L; - - private static final int BASIC_PADDING = 10; - private static final int FOLDER_COLUMNS = 40; - private static final String MIGRATE_COMMAND = "MIGRATE_COMMAND"; - private static final String BROWSE_COMMAND = "BROWSE_COMMAND"; - static final String EXIT_COMMAND = "EXIT_COMMAND"; - - static final int X_SIZE = 700; - static final int Y_SIZE = 400; - - private SpringLayout layoutManager = new SpringLayout(); - private SpringLayoutHelper slh = new SpringLayoutHelper(layoutManager, BASIC_PADDING); - - private JLabel migrationLabel; - - private JRadioButton radioLog4j; - private JRadioButton radioJCL; - private JRadioButton radioJUL; - private ButtonGroup buttonGroup; - - private JTextField folderTextField; - private JLabel warningLabel; - JButton migrateButton; - private JButton browseButton; - private JLabel folderLabel; - - private JCheckBox awareCheckBox; - private JLabel awareLabel; - - JLabel otherLabel; - JProgressBar progressBar; - private JFileChooser fileChooser; - - public MigratorFrame() { - super(); - initGUI(); - } - - private void initGUI() { - try { - setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); - getContentPane().setLayout(layoutManager); - this.setTitle("SLF4J migrator"); - - createComponents(); - constrainAll(); - addAllComponentsToContextPane(); - pack(); - this.setSize(700, 400); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void createComponents() { - createMigrationLabel(); - createRadioJCL(); - createRadioLog4j(); - createRadioJUL(); - createButtonGroup(); - createFolderLabel(); - createFolderTextField(); - createBrowseButton(); - createMigrateButton(); - createAwareCheckbox(); - createAwareLabel(); - createWarningLabel(); - createFileChooser(); - - otherLabel = new JLabel(); - otherLabel.setText(""); - createProgressBar(); - - } - - /** - * - */ - private void constrainAll() { - - // contrain migration label - layoutManager.putConstraint(SpringLayout.WEST, migrationLabel, BASIC_PADDING, SpringLayout.EAST, this); - - layoutManager.putConstraint(SpringLayout.NORTH, migrationLabel, BASIC_PADDING, SpringLayout.NORTH, this); - - slh.placeToTheRight(migrationLabel, radioJCL, BASIC_PADDING, -BASIC_PADDING / 2); - slh.placeBelow(radioJCL, radioLog4j, 0, 0); - - slh.placeBelow(radioLog4j, radioJUL, 0, 0); - - slh.placeBelow(migrationLabel, folderLabel, 0, BASIC_PADDING * 6); - slh.placeToTheRight(folderLabel, folderTextField); - slh.placeToTheRight(folderTextField, browseButton, BASIC_PADDING, -BASIC_PADDING / 2); - - slh.placeBelow(folderLabel, warningLabel, 0, BASIC_PADDING * 3); - - slh.placeBelow(warningLabel, awareCheckBox, 0, (int) (BASIC_PADDING * 1.5)); - slh.placeToTheRight(awareCheckBox, awareLabel); - - slh.placeBelow(awareCheckBox, migrateButton, 0, BASIC_PADDING * 3); - - slh.placeBelow(migrateButton, otherLabel, 0, BASIC_PADDING * 2); - - slh.placeBelow(otherLabel, progressBar, 0, BASIC_PADDING); - } - - private void addAllComponentsToContextPane() { - getContentPane().add(migrationLabel); - getContentPane().add(radioJCL); - getContentPane().add(radioLog4j); - getContentPane().add(radioJUL); - - getContentPane().add(folderLabel); - getContentPane().add(folderTextField); - getContentPane().add(browseButton); - getContentPane().add(migrateButton); - - getContentPane().add(awareCheckBox); - getContentPane().add(awareLabel); - - getContentPane().add(warningLabel); - - getContentPane().add(otherLabel); - getContentPane().add(progressBar); - } - - private void createButtonGroup() { - buttonGroup = new ButtonGroup(); - buttonGroup.add(radioJCL); - buttonGroup.add(radioLog4j); - buttonGroup.add(radioJUL); - } - - private void createMigrationLabel() { - migrationLabel = new JLabel(); - migrationLabel.setText("Migration Type"); - } - - private void createRadioJCL() { - radioJCL = new JRadioButton(); - radioJCL.setText("from Jakarta Commons Logging to SLF4J"); - radioJCL.setToolTipText("Select this button if you wish to migrate a Java project using Jakarta Commons Logging to use SLF4J."); - } - - private void createRadioLog4j() { - radioLog4j = new JRadioButton(); - radioLog4j.setText("from log4j to SLF4J "); - radioLog4j.setToolTipText("Select this button if you wish to migrate a Java project using log4j to use SLF4J."); - } - - private void createRadioJUL() { - radioJUL = new JRadioButton(); - radioJUL.setText("from JUL to SLF4J "); - radioJUL.setToolTipText("Select this button if you wish to migrate a Java project using java.utl.logging (JUL) to use SLF4J."); - } - - private void createFolderLabel() { - folderLabel = new JLabel(); - folderLabel.setText("Project Directory"); - } - - private void createFolderTextField() { - folderTextField = new JTextField(); - folderTextField.setColumns(FOLDER_COLUMNS); - } - - private void createBrowseButton() { - browseButton = new JButton(); - browseButton.setText("Browse"); - browseButton.addActionListener(this); - browseButton.setActionCommand(BROWSE_COMMAND); - browseButton.setToolTipText("Click this button to browse the file systems on your computer."); - } - - private void createAwareCheckbox() { - awareCheckBox = new JCheckBox(); - awareCheckBox.setToolTipText("

Check this box of you understand that the migration tool

will not backup your Java source files."); - } - - private void createAwareLabel() { - awareLabel = new JLabel(); - awareLabel.setText("" + "

I am aware that this tool will directly modify all Java source files

" - + "

in the selected folder without creating backup files.

" + ""); - } - - private void createWarningLabel() { - warningLabel = new JLabel(); - warningLabel.setText("" + "

WARNING: This SLF4J migration tool will directly modify all Java source files

" - + "

in the selected project folder without creating a backup of the original files.

" + ""); - } - - private void createMigrateButton() { - migrateButton = new JButton(); - migrateButton.setText("Migrate Project to SLF4J"); - migrateButton.setToolTipText("Click this button to initiate migration of your project."); - migrateButton.addActionListener(this); - migrateButton.setActionCommand(MIGRATE_COMMAND); - } - - private void createFileChooser() { - fileChooser = new JFileChooser(); - fileChooser.setDialogTitle("Source folder selector"); - fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - } - - private void createProgressBar() { - progressBar = new JProgressBar(0, 1); - progressBar.setPreferredSize(new java.awt.Dimension((int) (X_SIZE * 0.8), 5)); - progressBar.setVisible(false); - } - - public void disableInput() { - radioJCL.setEnabled(false); - radioLog4j.setEnabled(false); - - browseButton.setEnabled(false); - - folderTextField.setEnabled(false); - awareCheckBox.setEnabled(false); - migrateButton.setText("Migration in progress"); - migrateButton.setEnabled(false); - - } - - public void actionPerformed(ActionEvent e) { - - if (MIGRATE_COMMAND.equals(e.getActionCommand())) { - - List errorList = doSanityAnalysis(); - if (errorList.size() > 0) { - showDialogBox(errorList); - } else { - - File projectFolder = new File(folderTextField.getText()); - int conversionType; - if (radioJCL.isSelected()) { - conversionType = Constant.JCL_TO_SLF4J; - } else if (radioLog4j.isSelected()) { - conversionType = Constant.LOG4J_TO_SLF4J; - } else if (radioJUL.isSelected()) { - conversionType = Constant.JUL_TO_SLF4J; - } else { - // we cannot possibly reach here - throw new IllegalStateException("One of JCL or log4j project must have been previously chosen."); - } - ConversionTask task = new ConversionTask(projectFolder, this, conversionType); - task.launch(); - } - } else if (BROWSE_COMMAND.equals(e.getActionCommand())) { - showFileChooser(); - } else if (EXIT_COMMAND.equals(e.getActionCommand())) { - this.dispose(); - } - } - - void showFileChooser() { - int returnVal = fileChooser.showOpenDialog(this); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File selectedFile = fileChooser.getSelectedFile(); - folderTextField.setText(selectedFile.getAbsolutePath()); - } - } - - List doSanityAnalysis() { - - List errorList = new ArrayList(); - if (!radioJCL.isSelected() && !radioLog4j.isSelected() && !radioJUL.isSelected()) { - errorList.add("Please select the migration type: JCL, log4j, or JUL to SLF4J."); - } - - String folder = folderTextField.getText(); - - if (folder == null || folder.length() == 0) { - errorList.add("Please select the folder of the project to migrate"); - } else if (!isDirectory(folder)) { - errorList.add("[" + folder + "] does not look like a valid folder"); - } - - if (!awareCheckBox.isSelected()) { - errorList.add("Cannot initiate migration unless you acknowledge

that files will be modified without creating backup files"); - } - return errorList; - } - - void showDialogBox(List errorList) { - StringBuilder buf = new StringBuilder(); - buf.append(""); - int i = 1; - for (String msg : errorList) { - buf.append("

"); - buf.append(i); - buf.append(". "); - buf.append(msg); - buf.append("

"); - i++; - } - buf.append(""); - - JOptionPane.showMessageDialog(this, buf.toString(), "", JOptionPane.ERROR_MESSAGE); - } - - boolean isDirectory(String filename) { - if (filename == null) { - return false; - } - File file = new File(filename); - if (file.exists() && file.isDirectory()) { - return true; - } else { - return false; - } - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.internal; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import javax.swing.ButtonGroup; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JProgressBar; +import javax.swing.JRadioButton; +import javax.swing.JTextField; +import javax.swing.SpringLayout; +import javax.swing.WindowConstants; + +import org.slf4j.migrator.Constant; +import org.slf4j.migrator.helper.SpringLayoutHelper; + +public class MigratorFrame extends JFrame implements ActionListener { + private static final long serialVersionUID = 1L; + + private static final int BASIC_PADDING = 10; + private static final int FOLDER_COLUMNS = 40; + private static final String MIGRATE_COMMAND = "MIGRATE_COMMAND"; + private static final String BROWSE_COMMAND = "BROWSE_COMMAND"; + static final String EXIT_COMMAND = "EXIT_COMMAND"; + + static final int X_SIZE = 700; + static final int Y_SIZE = 400; + + private SpringLayout layoutManager = new SpringLayout(); + private SpringLayoutHelper slh = new SpringLayoutHelper(layoutManager, BASIC_PADDING); + + private JLabel migrationLabel; + + private JRadioButton radioLog4j; + private JRadioButton radioJCL; + private JRadioButton radioJUL; + private ButtonGroup buttonGroup; + + private JTextField folderTextField; + private JLabel warningLabel; + JButton migrateButton; + private JButton browseButton; + private JLabel folderLabel; + + private JCheckBox awareCheckBox; + private JLabel awareLabel; + + JLabel otherLabel; + JProgressBar progressBar; + private JFileChooser fileChooser; + + public MigratorFrame() { + super(); + initGUI(); + } + + private void initGUI() { + try { + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + getContentPane().setLayout(layoutManager); + this.setTitle("SLF4J migrator"); + + createComponents(); + constrainAll(); + addAllComponentsToContextPane(); + pack(); + this.setSize(700, 400); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void createComponents() { + createMigrationLabel(); + createRadioJCL(); + createRadioLog4j(); + createRadioJUL(); + createButtonGroup(); + createFolderLabel(); + createFolderTextField(); + createBrowseButton(); + createMigrateButton(); + createAwareCheckbox(); + createAwareLabel(); + createWarningLabel(); + createFileChooser(); + + otherLabel = new JLabel(); + otherLabel.setText(""); + createProgressBar(); + + } + + /** + * + */ + private void constrainAll() { + + // contrain migration label + layoutManager.putConstraint(SpringLayout.WEST, migrationLabel, BASIC_PADDING, SpringLayout.EAST, this); + + layoutManager.putConstraint(SpringLayout.NORTH, migrationLabel, BASIC_PADDING, SpringLayout.NORTH, this); + + slh.placeToTheRight(migrationLabel, radioJCL, BASIC_PADDING, -BASIC_PADDING / 2); + slh.placeBelow(radioJCL, radioLog4j, 0, 0); + + slh.placeBelow(radioLog4j, radioJUL, 0, 0); + + slh.placeBelow(migrationLabel, folderLabel, 0, BASIC_PADDING * 6); + slh.placeToTheRight(folderLabel, folderTextField); + slh.placeToTheRight(folderTextField, browseButton, BASIC_PADDING, -BASIC_PADDING / 2); + + slh.placeBelow(folderLabel, warningLabel, 0, BASIC_PADDING * 3); + + slh.placeBelow(warningLabel, awareCheckBox, 0, (int) (BASIC_PADDING * 1.5)); + slh.placeToTheRight(awareCheckBox, awareLabel); + + slh.placeBelow(awareCheckBox, migrateButton, 0, BASIC_PADDING * 3); + + slh.placeBelow(migrateButton, otherLabel, 0, BASIC_PADDING * 2); + + slh.placeBelow(otherLabel, progressBar, 0, BASIC_PADDING); + } + + private void addAllComponentsToContextPane() { + getContentPane().add(migrationLabel); + getContentPane().add(radioJCL); + getContentPane().add(radioLog4j); + getContentPane().add(radioJUL); + + getContentPane().add(folderLabel); + getContentPane().add(folderTextField); + getContentPane().add(browseButton); + getContentPane().add(migrateButton); + + getContentPane().add(awareCheckBox); + getContentPane().add(awareLabel); + + getContentPane().add(warningLabel); + + getContentPane().add(otherLabel); + getContentPane().add(progressBar); + } + + private void createButtonGroup() { + buttonGroup = new ButtonGroup(); + buttonGroup.add(radioJCL); + buttonGroup.add(radioLog4j); + buttonGroup.add(radioJUL); + } + + private void createMigrationLabel() { + migrationLabel = new JLabel(); + migrationLabel.setText("Migration Type"); + } + + private void createRadioJCL() { + radioJCL = new JRadioButton(); + radioJCL.setText("from Jakarta Commons Logging to SLF4J"); + radioJCL.setToolTipText("Select this button if you wish to migrate a Java project using Jakarta Commons Logging to use SLF4J."); + } + + private void createRadioLog4j() { + radioLog4j = new JRadioButton(); + radioLog4j.setText("from log4j to SLF4J "); + radioLog4j.setToolTipText("Select this button if you wish to migrate a Java project using log4j to use SLF4J."); + } + + private void createRadioJUL() { + radioJUL = new JRadioButton(); + radioJUL.setText("from JUL to SLF4J "); + radioJUL.setToolTipText("Select this button if you wish to migrate a Java project using java.utl.logging (JUL) to use SLF4J."); + } + + private void createFolderLabel() { + folderLabel = new JLabel(); + folderLabel.setText("Project Directory"); + } + + private void createFolderTextField() { + folderTextField = new JTextField(); + folderTextField.setColumns(FOLDER_COLUMNS); + } + + private void createBrowseButton() { + browseButton = new JButton(); + browseButton.setText("Browse"); + browseButton.addActionListener(this); + browseButton.setActionCommand(BROWSE_COMMAND); + browseButton.setToolTipText("Click this button to browse the file systems on your computer."); + } + + private void createAwareCheckbox() { + awareCheckBox = new JCheckBox(); + awareCheckBox.setToolTipText("

Check this box of you understand that the migration tool

will not backup your Java source files."); + } + + private void createAwareLabel() { + awareLabel = new JLabel(); + awareLabel.setText("" + "

I am aware that this tool will directly modify all Java source files

" + + "

in the selected folder without creating backup files.

" + ""); + } + + private void createWarningLabel() { + warningLabel = new JLabel(); + warningLabel.setText("" + "

WARNING: This SLF4J migration tool will directly modify all Java source files

" + + "

in the selected project folder without creating a backup of the original files.

" + ""); + } + + private void createMigrateButton() { + migrateButton = new JButton(); + migrateButton.setText("Migrate Project to SLF4J"); + migrateButton.setToolTipText("Click this button to initiate migration of your project."); + migrateButton.addActionListener(this); + migrateButton.setActionCommand(MIGRATE_COMMAND); + } + + private void createFileChooser() { + fileChooser = new JFileChooser(); + fileChooser.setDialogTitle("Source folder selector"); + fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + } + + private void createProgressBar() { + progressBar = new JProgressBar(0, 1); + progressBar.setPreferredSize(new java.awt.Dimension((int) (X_SIZE * 0.8), 5)); + progressBar.setVisible(false); + } + + public void disableInput() { + radioJCL.setEnabled(false); + radioLog4j.setEnabled(false); + + browseButton.setEnabled(false); + + folderTextField.setEnabled(false); + awareCheckBox.setEnabled(false); + migrateButton.setText("Migration in progress"); + migrateButton.setEnabled(false); + + } + + public void actionPerformed(ActionEvent e) { + + if (MIGRATE_COMMAND.equals(e.getActionCommand())) { + + List errorList = doSanityAnalysis(); + if (errorList.size() > 0) { + showDialogBox(errorList); + } else { + + File projectFolder = new File(folderTextField.getText()); + int conversionType; + if (radioJCL.isSelected()) { + conversionType = Constant.JCL_TO_SLF4J; + } else if (radioLog4j.isSelected()) { + conversionType = Constant.LOG4J_TO_SLF4J; + } else if (radioJUL.isSelected()) { + conversionType = Constant.JUL_TO_SLF4J; + } else { + // we cannot possibly reach here + throw new IllegalStateException("One of JCL or log4j project must have been previously chosen."); + } + ConversionTask task = new ConversionTask(projectFolder, this, conversionType); + task.launch(); + } + } else if (BROWSE_COMMAND.equals(e.getActionCommand())) { + showFileChooser(); + } else if (EXIT_COMMAND.equals(e.getActionCommand())) { + this.dispose(); + } + } + + void showFileChooser() { + int returnVal = fileChooser.showOpenDialog(this); + if (returnVal == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + folderTextField.setText(selectedFile.getAbsolutePath()); + } + } + + List doSanityAnalysis() { + + List errorList = new ArrayList(); + if (!radioJCL.isSelected() && !radioLog4j.isSelected() && !radioJUL.isSelected()) { + errorList.add("Please select the migration type: JCL, log4j, or JUL to SLF4J."); + } + + String folder = folderTextField.getText(); + + if (folder == null || folder.length() == 0) { + errorList.add("Please select the folder of the project to migrate"); + } else if (!isDirectory(folder)) { + errorList.add("[" + folder + "] does not look like a valid folder"); + } + + if (!awareCheckBox.isSelected()) { + errorList.add("Cannot initiate migration unless you acknowledge

that files will be modified without creating backup files"); + } + return errorList; + } + + void showDialogBox(List errorList) { + StringBuilder buf = new StringBuilder(); + buf.append(""); + int i = 1; + for (String msg : errorList) { + buf.append("

"); + buf.append(i); + buf.append(". "); + buf.append(msg); + buf.append("

"); + i++; + } + buf.append(""); + + JOptionPane.showMessageDialog(this, buf.toString(), "", JOptionPane.ERROR_MESSAGE); + } + + boolean isDirectory(String filename) { + if (filename == null) { + return false; + } + File file = new File(filename); + if (file.exists() && file.isDirectory()) { + return true; + } else { + return false; + } + } +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListener.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListener.java index 55493e7..a9b8edc 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListener.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListener.java @@ -1,45 +1,45 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.internal; - -import java.io.File; - -public interface ProgressListener { - - public void onMigrationBegin(); - - public void onDirectory(File file); - - public void onFileAddition(File file); - - public void onFileScanBegin(); - - public void onFileScan(File file); - - public void onInplaceConversion(File file); - - public void onDone(); - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.internal; + +import java.io.File; + +public interface ProgressListener { + + public void onMigrationBegin(); + + public void onDirectory(File file); + + public void onFileAddition(File file); + + public void onFileScanBegin(); + + public void onFileScan(File file); + + public void onInplaceConversion(File file); + + public void onDone(); + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListenerImpl.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListenerImpl.java index 754770e..8187e7e 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListenerImpl.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListenerImpl.java @@ -1,121 +1,121 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.internal; - -import java.io.File; -import java.io.IOException; - -import org.slf4j.migrator.helper.Abbreviator; - -public class ProgressListenerImpl implements ProgressListener { - - static final int TARGET_FILE_LENGTH = 85; - static final int UPDATE_THRESHOLD = 100; - - int addFileCount = 0; - int scanFileCount = 0; - int inplaceConversionCount = 0; - final MigratorFrame frame; - - Abbreviator abbr; - - long lastUpdate = 0; - - public ProgressListenerImpl(File projectFolder, MigratorFrame frame) { - this.frame = frame; - this.abbr = new Abbreviator((int) projectFolder.length(), TARGET_FILE_LENGTH, File.separatorChar); - } - - public void onMigrationBegin() { - frame.disableInput(); - } - - boolean isTooSoon() { - long now = System.currentTimeMillis(); - if (now - lastUpdate < UPDATE_THRESHOLD) { - return true; - } else { - lastUpdate = now; - return false; - } - } - - public void onDirectory(File file) { - if (isTooSoon()) - return; - - String abbreviatedName = getShortName(file); - frame.otherLabel.setText("

Searching folder [" + abbreviatedName + "]

Found " + addFileCount + " java files to scan."); - } - - public void onDone() { - frame.progressBar.setVisible(false); - frame.otherLabel.setText("Scanned " + addFileCount + " java files, " + inplaceConversionCount - + " files were modified."); - - frame.migrateButton.setActionCommand(MigratorFrame.EXIT_COMMAND); - frame.migrateButton.setText("Exit"); - frame.migrateButton.setToolTipText("Click on this button to exit this application."); - frame.migrateButton.setEnabled(true); - - } - - public void onFileAddition(File file) { - addFileCount++; - } - - public void onFileScan(File file) { - - scanFileCount++; - if (isTooSoon()) - return; - String abbreviatedName = getShortName(file); - - frame.otherLabel.setText("

Scanning file [" + abbreviatedName + "]

"); - // File + scanFileCount + " out of "+ addFileCount+" files to scan."+ - // inplaceConversionCount+ " files converted." + - - frame.progressBar.setValue(scanFileCount); - } - - public void onInplaceConversion(File file) { - inplaceConversionCount++; - } - - String getShortName(File file) { - try { - return abbr.abbreviate(file.getCanonicalPath()); - } catch (IOException e) { - return file.toString(); - } - } - - public void onFileScanBegin() { - frame.progressBar.setMaximum(addFileCount); - frame.progressBar.setValue(0); - frame.progressBar.setVisible(true); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.internal; + +import java.io.File; +import java.io.IOException; + +import org.slf4j.migrator.helper.Abbreviator; + +public class ProgressListenerImpl implements ProgressListener { + + static final int TARGET_FILE_LENGTH = 85; + static final int UPDATE_THRESHOLD = 100; + + int addFileCount = 0; + int scanFileCount = 0; + int inplaceConversionCount = 0; + final MigratorFrame frame; + + Abbreviator abbr; + + long lastUpdate = 0; + + public ProgressListenerImpl(File projectFolder, MigratorFrame frame) { + this.frame = frame; + this.abbr = new Abbreviator((int) projectFolder.length(), TARGET_FILE_LENGTH, File.separatorChar); + } + + public void onMigrationBegin() { + frame.disableInput(); + } + + boolean isTooSoon() { + long now = System.currentTimeMillis(); + if (now - lastUpdate < UPDATE_THRESHOLD) { + return true; + } else { + lastUpdate = now; + return false; + } + } + + public void onDirectory(File file) { + if (isTooSoon()) + return; + + String abbreviatedName = getShortName(file); + frame.otherLabel.setText("

Searching folder [" + abbreviatedName + "]

Found " + addFileCount + " java files to scan."); + } + + public void onDone() { + frame.progressBar.setVisible(false); + frame.otherLabel.setText("Scanned " + addFileCount + " java files, " + inplaceConversionCount + + " files were modified."); + + frame.migrateButton.setActionCommand(MigratorFrame.EXIT_COMMAND); + frame.migrateButton.setText("Exit"); + frame.migrateButton.setToolTipText("Click on this button to exit this application."); + frame.migrateButton.setEnabled(true); + + } + + public void onFileAddition(File file) { + addFileCount++; + } + + public void onFileScan(File file) { + + scanFileCount++; + if (isTooSoon()) + return; + String abbreviatedName = getShortName(file); + + frame.otherLabel.setText("

Scanning file [" + abbreviatedName + "]

"); + // File + scanFileCount + " out of "+ addFileCount+" files to scan."+ + // inplaceConversionCount+ " files converted." + + + frame.progressBar.setValue(scanFileCount); + } + + public void onInplaceConversion(File file) { + inplaceConversionCount++; + } + + String getShortName(File file) { + try { + return abbr.abbreviate(file.getCanonicalPath()); + } catch (IOException e) { + return file.toString(); + } + } + + public void onFileScanBegin() { + frame.progressBar.setMaximum(addFileCount); + frame.progressBar.setValue(0); + frame.progressBar.setVisible(true); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/ConversionRule.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/ConversionRule.java index 0d3e243..8330659 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/ConversionRule.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/ConversionRule.java @@ -1,51 +1,51 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public interface ConversionRule { - - public Pattern getPattern(); - - /** - * Given replacement rules, replace each capturing group in matcher's pattern - * - * @param matcher - * @return String - */ - public String replace(Matcher matcher); - - /** - * Returns a non-null value if there should be an additional line - * following a match of this rule. In most cases this method - * returns null. - * - * @return String - */ - public String getAdditionalLine(); - +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public interface ConversionRule { + + public Pattern getPattern(); + + /** + * Given replacement rules, replace each capturing group in matcher's pattern + * + * @param matcher + * @return String + */ + public String replace(Matcher matcher); + + /** + * Returns a non-null value if there should be an additional line + * following a match of this rule. In most cases this method + * returns null. + * + * @return String + */ + public String getAdditionalLine(); + }diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/EmptyRuleSet.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/EmptyRuleSet.java index f9a1686..a039326 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/EmptyRuleSet.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/EmptyRuleSet.java @@ -1,39 +1,39 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -public class EmptyRuleSet implements RuleSet { - - List list = new ArrayList(); - - public Iterator iterator() { - return list.iterator(); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class EmptyRuleSet implements RuleSet { + + List list = new ArrayList(); + + public Iterator iterator() { + return list.iterator(); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/JCLRuleSet.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/JCLRuleSet.java index 0a33284..f463e46 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/JCLRuleSet.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/JCLRuleSet.java @@ -1,69 +1,69 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.regex.Pattern; - -/** - * This class represents JCL to SLF4J conversion rules - * - * @author Jean-Noel Charpin - * - */ -public class JCLRuleSet implements RuleSet { - - private ArrayList conversionRuleList; - - public JCLRuleSet() { - // matching : import org.apache.commons.logging.LogFactory; - SingleConversionRule cr0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.LogFactory;"), - "import org.slf4j.LoggerFactory;"); - - // matching : import org.apache.commons.logging.Log; - SingleConversionRule cr1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.Log;"), "import org.slf4j.Logger;"); - - SingleConversionRule cr2 = new SingleConversionRule(Pattern.compile("(\\sLog\\b)"), " Logger"); - - SingleConversionRule cr3 = new SingleConversionRule(Pattern.compile("(^Log\\b)"), "Logger"); - - SingleConversionRule cr4 = new SingleConversionRule(Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("), "LoggerFactory.getLogger("); - - SingleConversionRule cr5 = new SingleConversionRule(Pattern.compile("LogFactory.getLog\\("), "LoggerFactory.getLogger("); - - conversionRuleList = new ArrayList(); - conversionRuleList.add(cr0); - conversionRuleList.add(cr1); - conversionRuleList.add(cr2); - conversionRuleList.add(cr3); - conversionRuleList.add(cr4); - conversionRuleList.add(cr5); - } - - public Iterator iterator() { - return conversionRuleList.iterator(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.regex.Pattern; + +/** + * This class represents JCL to SLF4J conversion rules + * + * @author Jean-Noel Charpin + * + */ +public class JCLRuleSet implements RuleSet { + + private ArrayList conversionRuleList; + + public JCLRuleSet() { + // matching : import org.apache.commons.logging.LogFactory; + SingleConversionRule cr0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.LogFactory;"), + "import org.slf4j.LoggerFactory;"); + + // matching : import org.apache.commons.logging.Log; + SingleConversionRule cr1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.Log;"), "import org.slf4j.Logger;"); + + SingleConversionRule cr2 = new SingleConversionRule(Pattern.compile("(\\sLog\\b)"), " Logger"); + + SingleConversionRule cr3 = new SingleConversionRule(Pattern.compile("(^Log\\b)"), "Logger"); + + SingleConversionRule cr4 = new SingleConversionRule(Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("), "LoggerFactory.getLogger("); + + SingleConversionRule cr5 = new SingleConversionRule(Pattern.compile("LogFactory.getLog\\("), "LoggerFactory.getLogger("); + + conversionRuleList = new ArrayList(); + conversionRuleList.add(cr0); + conversionRuleList.add(cr1); + conversionRuleList.add(cr2); + conversionRuleList.add(cr3); + conversionRuleList.add(cr4); + conversionRuleList.add(cr5); + } + + public Iterator iterator() { + return conversionRuleList.iterator(); + } +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/JULRuleSet.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/JULRuleSet.java index 1e17344..b296b70 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/JULRuleSet.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/JULRuleSet.java @@ -1,72 +1,72 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.regex.Pattern; - -/** - * This class represents java.util.logging (JUL) to SLF4J conversion rules - * - * @author Jean-Noel Charpin - * @author Ceki Gulcu - */ -public class JULRuleSet implements RuleSet { - - private ArrayList conversionRuleList; - - public JULRuleSet() { - - SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.Logger;"), "import org.slf4j.Logger;", - "import org.slf4j.LoggerFactory;"); - - SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;"); - - SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.*;"), "import org.slf4j.Logger;", - "import org.slf4j.LoggerFactory;"); - - SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger("); - - SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger("); - - SingleConversionRule crWarning = new SingleConversionRule(Pattern.compile("\\.warning\\("), ".warn("); - SingleConversionRule crSevere = new SingleConversionRule(Pattern.compile("\\.severe\\("), ".error("); - - conversionRuleList = new ArrayList(); - conversionRuleList.add(crImport0); - conversionRuleList.add(crImport1); - conversionRuleList.add(crImport2); - conversionRuleList.add(crFactory0); - conversionRuleList.add(crFactory1); - conversionRuleList.add(crWarning); - conversionRuleList.add(crSevere); - } - - public Iterator iterator() { - return conversionRuleList.iterator(); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.regex.Pattern; + +/** + * This class represents java.util.logging (JUL) to SLF4J conversion rules + * + * @author Jean-Noel Charpin + * @author Ceki Gulcu + */ +public class JULRuleSet implements RuleSet { + + private ArrayList conversionRuleList; + + public JULRuleSet() { + + SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.Logger;"), "import org.slf4j.Logger;", + "import org.slf4j.LoggerFactory;"); + + SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;"); + + SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.*;"), "import org.slf4j.Logger;", + "import org.slf4j.LoggerFactory;"); + + SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger("); + + SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger("); + + SingleConversionRule crWarning = new SingleConversionRule(Pattern.compile("\\.warning\\("), ".warn("); + SingleConversionRule crSevere = new SingleConversionRule(Pattern.compile("\\.severe\\("), ".error("); + + conversionRuleList = new ArrayList(); + conversionRuleList.add(crImport0); + conversionRuleList.add(crImport1); + conversionRuleList.add(crImport2); + conversionRuleList.add(crFactory0); + conversionRuleList.add(crFactory1); + conversionRuleList.add(crWarning); + conversionRuleList.add(crSevere); + } + + public Iterator iterator() { + return conversionRuleList.iterator(); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/LineConverter.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/LineConverter.java index f45bda9..850349f 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/LineConverter.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/LineConverter.java @@ -1,91 +1,91 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class LineConverter { - - final RuleSet ruleSet; - boolean atLeastOneMatchOccured = false; - - public LineConverter(RuleSet ruleSet) { - this.ruleSet = ruleSet; - } - - /** - * Check if the specified text is matching some conversions rules. - * If a rule matches, ask for line replacement. - * - *

In case no rule can be applied, then the input text is - * returned without change. - * - * @param text - * @return String - */ - public String[] getReplacement(String text) { - ConversionRule conversionRule; - Pattern pattern; - Matcher matcher; - Iterator conversionRuleIterator = ruleSet.iterator(); - String additionalLine = null; - while (conversionRuleIterator.hasNext()) { - conversionRule = conversionRuleIterator.next(); - pattern = conversionRule.getPattern(); - matcher = pattern.matcher(text); - if (matcher.find()) { - // System.out.println("matching " + text); - atLeastOneMatchOccured = true; - String replacementText = conversionRule.replace(matcher); - text = matcher.replaceAll(replacementText); - if (conversionRule.getAdditionalLine() != null) { - additionalLine = conversionRule.getAdditionalLine(); - } - } - } - - if (additionalLine == null) { - return new String[] { text }; - } else { - return new String[] { text, additionalLine }; - } - } - - public String getOneLineReplacement(String text) { - String[] r = getReplacement(text); - if (r.length != 1) { - throw new IllegalStateException("Expecting a single string but got " + Arrays.toString(r)); - } else { - return r[0]; - } - } - - public boolean atLeastOneMatchOccured() { - return atLeastOneMatchOccured; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class LineConverter { + + final RuleSet ruleSet; + boolean atLeastOneMatchOccured = false; + + public LineConverter(RuleSet ruleSet) { + this.ruleSet = ruleSet; + } + + /** + * Check if the specified text is matching some conversions rules. + * If a rule matches, ask for line replacement. + * + *

In case no rule can be applied, then the input text is + * returned without change. + * + * @param text + * @return String + */ + public String[] getReplacement(String text) { + ConversionRule conversionRule; + Pattern pattern; + Matcher matcher; + Iterator conversionRuleIterator = ruleSet.iterator(); + String additionalLine = null; + while (conversionRuleIterator.hasNext()) { + conversionRule = conversionRuleIterator.next(); + pattern = conversionRule.getPattern(); + matcher = pattern.matcher(text); + if (matcher.find()) { + // System.out.println("matching " + text); + atLeastOneMatchOccured = true; + String replacementText = conversionRule.replace(matcher); + text = matcher.replaceAll(replacementText); + if (conversionRule.getAdditionalLine() != null) { + additionalLine = conversionRule.getAdditionalLine(); + } + } + } + + if (additionalLine == null) { + return new String[] { text }; + } else { + return new String[] { text, additionalLine }; + } + } + + public String getOneLineReplacement(String text) { + String[] r = getReplacement(text); + if (r.length != 1) { + throw new IllegalStateException("Expecting a single string but got " + Arrays.toString(r)); + } else { + return r[0]; + } + } + + public boolean atLeastOneMatchOccured() { + return atLeastOneMatchOccured; + } +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/Log4jRuleSet.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/Log4jRuleSet.java old file mode 100644 new file mode 100755 index 4dbaf7c..c760496 100755 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/Log4jRuleSet.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/Log4jRuleSet.java @@ -1,78 +1,78 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.regex.Pattern; - -public class Log4jRuleSet implements RuleSet { - - private ArrayList conversionRuleList; - - public Log4jRuleSet() { - - SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Logger;"), "import org.slf4j.Logger;", - "import org.slf4j.LoggerFactory;"); - - SingleConversionRule catImport = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Category;"), "import org.slf4j.Logger;", - "import org.slf4j.LoggerFactory;"); - - SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;"); - - SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.*;"), "import org.slf4j.Logger;", - "import org.slf4j.LoggerFactory;"); - - SingleConversionRule crImportMDC = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.MDC;"), "import org.slf4j.MDC;"); - - SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger("); - - SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("\\sCategory.getInstance\\("), " LoggerFactory.getLogger("); - - SingleConversionRule crFactory2 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger("); - - SingleConversionRule variable0 = new SingleConversionRule(Pattern.compile("(\\sCategory\\b)"), " Logger"); - - SingleConversionRule variable1 = new SingleConversionRule(Pattern.compile("(^Category\\b)"), "Logger"); - - conversionRuleList = new ArrayList(); - conversionRuleList.add(crImport0); - conversionRuleList.add(catImport); - conversionRuleList.add(crImport1); - conversionRuleList.add(crImport2); - conversionRuleList.add(crImportMDC); - conversionRuleList.add(crFactory0); - conversionRuleList.add(crFactory1); - conversionRuleList.add(crFactory2); - - conversionRuleList.add(variable0); - conversionRuleList.add(variable1); - } - - public Iterator iterator() { - return conversionRuleList.iterator(); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.regex.Pattern; + +public class Log4jRuleSet implements RuleSet { + + private ArrayList conversionRuleList; + + public Log4jRuleSet() { + + SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Logger;"), "import org.slf4j.Logger;", + "import org.slf4j.LoggerFactory;"); + + SingleConversionRule catImport = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Category;"), "import org.slf4j.Logger;", + "import org.slf4j.LoggerFactory;"); + + SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;"); + + SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.*;"), "import org.slf4j.Logger;", + "import org.slf4j.LoggerFactory;"); + + SingleConversionRule crImportMDC = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.MDC;"), "import org.slf4j.MDC;"); + + SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger("); + + SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("\\sCategory.getInstance\\("), " LoggerFactory.getLogger("); + + SingleConversionRule crFactory2 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger("); + + SingleConversionRule variable0 = new SingleConversionRule(Pattern.compile("(\\sCategory\\b)"), " Logger"); + + SingleConversionRule variable1 = new SingleConversionRule(Pattern.compile("(^Category\\b)"), "Logger"); + + conversionRuleList = new ArrayList(); + conversionRuleList.add(crImport0); + conversionRuleList.add(catImport); + conversionRuleList.add(crImport1); + conversionRuleList.add(crImport2); + conversionRuleList.add(crImportMDC); + conversionRuleList.add(crFactory0); + conversionRuleList.add(crFactory1); + conversionRuleList.add(crFactory2); + + conversionRuleList.add(variable0); + conversionRuleList.add(variable1); + } + + public Iterator iterator() { + return conversionRuleList.iterator(); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java index ce208c1..ce1ee52 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java @@ -1,100 +1,100 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * This class represents a conversion rule It uses a Pattern and defines for - * each capturing group of this Pattern a replacement text - * - * @author jean-noelcharpin - * - */ -public class MultiGroupConversionRule implements ConversionRule { - - // It is extremely unlikely to encounter more than 10 groups in one of - // our conversion reg-expressions - final private static int MAX_GROUPS = 10; - - private Pattern pattern; - private String[] replacementTable = new String[MAX_GROUPS]; - - public MultiGroupConversionRule(Pattern pattern) { - this.pattern = pattern; - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.converter.ConversionRule#getPattern() - */ - public Pattern getPattern() { - return pattern; - } - - public void addReplacement(int groupIndex, String replacement) { - if (groupIndex == 0) { - throw new IllegalArgumentException("regex groups start at 1, not zero"); - } - replacementTable[groupIndex] = replacement; - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.converter.ConversionRule#getReplacement(java.lang.Integer) - */ - public String getReplacement(int groupIndex) { - return replacementTable[groupIndex]; - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher) - */ - public String replace(Matcher matcher) { - StringBuilder replacementBuffer = new StringBuilder(); - String replacementText; - - for (int group = 1; group <= matcher.groupCount(); group++) { - replacementText = getReplacement(group); - if (replacementText != null) { - // System.out.println("replacing group " + group + " : " - // + matcher.group(group) + " with " + replacementText); - replacementBuffer.append(replacementText); - } else { - replacementBuffer.append(matcher.group(group)); - } - } - return replacementBuffer.toString(); - } - - public String getAdditionalLine() { - return null; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * This class represents a conversion rule It uses a Pattern and defines for + * each capturing group of this Pattern a replacement text + * + * @author jean-noelcharpin + * + */ +public class MultiGroupConversionRule implements ConversionRule { + + // It is extremely unlikely to encounter more than 10 groups in one of + // our conversion reg-expressions + final private static int MAX_GROUPS = 10; + + private Pattern pattern; + private String[] replacementTable = new String[MAX_GROUPS]; + + public MultiGroupConversionRule(Pattern pattern) { + this.pattern = pattern; + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.converter.ConversionRule#getPattern() + */ + public Pattern getPattern() { + return pattern; + } + + public void addReplacement(int groupIndex, String replacement) { + if (groupIndex == 0) { + throw new IllegalArgumentException("regex groups start at 1, not zero"); + } + replacementTable[groupIndex] = replacement; + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.converter.ConversionRule#getReplacement(java.lang.Integer) + */ + public String getReplacement(int groupIndex) { + return replacementTable[groupIndex]; + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher) + */ + public String replace(Matcher matcher) { + StringBuilder replacementBuffer = new StringBuilder(); + String replacementText; + + for (int group = 1; group <= matcher.groupCount(); group++) { + replacementText = getReplacement(group); + if (replacementText != null) { + // System.out.println("replacing group " + group + " : " + // + matcher.group(group) + " with " + replacementText); + replacementBuffer.append(replacementText); + } else { + replacementBuffer.append(matcher.group(group)); + } + } + return replacementBuffer.toString(); + } + + public String getAdditionalLine() { + return null; + } +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/RuleSet.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/RuleSet.java index 3e96bc1..6c5bf37 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/RuleSet.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/RuleSet.java @@ -1,33 +1,33 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.Iterator; - -public interface RuleSet { - - Iterator iterator(); - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.Iterator; + +public interface RuleSet { + + Iterator iterator(); + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/SingleConversionRule.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/SingleConversionRule.java index 3be2313..d6b0a5d 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/SingleConversionRule.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/SingleConversionRule.java @@ -1,75 +1,75 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * This class represents a conversion rule It uses a Pattern and defines for - * each capturing group of this Pattern a replacement text - * - * @author jean-noelcharpin - * - */ -public class SingleConversionRule implements ConversionRule { - - final private Pattern pattern; - final private String replacementText; - final private String additionalLine; - - public SingleConversionRule(Pattern pattern, String replacementText) { - this(pattern, replacementText, null); - } - - public SingleConversionRule(Pattern pattern, String replacementText, String additionalLine) { - this.pattern = pattern; - this.replacementText = replacementText; - this.additionalLine = additionalLine; - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.converter.ConversionRule#getPattern() - */ - public Pattern getPattern() { - return pattern; - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher) - */ - public String replace(Matcher matcher) { - return replacementText; - } - - public String getAdditionalLine() { - return additionalLine; - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * This class represents a conversion rule It uses a Pattern and defines for + * each capturing group of this Pattern a replacement text + * + * @author jean-noelcharpin + * + */ +public class SingleConversionRule implements ConversionRule { + + final private Pattern pattern; + final private String replacementText; + final private String additionalLine; + + public SingleConversionRule(Pattern pattern, String replacementText) { + this(pattern, replacementText, null); + } + + public SingleConversionRule(Pattern pattern, String replacementText, String additionalLine) { + this.pattern = pattern; + this.replacementText = replacementText; + this.additionalLine = additionalLine; + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.converter.ConversionRule#getPattern() + */ + public Pattern getPattern() { + return pattern; + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher) + */ + public String replace(Matcher matcher) { + return replacementText; + } + + public String getAdditionalLine() { + return additionalLine; + } + +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/AllTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/AllTest.java old file mode 100644 new file mode 100755 index 229e864..9473b65 100755 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/AllTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/AllTest.java @@ -1,35 +1,35 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ org.slf4j.migrator.PackageTest.class, org.slf4j.migrator.line.PackageTest.class, org.slf4j.migrator.helper.PackageTest.class }) -public class AllTest { - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ org.slf4j.migrator.PackageTest.class, org.slf4j.migrator.line.PackageTest.class, org.slf4j.migrator.helper.PackageTest.class }) +public class AllTest { + +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/AternativeApproach.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/AternativeApproach.java index e5aa2bc..d530a6c 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/AternativeApproach.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/AternativeApproach.java @@ -1,154 +1,154 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.slf4j.migrator.line.MultiGroupConversionRule; - -import junit.framework.TestCase; - -public class AternativeApproach extends TestCase { - - /** - * In this test we see that we cans use more simple Pattern to do the - * conversion - * - */ - public void test() { - MultiGroupConversionRule cr2 = new MultiGroupConversionRule(Pattern.compile("(.*)(Log)")); - cr2.addReplacement(2, "LOGGER"); - - String s = "abcd Log"; - Pattern pat = cr2.getPattern(); - Matcher m = pat.matcher(s); - - assertTrue(m.matches()); - String r = cr2.replace(m); - assertEquals("abcd LOGGER", r); - - System.out.println(r); - } - - /** - * In this test we replace, using the simple Pattern (Log), the full Log - * declaration and instantiation. This is not convenient because we will also - * replace all String containing "Log". - */ - public void test2() { - Pattern pat = Pattern.compile("(Log)"); - String s = "abcd Log ="; - Matcher m = pat.matcher(s); - assertTrue(m.find()); - String r = m.replaceAll("Logger"); - assertEquals("abcd Logger =", r); - - String s1 = "Log l = LogFactory.getLog(MyClass.class);"; - m = pat.matcher(s1); - assertTrue(m.find()); - r = m.replaceAll("Logger"); - assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", r); - - String s2 = "Logabc "; - m = pat.matcher(s2); - assertTrue(m.find()); - - String s3 = "abcLog"; - m = pat.matcher(s3); - assertTrue(m.find()); - } - - /** - * In this test we use a simple Pattern to replace the log instantiation - * without influence on Log declaration. - * - */ - public void test3() { - Pattern pat = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("); - String s = "Log log = LogFactory.getFactory().getInstance(\"x\");"; - Matcher m = pat.matcher(s); - assertTrue(m.find()); - String r = m.replaceAll("LoggerFactory.getLogger("); - assertEquals("Log log = LoggerFactory.getLogger(\"x\");", r); - - String nonMatching = "Log log = xxx;"; - pat.matcher(nonMatching); - assertFalse(m.find()); - } - - /** - * In this test we try to replace keyword Log without influence on String - * containing Log We see that we have to use two different Patterns - */ - public void test4() { - Pattern pat = Pattern.compile("(\\sLog\\b)"); - String s = "abcd Log ="; - Matcher m = pat.matcher(s); - assertTrue(m.find()); - String r = m.replaceAll(" Logger"); - assertEquals("abcd Logger =", r); - - String s2 = "Logabcd "; - m = pat.matcher(s2); - assertFalse(m.find()); - - String s3 = "abcdLogabcd "; - m = pat.matcher(s3); - assertFalse(m.find()); - - String s4 = "abcdLog"; - m = pat.matcher(s4); - assertFalse(m.find()); - - String s5 = "Log myLog"; - m = pat.matcher(s5); - assertFalse(m.find()); - - Pattern pat2 = Pattern.compile("^Log\\b"); - Matcher m2 = pat2.matcher(s5); - assertTrue(m2.find()); - r = m2.replaceAll("Logger"); - assertEquals("Logger myLog", r); - } - - /** - * In this test we combine two Pattern to achieve the intended conversion - */ - public void test5() { - Pattern pat = Pattern.compile("(\\sLog\\b)"); - String s = "public Log myLog =LogFactory.getFactory().getInstance(myClass.class);"; - Matcher m = pat.matcher(s); - assertTrue(m.find()); - String r = m.replaceAll(" Logger"); - assertEquals("public Logger myLog =LogFactory.getFactory().getInstance(myClass.class);", r); - - Pattern pat2 = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("); - m = pat2.matcher(r); - assertTrue(m.find()); - r = m.replaceAll("LoggerFactory.getLogger("); - assertEquals("public Logger myLog =LoggerFactory.getLogger(myClass.class);", r); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.slf4j.migrator.line.MultiGroupConversionRule; + +import junit.framework.TestCase; + +public class AternativeApproach extends TestCase { + + /** + * In this test we see that we cans use more simple Pattern to do the + * conversion + * + */ + public void test() { + MultiGroupConversionRule cr2 = new MultiGroupConversionRule(Pattern.compile("(.*)(Log)")); + cr2.addReplacement(2, "LOGGER"); + + String s = "abcd Log"; + Pattern pat = cr2.getPattern(); + Matcher m = pat.matcher(s); + + assertTrue(m.matches()); + String r = cr2.replace(m); + assertEquals("abcd LOGGER", r); + + System.out.println(r); + } + + /** + * In this test we replace, using the simple Pattern (Log), the full Log + * declaration and instantiation. This is not convenient because we will also + * replace all String containing "Log". + */ + public void test2() { + Pattern pat = Pattern.compile("(Log)"); + String s = "abcd Log ="; + Matcher m = pat.matcher(s); + assertTrue(m.find()); + String r = m.replaceAll("Logger"); + assertEquals("abcd Logger =", r); + + String s1 = "Log l = LogFactory.getLog(MyClass.class);"; + m = pat.matcher(s1); + assertTrue(m.find()); + r = m.replaceAll("Logger"); + assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", r); + + String s2 = "Logabc "; + m = pat.matcher(s2); + assertTrue(m.find()); + + String s3 = "abcLog"; + m = pat.matcher(s3); + assertTrue(m.find()); + } + + /** + * In this test we use a simple Pattern to replace the log instantiation + * without influence on Log declaration. + * + */ + public void test3() { + Pattern pat = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("); + String s = "Log log = LogFactory.getFactory().getInstance(\"x\");"; + Matcher m = pat.matcher(s); + assertTrue(m.find()); + String r = m.replaceAll("LoggerFactory.getLogger("); + assertEquals("Log log = LoggerFactory.getLogger(\"x\");", r); + + String nonMatching = "Log log = xxx;"; + pat.matcher(nonMatching); + assertFalse(m.find()); + } + + /** + * In this test we try to replace keyword Log without influence on String + * containing Log We see that we have to use two different Patterns + */ + public void test4() { + Pattern pat = Pattern.compile("(\\sLog\\b)"); + String s = "abcd Log ="; + Matcher m = pat.matcher(s); + assertTrue(m.find()); + String r = m.replaceAll(" Logger"); + assertEquals("abcd Logger =", r); + + String s2 = "Logabcd "; + m = pat.matcher(s2); + assertFalse(m.find()); + + String s3 = "abcdLogabcd "; + m = pat.matcher(s3); + assertFalse(m.find()); + + String s4 = "abcdLog"; + m = pat.matcher(s4); + assertFalse(m.find()); + + String s5 = "Log myLog"; + m = pat.matcher(s5); + assertFalse(m.find()); + + Pattern pat2 = Pattern.compile("^Log\\b"); + Matcher m2 = pat2.matcher(s5); + assertTrue(m2.find()); + r = m2.replaceAll("Logger"); + assertEquals("Logger myLog", r); + } + + /** + * In this test we combine two Pattern to achieve the intended conversion + */ + public void test5() { + Pattern pat = Pattern.compile("(\\sLog\\b)"); + String s = "public Log myLog =LogFactory.getFactory().getInstance(myClass.class);"; + Matcher m = pat.matcher(s); + assertTrue(m.find()); + String r = m.replaceAll(" Logger"); + assertEquals("public Logger myLog =LogFactory.getFactory().getInstance(myClass.class);", r); + + Pattern pat2 = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("); + m = pat2.matcher(r); + assertTrue(m.find()); + r = m.replaceAll("LoggerFactory.getLogger("); + assertEquals("public Logger myLog =LoggerFactory.getLogger(myClass.class);", r); + } +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/FileConverterTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/FileConverterTest.java index 4db2002..4e1b138 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/FileConverterTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/FileConverterTest.java @@ -1,43 +1,43 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -import java.io.File; -import java.io.IOException; - -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.migrator.internal.NopProgressListener; -import org.slf4j.migrator.line.EmptyRuleSet; - -public class FileConverterTest { - - @Test - @Ignore - public void XtestNOP() throws IOException { - InplaceFileConverter fc = new InplaceFileConverter(new EmptyRuleSet(), new NopProgressListener()); - fc.convert(new File("c:/varargs.txt")); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +import java.io.File; +import java.io.IOException; + +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.migrator.internal.NopProgressListener; +import org.slf4j.migrator.line.EmptyRuleSet; + +public class FileConverterTest { + + @Test + @Ignore + public void XtestNOP() throws IOException { + InplaceFileConverter fc = new InplaceFileConverter(new EmptyRuleSet(), new NopProgressListener()); + fc.convert(new File("c:/varargs.txt")); + } +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/PackageTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/PackageTest.java old file mode 100644 new file mode 100755 index 9e2cd2f..dfb6af8 100755 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/PackageTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/PackageTest.java @@ -1,34 +1,34 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ AternativeApproach.class }) -public class PackageTest { -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ AternativeApproach.class }) +public class PackageTest { +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/ProjectConverterTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/ProjectConverterTest.java index 1bf1905..537ba3f 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/ProjectConverterTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/ProjectConverterTest.java @@ -1,45 +1,45 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator; - -import java.io.File; - -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.migrator.internal.NopProgressListener; - -public class ProjectConverterTest { - - public void test() { - } - - @Test - @Ignore - public void XtestBarracuda() { - ProjectConverter pc = new ProjectConverter(Constant.LOG4J_TO_SLF4J, new NopProgressListener()); - File projectFolder = new File("c:/home/ceki//Varia/Barracuda"); - pc.convertProject(projectFolder); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator; + +import java.io.File; + +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.migrator.internal.NopProgressListener; + +public class ProjectConverterTest { + + public void test() { + } + + @Test + @Ignore + public void XtestBarracuda() { + ProjectConverter pc = new ProjectConverter(Constant.LOG4J_TO_SLF4J, new NopProgressListener()); + File projectFolder = new File("c:/home/ceki//Varia/Barracuda"); + pc.convertProject(projectFolder); + } +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/AbbreviatorTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/AbbreviatorTest.java index 9f24df5..ac470b8 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/AbbreviatorTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/AbbreviatorTest.java @@ -1,152 +1,152 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.helper; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class AbbreviatorTest { - - static final char FS = '/'; - static final String INPUT_0 = "/abc/123456/ABC"; - static final String INPUT_1 = "/abc/123456/xxxxx/ABC"; - - RandomHelper rh = new RandomHelper(FS); - - @Test - public void testSmoke() { - { - Abbreviator abb = new Abbreviator(2, 100, FS); - String r = abb.abbreviate(INPUT_0); - assertEquals(INPUT_0, r); - } - - { - Abbreviator abb = new Abbreviator(3, 8, FS); - String r = abb.abbreviate(INPUT_0); - assertEquals("/abc/.../ABC", r); - } - { - Abbreviator abb = new Abbreviator(3, 8, FS); - String r = abb.abbreviate(INPUT_0); - assertEquals("/abc/.../ABC", r); - } - } - - @Test - public void testImpossibleToAbbreviate() { - Abbreviator abb = new Abbreviator(2, 20, FS); - String in = "iczldqwivpgm/mgrmvbjdxrwmqgprdjusth"; - String r = abb.abbreviate(in); - assertEquals(in, r); - } - - @Test - public void testNoFS() { - Abbreviator abb = new Abbreviator(2, 100, FS); - String r = abb.abbreviate("hello"); - assertEquals("hello", r); - - } - - @Test - public void testZeroPrefix() { - { - Abbreviator abb = new Abbreviator(0, 100, FS); - String r = abb.abbreviate(INPUT_0); - assertEquals(INPUT_0, r); - } - } - - @Test - public void testTheories() { - int MAX_RANDOM_FIXED_LEN = 20; - int MAX_RANDOM_AVG_LEN = 20; - int MAX_RANDOM_MAX_LEN = 100; - for (int i = 0; i < 10000; i++) { - - // System.out.println("Test number " + i); - - // 0 <= fixedLen < MAX_RANDOM_FIXED_LEN - int fixedLen = rh.nextInt(MAX_RANDOM_FIXED_LEN); - // 5 <= averageLen < MAX_RANDOM_AVG_LEN - int averageLen = rh.nextInt(MAX_RANDOM_AVG_LEN) + 3; - // System.out.println("fixedLen="+fixedLen+", averageLen="+averageLen); - - int maxLen = rh.nextInt(MAX_RANDOM_MAX_LEN) + fixedLen; - if (maxLen <= 1) { - continue; - } - // System.out.println("maxLen="+maxLen); - int targetLen = (maxLen / 2) + rh.nextInt(maxLen / 2) + 1; - - if (targetLen > maxLen) { - targetLen = maxLen; - } - String filename = rh.buildRandomFileName(averageLen, maxLen); - - Abbreviator abb = new Abbreviator(fixedLen, targetLen, FS); - String result = abb.abbreviate(filename); - assertTheory0(averageLen, filename, result, fixedLen, targetLen); - assertUsefulness(averageLen, filename, result, fixedLen, targetLen); - assertTheory1(filename, result, fixedLen, targetLen); - assertTheory2(filename, result, fixedLen, targetLen); - } - } - - // result length is smaller than original length - void assertTheory0(int averageLen, String filename, String result, int fixedLen, int targetLength) { - assertTrue("filename=[" + filename + "] result=[" + result + "]", result.length() <= filename.length()); - } - - // if conditions allow, result length should be to target length - void assertUsefulness(int averageLen, String filename, String result, int fixedLen, int targetLength) { - int resLen = result.length(); - - int margin = averageLen * 4; - if (targetLength > fixedLen + margin) { - assertTrue("filename=[" + filename + "], result=[" + result + "] resultLength=" + resLen + " fixedLength=" + fixedLen + ", targetLength=" - + targetLength + ", avgLen=" + averageLen, result.length() <= targetLength + averageLen); - } - } - - // result start with prefix found in filename - void assertTheory1(String filename, String result, int fixedLen, int targetLength) { - String prefix = filename.substring(0, fixedLen); - assertTrue(result.startsWith(prefix)); - } - - // The string /.../ is found in the result once at a position higher - // than fixedLen - void assertTheory2(String filename, String result, int fixedLen, int targetLength) { - if (filename == result) { - return; - } - int fillerIndex = result.indexOf(Abbreviator.FILLER); - assertTrue(fillerIndex >= fixedLen); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.helper; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class AbbreviatorTest { + + static final char FS = '/'; + static final String INPUT_0 = "/abc/123456/ABC"; + static final String INPUT_1 = "/abc/123456/xxxxx/ABC"; + + RandomHelper rh = new RandomHelper(FS); + + @Test + public void testSmoke() { + { + Abbreviator abb = new Abbreviator(2, 100, FS); + String r = abb.abbreviate(INPUT_0); + assertEquals(INPUT_0, r); + } + + { + Abbreviator abb = new Abbreviator(3, 8, FS); + String r = abb.abbreviate(INPUT_0); + assertEquals("/abc/.../ABC", r); + } + { + Abbreviator abb = new Abbreviator(3, 8, FS); + String r = abb.abbreviate(INPUT_0); + assertEquals("/abc/.../ABC", r); + } + } + + @Test + public void testImpossibleToAbbreviate() { + Abbreviator abb = new Abbreviator(2, 20, FS); + String in = "iczldqwivpgm/mgrmvbjdxrwmqgprdjusth"; + String r = abb.abbreviate(in); + assertEquals(in, r); + } + + @Test + public void testNoFS() { + Abbreviator abb = new Abbreviator(2, 100, FS); + String r = abb.abbreviate("hello"); + assertEquals("hello", r); + + } + + @Test + public void testZeroPrefix() { + { + Abbreviator abb = new Abbreviator(0, 100, FS); + String r = abb.abbreviate(INPUT_0); + assertEquals(INPUT_0, r); + } + } + + @Test + public void testTheories() { + int MAX_RANDOM_FIXED_LEN = 20; + int MAX_RANDOM_AVG_LEN = 20; + int MAX_RANDOM_MAX_LEN = 100; + for (int i = 0; i < 10000; i++) { + + // System.out.println("Test number " + i); + + // 0 <= fixedLen < MAX_RANDOM_FIXED_LEN + int fixedLen = rh.nextInt(MAX_RANDOM_FIXED_LEN); + // 5 <= averageLen < MAX_RANDOM_AVG_LEN + int averageLen = rh.nextInt(MAX_RANDOM_AVG_LEN) + 3; + // System.out.println("fixedLen="+fixedLen+", averageLen="+averageLen); + + int maxLen = rh.nextInt(MAX_RANDOM_MAX_LEN) + fixedLen; + if (maxLen <= 1) { + continue; + } + // System.out.println("maxLen="+maxLen); + int targetLen = (maxLen / 2) + rh.nextInt(maxLen / 2) + 1; + + if (targetLen > maxLen) { + targetLen = maxLen; + } + String filename = rh.buildRandomFileName(averageLen, maxLen); + + Abbreviator abb = new Abbreviator(fixedLen, targetLen, FS); + String result = abb.abbreviate(filename); + assertTheory0(averageLen, filename, result, fixedLen, targetLen); + assertUsefulness(averageLen, filename, result, fixedLen, targetLen); + assertTheory1(filename, result, fixedLen, targetLen); + assertTheory2(filename, result, fixedLen, targetLen); + } + } + + // result length is smaller than original length + void assertTheory0(int averageLen, String filename, String result, int fixedLen, int targetLength) { + assertTrue("filename=[" + filename + "] result=[" + result + "]", result.length() <= filename.length()); + } + + // if conditions allow, result length should be to target length + void assertUsefulness(int averageLen, String filename, String result, int fixedLen, int targetLength) { + int resLen = result.length(); + + int margin = averageLen * 4; + if (targetLength > fixedLen + margin) { + assertTrue("filename=[" + filename + "], result=[" + result + "] resultLength=" + resLen + " fixedLength=" + fixedLen + ", targetLength=" + + targetLength + ", avgLen=" + averageLen, result.length() <= targetLength + averageLen); + } + } + + // result start with prefix found in filename + void assertTheory1(String filename, String result, int fixedLen, int targetLength) { + String prefix = filename.substring(0, fixedLen); + assertTrue(result.startsWith(prefix)); + } + + // The string /.../ is found in the result once at a position higher + // than fixedLen + void assertTheory2(String filename, String result, int fixedLen, int targetLength) { + if (filename == result) { + return; + } + int fillerIndex = result.indexOf(Abbreviator.FILLER); + assertTrue(fillerIndex >= fixedLen); + } +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/PackageTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/PackageTest.java old file mode 100644 new file mode 100755 index a010a98..e72304f 100755 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/PackageTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/PackageTest.java @@ -1,34 +1,34 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.helper; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ AbbreviatorTest.class }) -public class PackageTest { -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.helper; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ AbbreviatorTest.class }) +public class PackageTest { +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/RandomHelper.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/RandomHelper.java index ddab0bc..1928daa 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/RandomHelper.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/RandomHelper.java @@ -1,70 +1,70 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.helper; - -import java.util.Random; - -public class RandomHelper { - - private Random random = new Random(100); - final char folderSeparator; - - RandomHelper(char folderSeparator) { - this.folderSeparator = folderSeparator; - } - - private String randomString(int len) { - StringBuilder buf = new StringBuilder(); - for (int i = 0; i < len; i++) { - int offset = random.nextInt(26); - char c = (char) ('a' + offset); - buf.append(c); - } - return buf.toString(); - } - - int nextInt(int n) { - return random.nextInt(n); - } - - String buildRandomFileName(int averageNodeLength, int totalLength) { - StringBuilder buf = new StringBuilder(); - int MAX_NODE_LENGTH = averageNodeLength * 2; - while (buf.length() < totalLength) { - int remaining = totalLength - buf.length(); - int currentNodeLength; - if (remaining > MAX_NODE_LENGTH) { - currentNodeLength = random.nextInt(MAX_NODE_LENGTH) + 1; - buf.append(randomString(currentNodeLength)); - buf.append('/'); - } else { - currentNodeLength = remaining; - buf.append(randomString(currentNodeLength)); - } - } - return buf.toString(); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.helper; + +import java.util.Random; + +public class RandomHelper { + + private Random random = new Random(100); + final char folderSeparator; + + RandomHelper(char folderSeparator) { + this.folderSeparator = folderSeparator; + } + + private String randomString(int len) { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < len; i++) { + int offset = random.nextInt(26); + char c = (char) ('a' + offset); + buf.append(c); + } + return buf.toString(); + } + + int nextInt(int n) { + return random.nextInt(n); + } + + String buildRandomFileName(int averageNodeLength, int totalLength) { + StringBuilder buf = new StringBuilder(); + int MAX_NODE_LENGTH = averageNodeLength * 2; + while (buf.length() < totalLength) { + int remaining = totalLength - buf.length(); + int currentNodeLength; + if (remaining > MAX_NODE_LENGTH) { + currentNodeLength = random.nextInt(MAX_NODE_LENGTH) + 1; + buf.append(randomString(currentNodeLength)); + buf.append('/'); + } else { + currentNodeLength = remaining; + buf.append(randomString(currentNodeLength)); + } + } + return buf.toString(); + } + +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/internal/NopProgressListener.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/internal/NopProgressListener.java index 8b92b6a..08686ed 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/internal/NopProgressListener.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/internal/NopProgressListener.java @@ -1,54 +1,54 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.internal; - -import java.io.File; - -import org.slf4j.migrator.internal.ProgressListener; - -public class NopProgressListener implements ProgressListener { - - public void onDirectory(File file) { - } - - public void onDone() { - } - - public void onFileAddition(File file) { - } - - public void onFileScan(File file) { - } - - public void onInplaceConversion(File file) { - } - - public void onFileScanBegin() { - } - - public void onMigrationBegin() { - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.internal; + +import java.io.File; + +import org.slf4j.migrator.internal.ProgressListener; + +public class NopProgressListener implements ProgressListener { + + public void onDirectory(File file) { + } + + public void onDone() { + } + + public void onFileAddition(File file) { + } + + public void onFileScan(File file) { + } + + public void onInplaceConversion(File file) { + } + + public void onFileScanBegin() { + } + + public void onMigrationBegin() { + } + +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/JCLRuleSetTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/JCLRuleSetTest.java index 6282b91..f480229 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/JCLRuleSetTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/JCLRuleSetTest.java @@ -1,125 +1,125 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class JCLRuleSetTest { - - LineConverter jclConverter = new LineConverter(new JCLRuleSet()); - - @Test - public void testImportReplacement() { - // LogFactory import replacement - assertEquals("import org.slf4j.LoggerFactory;", jclConverter.getOneLineReplacement("import org.apache.commons.logging.LogFactory;")); - // Log import replacement - assertEquals("import org.slf4j.Logger;", jclConverter.getOneLineReplacement("import org.apache.commons.logging.Log;")); - } - - @Test - public void testLogFactoryGetLogReplacement() { - // Logger declaration and instanciation without modifier - assertEquals(" Logger l = LoggerFactory.getLogger(MyClass.class);", - jclConverter.getOneLineReplacement(" Log l = LogFactory.getLog(MyClass.class);")); - // Logger declaration and instanciation with one modifier - assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);", - jclConverter.getOneLineReplacement("public Log mylog=LogFactory.getLog(MyClass.class);")); - // Logger declaration and instanciation with two modifier - assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", - jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class);")); - // Logger declaration and instanciation with two modifier and comment at the - // end of line - assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); //logger instanciation and declaration", - jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class); //logger instanciation and declaration")); - // Logger instanciation without declaration and comment at the end of line - assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", - jclConverter.getOneLineReplacement(" myLog = LogFactory.getLog(MyClass.class);//logger instanciation")); - // commented Logger declaration and instanciation with two modifier - assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", - jclConverter.getOneLineReplacement("//public static Log mylog1 = LogFactory.getLog(MyClass.class);")); - // commented Logger instanciation without declaration - assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", - jclConverter.getOneLineReplacement("// myLog = LogFactory.getLog(MyClass.class);//logger instanciation")); - } - - @Test - public void testLogFactoryGetFactoryReplacement() { - - // Logger declaration and instanciation without modifier - assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", - jclConverter.getOneLineReplacement("Log l = LogFactory.getFactory().getInstance(MyClass.class);")); - // Logger declaration and instanciation with one modifier - assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);", - jclConverter.getOneLineReplacement("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);")); - // Logger declaration and instanciation with modifiers - assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", - jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class);")); - // Logger declaration and instanciation with two modifier and comment at the - // end of line - assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); //logger instanciation and declaration", - jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class); //logger instanciation and declaration")); - // Logger instanciation without declaration and comment at the end of line - assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", - jclConverter.getOneLineReplacement(" myLog = LogFactory.getFactory().getInstance(MyClass.class);//logger instanciation")); - // commented Logger declaration and instanciation with two modifier - assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", - jclConverter.getOneLineReplacement("//public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class);")); - // commented Logger instanciation without declaration - assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", - jclConverter.getOneLineReplacement("// myLog = LogFactory.getFactory().getInstance(MyClass.class);//logger instanciation")); - } - - @Test - public void testLogDeclarationReplacement() { - - // simple Logger declaration - assertEquals("Logger mylog;", jclConverter.getOneLineReplacement("Log mylog;")); - // Logger declaration with a modifier - assertEquals("private Logger mylog;", jclConverter.getOneLineReplacement("private Log mylog;")); - - // Logger declaration with modifiers - assertEquals("public static final Logger myLog;", jclConverter.getOneLineReplacement("public static final Log myLog;")); - // Logger declaration with modifiers and comment at the end of line - assertEquals("public Logger myLog;//logger declaration", jclConverter.getOneLineReplacement("public Log myLog;//logger declaration")); - // commented Logger declaration - assertEquals("//private Logger myLog;", jclConverter.getOneLineReplacement("//private Log myLog;")); - } - - @Test - public void testMultiLineReplacement() { - // Logger declaration on a line - assertEquals("protected Logger log =", jclConverter.getOneLineReplacement("protected Log log =")); - - // Logger instanciation on the next line - assertEquals(" LoggerFactory.getLogger(MyComponent.class);", jclConverter.getOneLineReplacement(" LogFactory.getLog(MyComponent.class);")); - // Logger declaration on a line - assertEquals("protected Logger log ", jclConverter.getOneLineReplacement("protected Log log ")); - // Logger instanciation on the next line - assertEquals(" = LoggerFactory.getLogger(MyComponent.class);", - jclConverter.getOneLineReplacement(" = LogFactory.getFactory().getInstance(MyComponent.class);")); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class JCLRuleSetTest { + + LineConverter jclConverter = new LineConverter(new JCLRuleSet()); + + @Test + public void testImportReplacement() { + // LogFactory import replacement + assertEquals("import org.slf4j.LoggerFactory;", jclConverter.getOneLineReplacement("import org.apache.commons.logging.LogFactory;")); + // Log import replacement + assertEquals("import org.slf4j.Logger;", jclConverter.getOneLineReplacement("import org.apache.commons.logging.Log;")); + } + + @Test + public void testLogFactoryGetLogReplacement() { + // Logger declaration and instanciation without modifier + assertEquals(" Logger l = LoggerFactory.getLogger(MyClass.class);", + jclConverter.getOneLineReplacement(" Log l = LogFactory.getLog(MyClass.class);")); + // Logger declaration and instanciation with one modifier + assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);", + jclConverter.getOneLineReplacement("public Log mylog=LogFactory.getLog(MyClass.class);")); + // Logger declaration and instanciation with two modifier + assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", + jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class);")); + // Logger declaration and instanciation with two modifier and comment at the + // end of line + assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); //logger instanciation and declaration", + jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class); //logger instanciation and declaration")); + // Logger instanciation without declaration and comment at the end of line + assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", + jclConverter.getOneLineReplacement(" myLog = LogFactory.getLog(MyClass.class);//logger instanciation")); + // commented Logger declaration and instanciation with two modifier + assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", + jclConverter.getOneLineReplacement("//public static Log mylog1 = LogFactory.getLog(MyClass.class);")); + // commented Logger instanciation without declaration + assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", + jclConverter.getOneLineReplacement("// myLog = LogFactory.getLog(MyClass.class);//logger instanciation")); + } + + @Test + public void testLogFactoryGetFactoryReplacement() { + + // Logger declaration and instanciation without modifier + assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", + jclConverter.getOneLineReplacement("Log l = LogFactory.getFactory().getInstance(MyClass.class);")); + // Logger declaration and instanciation with one modifier + assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);", + jclConverter.getOneLineReplacement("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);")); + // Logger declaration and instanciation with modifiers + assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", + jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class);")); + // Logger declaration and instanciation with two modifier and comment at the + // end of line + assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); //logger instanciation and declaration", + jclConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class); //logger instanciation and declaration")); + // Logger instanciation without declaration and comment at the end of line + assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", + jclConverter.getOneLineReplacement(" myLog = LogFactory.getFactory().getInstance(MyClass.class);//logger instanciation")); + // commented Logger declaration and instanciation with two modifier + assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", + jclConverter.getOneLineReplacement("//public static Log mylog1 = LogFactory.getFactory().getInstance(MyClass.class);")); + // commented Logger instanciation without declaration + assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", + jclConverter.getOneLineReplacement("// myLog = LogFactory.getFactory().getInstance(MyClass.class);//logger instanciation")); + } + + @Test + public void testLogDeclarationReplacement() { + + // simple Logger declaration + assertEquals("Logger mylog;", jclConverter.getOneLineReplacement("Log mylog;")); + // Logger declaration with a modifier + assertEquals("private Logger mylog;", jclConverter.getOneLineReplacement("private Log mylog;")); + + // Logger declaration with modifiers + assertEquals("public static final Logger myLog;", jclConverter.getOneLineReplacement("public static final Log myLog;")); + // Logger declaration with modifiers and comment at the end of line + assertEquals("public Logger myLog;//logger declaration", jclConverter.getOneLineReplacement("public Log myLog;//logger declaration")); + // commented Logger declaration + assertEquals("//private Logger myLog;", jclConverter.getOneLineReplacement("//private Log myLog;")); + } + + @Test + public void testMultiLineReplacement() { + // Logger declaration on a line + assertEquals("protected Logger log =", jclConverter.getOneLineReplacement("protected Log log =")); + + // Logger instanciation on the next line + assertEquals(" LoggerFactory.getLogger(MyComponent.class);", jclConverter.getOneLineReplacement(" LogFactory.getLog(MyComponent.class);")); + // Logger declaration on a line + assertEquals("protected Logger log ", jclConverter.getOneLineReplacement("protected Log log ")); + // Logger instanciation on the next line + assertEquals(" = LoggerFactory.getLogger(MyComponent.class);", + jclConverter.getOneLineReplacement(" = LogFactory.getFactory().getInstance(MyComponent.class);")); + } +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/Log4jRuleSetTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/Log4jRuleSetTest.java old file mode 100644 new file mode 100755 index 52a7df4..77e11b7 100755 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/Log4jRuleSetTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/Log4jRuleSetTest.java @@ -1,136 +1,136 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.Arrays; - -import org.junit.Test; -import org.slf4j.migrator.line.LineConverter; -import org.slf4j.migrator.line.Log4jRuleSet; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class Log4jRuleSetTest { - - LineConverter log4jConverter = new LineConverter(new Log4jRuleSet()); - - @Test - public void testImportReplacement() { - // LogFactory import replacement - assertEquals("import org.slf4j.LoggerFactory;", log4jConverter.getOneLineReplacement("import org.apache.log4j.LogManager;")); - // Log import replacement - assertTrue(Arrays.equals(new String[] { "import org.slf4j.Logger;", "import org.slf4j.LoggerFactory;" }, - log4jConverter.getReplacement("import org.apache.log4j.Logger;"))); - } - - @Test - public void testLogManagerGetLoggerReplacement() { - // Logger declaration and instanciation without modifier - assertEquals(" Logger l = LoggerFactory.getLogger(MyClass.class);", - log4jConverter.getOneLineReplacement(" Logger l = LogManager.getLogger(MyClass.class);")); - // Logger declaration and instanciation with one modifier - assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);", - log4jConverter.getOneLineReplacement("public Logger mylog=LogManager.getLogger(MyClass.class);")); - // Logger declaration and instanciation with two modifier - assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", - log4jConverter.getOneLineReplacement("public static Logger mylog1 = LogManager.getLogger(MyClass.class);")); - // Logger declaration and instanciation with two modifier and comment at the - // end of line - assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);//logger instanciation and declaration", - log4jConverter.getOneLineReplacement("public static Logger mylog1 = LogManager.getLogger(MyClass.class);//logger instanciation and declaration")); - // Logger instanciation without declaration and comment at the end of line - assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", - log4jConverter.getOneLineReplacement(" myLog = LogManager.getLogger(MyClass.class);//logger instanciation")); - // commented Logger declaration and instanciation with two modifier - assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", - log4jConverter.getOneLineReplacement("//public static Logger mylog1 = LogManager.getLogger(MyClass.class);")); - // commented Logger instanciation without declaration - assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", - log4jConverter.getOneLineReplacement("// myLog = LogManager.getLogger(MyClass.class);//logger instanciation")); - } - - @Test - public void testLoggerGetLoggerReplacement() { - // Logger declaration and instanciation without modifier - assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", log4jConverter.getOneLineReplacement("Logger l = Logger.getLogger(MyClass.class);")); - // Logger declaration and instanciation with one modifier - assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);", - log4jConverter.getOneLineReplacement("public Logger mylog=Logger.getLogger(MyClass.class);")); - // Logger declaration and instanciation with modifiers - assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", - log4jConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class);")); - // Logger declaration and instanciation with two modifier and comment at the - // end of line - assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); // logger instanciation and declaration", - log4jConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class); // logger instanciation and declaration")); - // Logger instanciation without declaration and comment at the end of line - assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", - log4jConverter.getOneLineReplacement(" myLog = Logger.getLogger(MyClass.class);//logger instanciation")); - // commented Logger declaration and instanciation with two modifier - assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", - log4jConverter.getOneLineReplacement("//public static Logger mylog1 = Logger.getLogger(MyClass.class);")); - // commented Logger instanciation without declaration - assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", - log4jConverter.getOneLineReplacement("// myLog = Logger.getLogger(MyClass.class);//logger instanciation")); - } - - @Test - public void testLogDeclarationReplacement() { - // simple Logger declaration - assertEquals("Logger mylog;", log4jConverter.getOneLineReplacement("Logger mylog;")); - // Logger declaration with a modifier - assertEquals("private Logger mylog;", log4jConverter.getOneLineReplacement("private Logger mylog;")); - - // Logger declaration with modifiers - assertEquals("public static final Logger myLog;", log4jConverter.getOneLineReplacement("public static final Logger myLog;")); - // Logger declaration with modifiers and comment at the end of line - assertEquals("public Logger myLog;//logger declaration", log4jConverter.getOneLineReplacement("public Logger myLog;//logger declaration")); - // commented Logger declaration - assertEquals("//private Logger myLog;", log4jConverter.getOneLineReplacement("//private Logger myLog;")); - } - - @Test - public void testMultiLineReplacement() { - // Logger declaration on a line - assertEquals("protected Logger log =", log4jConverter.getOneLineReplacement("protected Logger log =")); - - // Logger instanciation on the next line - assertEquals(" LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" LogManager.getLogger(MyComponent.class);")); - // Logger declaration on a line - assertEquals("protected Logger log ", log4jConverter.getOneLineReplacement("protected Logger log ")); - // Logger instanciation on the next line - assertEquals(" = LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" = LogManager.getLogger(MyComponent.class);")); - } - - @Test - public void categoryReplacement() { - // Category declaration on a line - assertEquals("protected Logger cat =", log4jConverter.getOneLineReplacement("protected Category cat =")); - - assertEquals(" LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" Category.getInstance(MyComponent.class);")); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.Arrays; + +import org.junit.Test; +import org.slf4j.migrator.line.LineConverter; +import org.slf4j.migrator.line.Log4jRuleSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class Log4jRuleSetTest { + + LineConverter log4jConverter = new LineConverter(new Log4jRuleSet()); + + @Test + public void testImportReplacement() { + // LogFactory import replacement + assertEquals("import org.slf4j.LoggerFactory;", log4jConverter.getOneLineReplacement("import org.apache.log4j.LogManager;")); + // Log import replacement + assertTrue(Arrays.equals(new String[] { "import org.slf4j.Logger;", "import org.slf4j.LoggerFactory;" }, + log4jConverter.getReplacement("import org.apache.log4j.Logger;"))); + } + + @Test + public void testLogManagerGetLoggerReplacement() { + // Logger declaration and instanciation without modifier + assertEquals(" Logger l = LoggerFactory.getLogger(MyClass.class);", + log4jConverter.getOneLineReplacement(" Logger l = LogManager.getLogger(MyClass.class);")); + // Logger declaration and instanciation with one modifier + assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);", + log4jConverter.getOneLineReplacement("public Logger mylog=LogManager.getLogger(MyClass.class);")); + // Logger declaration and instanciation with two modifier + assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", + log4jConverter.getOneLineReplacement("public static Logger mylog1 = LogManager.getLogger(MyClass.class);")); + // Logger declaration and instanciation with two modifier and comment at the + // end of line + assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);//logger instanciation and declaration", + log4jConverter.getOneLineReplacement("public static Logger mylog1 = LogManager.getLogger(MyClass.class);//logger instanciation and declaration")); + // Logger instanciation without declaration and comment at the end of line + assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", + log4jConverter.getOneLineReplacement(" myLog = LogManager.getLogger(MyClass.class);//logger instanciation")); + // commented Logger declaration and instanciation with two modifier + assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", + log4jConverter.getOneLineReplacement("//public static Logger mylog1 = LogManager.getLogger(MyClass.class);")); + // commented Logger instanciation without declaration + assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", + log4jConverter.getOneLineReplacement("// myLog = LogManager.getLogger(MyClass.class);//logger instanciation")); + } + + @Test + public void testLoggerGetLoggerReplacement() { + // Logger declaration and instanciation without modifier + assertEquals("Logger l = LoggerFactory.getLogger(MyClass.class);", log4jConverter.getOneLineReplacement("Logger l = Logger.getLogger(MyClass.class);")); + // Logger declaration and instanciation with one modifier + assertEquals("public Logger mylog=LoggerFactory.getLogger(MyClass.class);", + log4jConverter.getOneLineReplacement("public Logger mylog=Logger.getLogger(MyClass.class);")); + // Logger declaration and instanciation with modifiers + assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", + log4jConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class);")); + // Logger declaration and instanciation with two modifier and comment at the + // end of line + assertEquals("public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class); // logger instanciation and declaration", + log4jConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class); // logger instanciation and declaration")); + // Logger instanciation without declaration and comment at the end of line + assertEquals(" myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", + log4jConverter.getOneLineReplacement(" myLog = Logger.getLogger(MyClass.class);//logger instanciation")); + // commented Logger declaration and instanciation with two modifier + assertEquals("//public static Logger mylog1 = LoggerFactory.getLogger(MyClass.class);", + log4jConverter.getOneLineReplacement("//public static Logger mylog1 = Logger.getLogger(MyClass.class);")); + // commented Logger instanciation without declaration + assertEquals("// myLog = LoggerFactory.getLogger(MyClass.class);//logger instanciation", + log4jConverter.getOneLineReplacement("// myLog = Logger.getLogger(MyClass.class);//logger instanciation")); + } + + @Test + public void testLogDeclarationReplacement() { + // simple Logger declaration + assertEquals("Logger mylog;", log4jConverter.getOneLineReplacement("Logger mylog;")); + // Logger declaration with a modifier + assertEquals("private Logger mylog;", log4jConverter.getOneLineReplacement("private Logger mylog;")); + + // Logger declaration with modifiers + assertEquals("public static final Logger myLog;", log4jConverter.getOneLineReplacement("public static final Logger myLog;")); + // Logger declaration with modifiers and comment at the end of line + assertEquals("public Logger myLog;//logger declaration", log4jConverter.getOneLineReplacement("public Logger myLog;//logger declaration")); + // commented Logger declaration + assertEquals("//private Logger myLog;", log4jConverter.getOneLineReplacement("//private Logger myLog;")); + } + + @Test + public void testMultiLineReplacement() { + // Logger declaration on a line + assertEquals("protected Logger log =", log4jConverter.getOneLineReplacement("protected Logger log =")); + + // Logger instanciation on the next line + assertEquals(" LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" LogManager.getLogger(MyComponent.class);")); + // Logger declaration on a line + assertEquals("protected Logger log ", log4jConverter.getOneLineReplacement("protected Logger log ")); + // Logger instanciation on the next line + assertEquals(" = LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" = LogManager.getLogger(MyComponent.class);")); + } + + @Test + public void categoryReplacement() { + // Category declaration on a line + assertEquals("protected Logger cat =", log4jConverter.getOneLineReplacement("protected Category cat =")); + + assertEquals(" LoggerFactory.getLogger(MyComponent.class);", log4jConverter.getOneLineReplacement(" Category.getInstance(MyComponent.class);")); + } + +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/NoConversionTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/NoConversionTest.java index 179b280..60b1fdb 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/NoConversionTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/NoConversionTest.java @@ -1,75 +1,75 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class NoConversionTest { - - /** - * This test shows that performing JCL to SLF4J conversion has no impact on - * Log4j implementation - */ - @Test - public void testJclOverLog4jConversion() { - // running jcl to slf4j conversion - // JCLMatcher jclMatcher = - LineConverter jclLineConverter = new LineConverter(new JCLRuleSet()); - // no changes on log4j.LogManager import - assertEquals("import org.apache.log4j.LogManager;", jclLineConverter.getOneLineReplacement("import org.apache.log4j.LogManager;")); - // no changes on log4j.Logger import - assertEquals("import org.apache.log4j.Logger;", jclLineConverter.getOneLineReplacement("import org.apache.log4j.Logger;")); - // no changes on Logger instanciation using LogManager - assertEquals("Logger log = LogManager.getLogger(MyClass.class);", - jclLineConverter.getOneLineReplacement("Logger log = LogManager.getLogger(MyClass.class);")); - // no changes on Logger instanciation using Logger.getLogger - assertEquals("public static Logger mylog1 = Logger.getLogger(MyClass.class);", - jclLineConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class);")); - } - - /** - * This test shows that performing Log4j to SLF4J conversion has no impact on - * JCL implementation - */ - @Test - public void testLog4jOverJclConversion() { - // running log4j to slf4j conversion - LineConverter log4jConverter = new LineConverter(new Log4jRuleSet()); - - // no changes on LogFactory import - assertEquals("import org.apache.commons.logging.LogFactory;", log4jConverter.getOneLineReplacement("import org.apache.commons.logging.LogFactory;")); - // no changes on Log import - assertEquals("import org.apache.commons.logging.Log;", log4jConverter.getOneLineReplacement("import org.apache.commons.logging.Log;")); - // no changes on Log instanciation using Logfactory.getLog - assertEquals("public static Log mylog1 = LogFactory.getLog(MyClass.class);", - log4jConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class);")); - // no changes on log instanciation using LogFactory.getFactory().getInstance - assertEquals("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);", - log4jConverter.getOneLineReplacement("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);")); - - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class NoConversionTest { + + /** + * This test shows that performing JCL to SLF4J conversion has no impact on + * Log4j implementation + */ + @Test + public void testJclOverLog4jConversion() { + // running jcl to slf4j conversion + // JCLMatcher jclMatcher = + LineConverter jclLineConverter = new LineConverter(new JCLRuleSet()); + // no changes on log4j.LogManager import + assertEquals("import org.apache.log4j.LogManager;", jclLineConverter.getOneLineReplacement("import org.apache.log4j.LogManager;")); + // no changes on log4j.Logger import + assertEquals("import org.apache.log4j.Logger;", jclLineConverter.getOneLineReplacement("import org.apache.log4j.Logger;")); + // no changes on Logger instanciation using LogManager + assertEquals("Logger log = LogManager.getLogger(MyClass.class);", + jclLineConverter.getOneLineReplacement("Logger log = LogManager.getLogger(MyClass.class);")); + // no changes on Logger instanciation using Logger.getLogger + assertEquals("public static Logger mylog1 = Logger.getLogger(MyClass.class);", + jclLineConverter.getOneLineReplacement("public static Logger mylog1 = Logger.getLogger(MyClass.class);")); + } + + /** + * This test shows that performing Log4j to SLF4J conversion has no impact on + * JCL implementation + */ + @Test + public void testLog4jOverJclConversion() { + // running log4j to slf4j conversion + LineConverter log4jConverter = new LineConverter(new Log4jRuleSet()); + + // no changes on LogFactory import + assertEquals("import org.apache.commons.logging.LogFactory;", log4jConverter.getOneLineReplacement("import org.apache.commons.logging.LogFactory;")); + // no changes on Log import + assertEquals("import org.apache.commons.logging.Log;", log4jConverter.getOneLineReplacement("import org.apache.commons.logging.Log;")); + // no changes on Log instanciation using Logfactory.getLog + assertEquals("public static Log mylog1 = LogFactory.getLog(MyClass.class);", + log4jConverter.getOneLineReplacement("public static Log mylog1 = LogFactory.getLog(MyClass.class);")); + // no changes on log instanciation using LogFactory.getFactory().getInstance + assertEquals("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);", + log4jConverter.getOneLineReplacement("public Log mylog=LogFactory.getFactory().getInstance(MyClass.class);")); + + } +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/PackageTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/PackageTest.java old file mode 100644 new file mode 100755 index 264b3eb..e05977f 100755 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/PackageTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/PackageTest.java @@ -1,34 +1,34 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ TrivialMatcherTest.class, JCLRuleSetTest.class, Log4jRuleSetTest.class, NoConversionTest.class }) -public class PackageTest { -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +import org.junit.runners.Suite.SuiteClasses; + +@RunWith(Suite.class) +@SuiteClasses({ TrivialMatcherTest.class, JCLRuleSetTest.class, Log4jRuleSetTest.class, NoConversionTest.class }) +public class PackageTest { +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TrivialMatcher.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TrivialMatcher.java index 7b5deae..d392769 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TrivialMatcher.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TrivialMatcher.java @@ -1,63 +1,63 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.regex.Pattern; - -import org.slf4j.migrator.line.ConversionRule; -import org.slf4j.migrator.line.MultiGroupConversionRule; -import org.slf4j.migrator.line.RuleSet; -import org.slf4j.migrator.line.SingleConversionRule; - -class TrivialMatcher implements RuleSet { - - private ArrayList conversionRuleList; - - public TrivialMatcher() { - // simple rule no capturing group is defined, we use default capturing group which is group zero - SingleConversionRule cr = new SingleConversionRule(Pattern.compile("import org.slf4j.converter"), "simple replacement with an unique capturing group"); - - // we define 4 differents capturing groups - MultiGroupConversionRule cr1 = new MultiGroupConversionRule(Pattern.compile("(first group)( second group)( third group)( 4th group)")); - // group zero is ignored during treatment - // replacement for the first - cr1.addReplacement(1, "1st group"); - // no replacement for the second group it will remains the same - // empty string for the third group it will be deleted - cr1.addReplacement(3, ""); - // no replacement for the third group it will remains the same - - conversionRuleList = new ArrayList(); - conversionRuleList.add(cr); - conversionRuleList.add(cr1); - } - - public Iterator iterator() { - return conversionRuleList.iterator(); - } - +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.regex.Pattern; + +import org.slf4j.migrator.line.ConversionRule; +import org.slf4j.migrator.line.MultiGroupConversionRule; +import org.slf4j.migrator.line.RuleSet; +import org.slf4j.migrator.line.SingleConversionRule; + +class TrivialMatcher implements RuleSet { + + private ArrayList conversionRuleList; + + public TrivialMatcher() { + // simple rule no capturing group is defined, we use default capturing group which is group zero + SingleConversionRule cr = new SingleConversionRule(Pattern.compile("import org.slf4j.converter"), "simple replacement with an unique capturing group"); + + // we define 4 differents capturing groups + MultiGroupConversionRule cr1 = new MultiGroupConversionRule(Pattern.compile("(first group)( second group)( third group)( 4th group)")); + // group zero is ignored during treatment + // replacement for the first + cr1.addReplacement(1, "1st group"); + // no replacement for the second group it will remains the same + // empty string for the third group it will be deleted + cr1.addReplacement(3, ""); + // no replacement for the third group it will remains the same + + conversionRuleList = new ArrayList(); + conversionRuleList.add(cr); + conversionRuleList.add(cr1); + } + + public Iterator iterator() { + return conversionRuleList.iterator(); + } + }diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TrivialMatcherTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TrivialMatcherTest.java index bdb0ded..0a9194d 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TrivialMatcherTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TrivialMatcherTest.java @@ -1,45 +1,45 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.migrator.line; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class TrivialMatcherTest { - - @Test - public void testSimpleReplacement() { - LineConverter trivialLC = new LineConverter(new TrivialMatcher()); - - // "import org.slf4j.converter" -- > simple replacement with an unique - // capturing group - assertEquals("simple replacement with an unique capturing group", trivialLC.getOneLineReplacement("import org.slf4j.converter")); - - assertEquals("1st group second group 4th group", trivialLC.getOneLineReplacement("first group second group third group 4th group")); - - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.migrator.line; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class TrivialMatcherTest { + + @Test + public void testSimpleReplacement() { + LineConverter trivialLC = new LineConverter(new TrivialMatcher()); + + // "import org.slf4j.converter" -- > simple replacement with an unique + // capturing group + assertEquals("simple replacement with an unique capturing group", trivialLC.getOneLineReplacement("import org.slf4j.converter")); + + assertEquals("1st group second group 4th group", trivialLC.getOneLineReplacement("first group second group third group 4th group")); + + } + +} diff --git a/slf4j-nop/LICENSE.txt b/slf4j-nop/LICENSE.txt new file mode 100644 index 0000000..508a272 --- /dev/null +++ b/slf4j-nop/LICENSE.txt @@ -0,0 +1,24 @@ +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-nop/pom.xml b/slf4j-nop/pom.xml old file mode 100644 new file mode 100755 index 41f5a76..f6aaaec 100755 --- a/slf4j-nop/pom.xml +++ b/slf4j-nop/pom.xml @@ -1,27 +1,28 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - slf4j-nop - - jar - SLF4J NOP Binding - SLF4J NOP Binding - http://www.slf4j.org - - - - org.slf4j - slf4j-api - - - - \ No newline at end of file + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + slf4j-nop + + jar + SLF4J NOP Binding + SLF4J NOP Binding + http://www.slf4j.org + + + + org.slf4j + slf4j-api + + + + + diff --git a/slf4j-nop/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/slf4j-nop/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index 243cbfe..35fc464 100644 --- a/slf4j-nop/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-nop/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,80 +1,80 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.helpers.NOPLoggerFactory; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - * - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - /** - * Declare the version of the SLF4J API this implementation is compiled against. - * The value of this field is modified with each major release. - */ - // to avoid constant folding by the compiler, this field must *not* be final - public static String REQUESTED_API_VERSION = "1.6.99"; // !final - - private static final String loggerFactoryClassStr = NOPLoggerFactory.class.getName(); - - /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method - * should always be the same object - */ - private final ILoggerFactory loggerFactory; - - private StaticLoggerBinder() { - loggerFactory = new NOPLoggerFactory(); - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.helpers.NOPLoggerFactory; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + * + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is modified with each major release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; // !final + + private static final String loggerFactoryClassStr = NOPLoggerFactory.class.getName(); + + /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method + * should always be the same object + */ + private final ILoggerFactory loggerFactory; + + private StaticLoggerBinder() { + loggerFactory = new NOPLoggerFactory(); + } + + public ILoggerFactory getLoggerFactory() { + return loggerFactory; + } + + public String getLoggerFactoryClassStr() { + return loggerFactoryClassStr; + } +} diff --git a/slf4j-nop/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/slf4j-nop/src/main/java/org/slf4j/impl/StaticMDCBinder.java index dccb05a..a88f2bf 100644 --- a/slf4j-nop/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-nop/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,66 +1,66 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.helpers.NOPMDCAdapter; -import org.slf4j.spi.MDCAdapter; - -/** - * This implementation is bound to {@link NOPMDCAdapter}. - * - * @author Ceki Gülcü - */ -public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - - private StaticMDCBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMDCBinder singleton - * @since 1.7.14 - */ - public static final StaticMDCBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link StaticMDCBinder}. - */ - public MDCAdapter getMDCA() { - return new NOPMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return NOPMDCAdapter.class.getName(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.helpers.NOPMDCAdapter; +import org.slf4j.spi.MDCAdapter; + +/** + * This implementation is bound to {@link NOPMDCAdapter}. + * + * @author Ceki Gülcü + */ +public class StaticMDCBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMDCBinder singleton + * @since 1.7.14 + */ + public static final StaticMDCBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link StaticMDCBinder}. + */ + public MDCAdapter getMDCA() { + return new NOPMDCAdapter(); + } + + public String getMDCAdapterClassStr() { + return NOPMDCAdapter.class.getName(); + } +} diff --git a/slf4j-nop/src/main/java/org/slf4j/impl/StaticMarkerBinder.java b/slf4j-nop/src/main/java/org/slf4j/impl/StaticMarkerBinder.java index 21a48df..c37af78 100644 --- a/slf4j-nop/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-nop/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,77 +1,77 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMarkerBinder singleton - * @since 1.7.14 - */ - public static StaticMarkerBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMarkerBinder singleton + * @since 1.7.14 + */ + public static StaticMarkerBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + +} diff --git a/slf4j-nop/src/main/resources/META-INF/MANIFEST.MF b/slf4j-nop/src/main/resources/META-INF/MANIFEST.MF old file mode 100644 new file mode 100755 index 88f1cc9..8de6024 100755 --- a/slf4j-nop/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-nop/src/main/resources/META-INF/MANIFEST.MF @@ -1,12 +1,12 @@ -Implementation-Title: slf4j-nop -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.nop -Bundle-Name: slf4j-nop -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, - org.slf4j.spi;version=${parsedVersion.osgiVersion}, - org.slf4j.helpers;version=${parsedVersion.osgiVersion}, - org.slf4j.event;version=${parsedVersion.osgiVersion} +Implementation-Title: slf4j-nop +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.nop +Bundle-Name: slf4j-nop +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, + org.slf4j.spi;version=${parsedVersion.osgiVersion}, + org.slf4j.helpers;version=${parsedVersion.osgiVersion}, + org.slf4j.event;version=${parsedVersion.osgiVersion} Fragment-Host: slf4j.apidiff --git a/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java b/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java index 037bde1..51ae1ff 100644 --- a/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java @@ -1,121 +1,121 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import static org.junit.Assert.assertNull; - -import org.junit.Test; - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - * - */ -public class InvocationTest { - - @Test - public void test1() { - Logger logger = LoggerFactory.getLogger("test1"); - logger.debug("Hello world."); - } - - @Test - public void test2() { - Integer i1 = new Integer(1); - Integer i2 = new Integer(2); - Integer i3 = new Integer(3); - Exception e = new Exception("This is a test exception."); - Logger logger = LoggerFactory.getLogger("test2"); - - logger.debug("Hello world 1."); - logger.debug("Hello world {}", i1); - logger.debug("val={} val={}", i1, i2); - logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); - - logger.debug("Hello world 2", e); - logger.info("Hello world 2."); - - logger.warn("Hello world 3."); - logger.warn("Hello world 3", e); - - logger.error("Hello world 4."); - logger.error("Hello world {}", new Integer(3)); - logger.error("Hello world 4.", e); - } - - @Test - public void testNull() { - Logger logger = LoggerFactory.getLogger("testNull"); - logger.debug(null); - logger.info(null); - logger.warn(null); - logger.error(null); - - Exception e = new Exception("This is a test exception."); - logger.debug(null, e); - logger.info(null, e); - logger.warn(null, e); - logger.error(null, e); - } - - @Test - public void testMarker() { - Logger logger = LoggerFactory.getLogger("testMarker"); - Marker blue = MarkerFactory.getMarker("BLUE"); - logger.debug(blue, "hello"); - logger.info(blue, "hello"); - logger.warn(blue, "hello"); - logger.error(blue, "hello"); - - logger.debug(blue, "hello {}", "world"); - logger.info(blue, "hello {}", "world"); - logger.warn(blue, "hello {}", "world"); - logger.error(blue, "hello {}", "world"); - - logger.debug(blue, "hello {} and {} ", "world", "universe"); - logger.info(blue, "hello {} and {} ", "world", "universe"); - logger.warn(blue, "hello {} and {} ", "world", "universe"); - logger.error(blue, "hello {} and {} ", "world", "universe"); - } - - @Test - public void testMDC() { - MDC.put("k", "v"); - assertNull(MDC.get("k")); - MDC.remove("k"); - assertNull(MDC.get("k")); - MDC.clear(); - } - - @Test - public void testMDCCloseable() { - MDC.MDCCloseable closeable = MDC.putCloseable("k", "v"); - assertNull(MDC.get("k")); - closeable.close(); - assertNull(MDC.get("k")); - MDC.clear(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +/** + * Test whether invoking the SLF4J API causes problems or not. + * + * @author Ceki Gulcu + * + */ +public class InvocationTest { + + @Test + public void test1() { + Logger logger = LoggerFactory.getLogger("test1"); + logger.debug("Hello world."); + } + + @Test + public void test2() { + Integer i1 = new Integer(1); + Integer i2 = new Integer(2); + Integer i3 = new Integer(3); + Exception e = new Exception("This is a test exception."); + Logger logger = LoggerFactory.getLogger("test2"); + + logger.debug("Hello world 1."); + logger.debug("Hello world {}", i1); + logger.debug("val={} val={}", i1, i2); + logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); + + logger.debug("Hello world 2", e); + logger.info("Hello world 2."); + + logger.warn("Hello world 3."); + logger.warn("Hello world 3", e); + + logger.error("Hello world 4."); + logger.error("Hello world {}", new Integer(3)); + logger.error("Hello world 4.", e); + } + + @Test + public void testNull() { + Logger logger = LoggerFactory.getLogger("testNull"); + logger.debug(null); + logger.info(null); + logger.warn(null); + logger.error(null); + + Exception e = new Exception("This is a test exception."); + logger.debug(null, e); + logger.info(null, e); + logger.warn(null, e); + logger.error(null, e); + } + + @Test + public void testMarker() { + Logger logger = LoggerFactory.getLogger("testMarker"); + Marker blue = MarkerFactory.getMarker("BLUE"); + logger.debug(blue, "hello"); + logger.info(blue, "hello"); + logger.warn(blue, "hello"); + logger.error(blue, "hello"); + + logger.debug(blue, "hello {}", "world"); + logger.info(blue, "hello {}", "world"); + logger.warn(blue, "hello {}", "world"); + logger.error(blue, "hello {}", "world"); + + logger.debug(blue, "hello {} and {} ", "world", "universe"); + logger.info(blue, "hello {} and {} ", "world", "universe"); + logger.warn(blue, "hello {} and {} ", "world", "universe"); + logger.error(blue, "hello {} and {} ", "world", "universe"); + } + + @Test + public void testMDC() { + MDC.put("k", "v"); + assertNull(MDC.get("k")); + MDC.remove("k"); + assertNull(MDC.get("k")); + MDC.clear(); + } + + @Test + public void testMDCCloseable() { + MDC.MDCCloseable closeable = MDC.putCloseable("k", "v"); + assertNull(MDC.get("k")); + closeable.close(); + assertNull(MDC.get("k")); + MDC.clear(); + } +} diff --git a/slf4j-nop/src/test/java/org/slf4j/LoggerFactoryFriend.java b/slf4j-nop/src/test/java/org/slf4j/LoggerFactoryFriend.java old file mode 100644 new file mode 100755 index edf5fcf..4398d3b 100755 --- a/slf4j-nop/src/test/java/org/slf4j/LoggerFactoryFriend.java +++ b/slf4j-nop/src/test/java/org/slf4j/LoggerFactoryFriend.java @@ -1,7 +1,7 @@ -package org.slf4j; - -public class LoggerFactoryFriend { - static public void reset() { - LoggerFactory.reset(); - } -} +package org.slf4j; + +public class LoggerFactoryFriend { + static public void reset() { + LoggerFactory.reset(); + } +} diff --git a/slf4j-nop/src/test/java/org/slf4j/impl/MultithreadedInitializationTest.java b/slf4j-nop/src/test/java/org/slf4j/impl/MultithreadedInitializationTest.java old file mode 100644 new file mode 100755 index 18a3732..493b3d7 100755 --- a/slf4j-nop/src/test/java/org/slf4j/impl/MultithreadedInitializationTest.java +++ b/slf4j-nop/src/test/java/org/slf4j/impl/MultithreadedInitializationTest.java @@ -1,150 +1,150 @@ -/** - * Copyright (c) 2004-2016 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import static org.junit.Assert.assertEquals; - -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.BrokenBarrierException; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.atomic.AtomicLong; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.LoggerFactoryFriend; - -public class MultithreadedInitializationTest { - - final static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2; - - private static AtomicLong EVENT_COUNT = new AtomicLong(0); - - final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); - - int diff = new Random().nextInt(10000); - String loggerName = "org.slf4j.impl.MultithreadedInitializationTest"; - private final PrintStream oldErr = System.err; - StringPrintStream sps = new StringPrintStream(oldErr); - - @Before - public void setup() { - LoggerFactoryFriend.reset(); - System.setErr(sps); - } - - @After - public void tearDown() throws Exception { - LoggerFactoryFriend.reset(); - System.setErr(oldErr); - } - - @Test - public void multiThreadedInitialization() throws InterruptedException, BrokenBarrierException { - System.out.println("THREAD_COUNT=" + THREAD_COUNT); - LoggerAccessingThread[] accessors = harness(); - - for (LoggerAccessingThread accessor : accessors) { - EVENT_COUNT.getAndIncrement(); - accessor.logger.info("post harness"); - } - - Logger logger = LoggerFactory.getLogger(loggerName + ".slowInitialization-" + diff); - logger.info("hello"); - EVENT_COUNT.getAndIncrement(); - - assertEquals(0, sps.stringList.size()); - } - - private static LoggerAccessingThread[] harness() throws InterruptedException, BrokenBarrierException { - LoggerAccessingThread[] threads = new LoggerAccessingThread[THREAD_COUNT]; - final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); - for (int i = 0; i < THREAD_COUNT; i++) { - threads[i] = new LoggerAccessingThread(barrier, i); - threads[i].start(); - } - - barrier.await(); - for (int i = 0; i < THREAD_COUNT; i++) { - threads[i].join(); - } - return threads; - } - - static class LoggerAccessingThread extends Thread { - final CyclicBarrier barrier; - Logger logger; - int count; - - LoggerAccessingThread(CyclicBarrier barrier, int count) { - this.barrier = barrier; - this.count = count; - } - - public void run() { - try { - barrier.await(); - } catch (Exception e) { - e.printStackTrace(); - } - logger = LoggerFactory.getLogger(this.getClass().getName() + "-" + count); - logger.info("in run method"); - EVENT_COUNT.getAndIncrement(); - } - }; - - public static class StringPrintStream extends PrintStream { - - public static final String LINE_SEP = System.getProperty("line.separator"); - PrintStream other; - List stringList = new ArrayList(); - - public StringPrintStream(PrintStream ps) { - super(ps); - other = ps; - } - - public void print(String s) { - other.print(s); - stringList.add(s); - } - - public void println(String s) { - other.println(s); - stringList.add(s); - } - - public void println(Object o) { - other.println(o); - stringList.add(o.toString()); - } - }; - -} +/** + * Copyright (c) 2004-2016 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import static org.junit.Assert.assertEquals; + +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.atomic.AtomicLong; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.LoggerFactoryFriend; + +public class MultithreadedInitializationTest { + + final static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2; + + private static AtomicLong EVENT_COUNT = new AtomicLong(0); + + final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); + + int diff = new Random().nextInt(10000); + String loggerName = "org.slf4j.impl.MultithreadedInitializationTest"; + private final PrintStream oldErr = System.err; + StringPrintStream sps = new StringPrintStream(oldErr); + + @Before + public void setup() { + LoggerFactoryFriend.reset(); + System.setErr(sps); + } + + @After + public void tearDown() throws Exception { + LoggerFactoryFriend.reset(); + System.setErr(oldErr); + } + + @Test + public void multiThreadedInitialization() throws InterruptedException, BrokenBarrierException { + System.out.println("THREAD_COUNT=" + THREAD_COUNT); + LoggerAccessingThread[] accessors = harness(); + + for (LoggerAccessingThread accessor : accessors) { + EVENT_COUNT.getAndIncrement(); + accessor.logger.info("post harness"); + } + + Logger logger = LoggerFactory.getLogger(loggerName + ".slowInitialization-" + diff); + logger.info("hello"); + EVENT_COUNT.getAndIncrement(); + + assertEquals(0, sps.stringList.size()); + } + + private static LoggerAccessingThread[] harness() throws InterruptedException, BrokenBarrierException { + LoggerAccessingThread[] threads = new LoggerAccessingThread[THREAD_COUNT]; + final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); + for (int i = 0; i < THREAD_COUNT; i++) { + threads[i] = new LoggerAccessingThread(barrier, i); + threads[i].start(); + } + + barrier.await(); + for (int i = 0; i < THREAD_COUNT; i++) { + threads[i].join(); + } + return threads; + } + + static class LoggerAccessingThread extends Thread { + final CyclicBarrier barrier; + Logger logger; + int count; + + LoggerAccessingThread(CyclicBarrier barrier, int count) { + this.barrier = barrier; + this.count = count; + } + + public void run() { + try { + barrier.await(); + } catch (Exception e) { + e.printStackTrace(); + } + logger = LoggerFactory.getLogger(this.getClass().getName() + "-" + count); + logger.info("in run method"); + EVENT_COUNT.getAndIncrement(); + } + }; + + public static class StringPrintStream extends PrintStream { + + public static final String LINE_SEP = System.getProperty("line.separator"); + PrintStream other; + List stringList = new ArrayList(); + + public StringPrintStream(PrintStream ps) { + super(ps); + other = ps; + } + + public void print(String s) { + other.print(s); + stringList.add(s); + } + + public void println(String s) { + other.println(s); + stringList.add(s); + } + + public void println(Object o) { + other.println(o); + stringList.add(o.toString()); + } + }; + +} diff --git a/slf4j-simple/LICENSE.txt b/slf4j-simple/LICENSE.txt new file mode 100644 index 0000000..508a272 --- /dev/null +++ b/slf4j-simple/LICENSE.txt @@ -0,0 +1,24 @@ +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-simple/pom.xml b/slf4j-simple/pom.xml old file mode 100644 new file mode 100755 index 6b019bd..0c02ce5 100755 --- a/slf4j-simple/pom.xml +++ b/slf4j-simple/pom.xml @@ -1,34 +1,35 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - slf4j-simple - jar - SLF4J Simple Binding - SLF4J Simple binding - http://www.slf4j.org - - - - org.slf4j - slf4j-api - - - - org.slf4j - slf4j-api - test-jar - ${project.version} - test - - - - \ No newline at end of file + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + slf4j-simple + jar + SLF4J Simple Binding + SLF4J Simple binding + http://www.slf4j.org + + + + org.slf4j + slf4j-api + + + + org.slf4j + slf4j-api + test-jar + ${project.version} + test + + + + + diff --git a/slf4j-simple/src/main/java/org/slf4j/impl/OutputChoice.java b/slf4j-simple/src/main/java/org/slf4j/impl/OutputChoice.java old file mode 100644 new file mode 100755 index c3d691e..16c42d3 100755 --- a/slf4j-simple/src/main/java/org/slf4j/impl/OutputChoice.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/OutputChoice.java @@ -1,55 +1,55 @@ -package org.slf4j.impl; - -import java.io.PrintStream; - -/** - * This class encapsulates the user's choice of output target. - * - * @author Ceki Gülcü - * - */ -class OutputChoice { - - enum OutputChoiceType { - SYS_OUT, CACHED_SYS_OUT, SYS_ERR, CACHED_SYS_ERR, FILE; - } - - final OutputChoiceType outputChoiceType; - final PrintStream targetPrintStream; - - OutputChoice(OutputChoiceType outputChoiceType) { - if (outputChoiceType == OutputChoiceType.FILE) { - throw new IllegalArgumentException(); - } - this.outputChoiceType = outputChoiceType; - if (outputChoiceType == OutputChoiceType.CACHED_SYS_OUT) { - this.targetPrintStream = System.out; - } else if (outputChoiceType == OutputChoiceType.CACHED_SYS_ERR) { - this.targetPrintStream = System.err; - } else { - this.targetPrintStream = null; - } - } - - OutputChoice(PrintStream printStream) { - this.outputChoiceType = OutputChoiceType.FILE; - this.targetPrintStream = printStream; - } - - PrintStream getTargetPrintStream() { - switch (outputChoiceType) { - case SYS_OUT: - return System.out; - case SYS_ERR: - return System.err; - case CACHED_SYS_ERR: - case CACHED_SYS_OUT: - case FILE: - return targetPrintStream; - default: - throw new IllegalArgumentException(); - } - - } - -} +package org.slf4j.impl; + +import java.io.PrintStream; + +/** + * This class encapsulates the user's choice of output target. + * + * @author Ceki Gülcü + * + */ +class OutputChoice { + + enum OutputChoiceType { + SYS_OUT, CACHED_SYS_OUT, SYS_ERR, CACHED_SYS_ERR, FILE; + } + + final OutputChoiceType outputChoiceType; + final PrintStream targetPrintStream; + + OutputChoice(OutputChoiceType outputChoiceType) { + if (outputChoiceType == OutputChoiceType.FILE) { + throw new IllegalArgumentException(); + } + this.outputChoiceType = outputChoiceType; + if (outputChoiceType == OutputChoiceType.CACHED_SYS_OUT) { + this.targetPrintStream = System.out; + } else if (outputChoiceType == OutputChoiceType.CACHED_SYS_ERR) { + this.targetPrintStream = System.err; + } else { + this.targetPrintStream = null; + } + } + + OutputChoice(PrintStream printStream) { + this.outputChoiceType = OutputChoiceType.FILE; + this.targetPrintStream = printStream; + } + + PrintStream getTargetPrintStream() { + switch (outputChoiceType) { + case SYS_OUT: + return System.out; + case SYS_ERR: + return System.err; + case CACHED_SYS_ERR: + case CACHED_SYS_OUT: + case FILE: + return targetPrintStream; + default: + throw new IllegalArgumentException(); + } + + } + +} diff --git a/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLogger.java b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLogger.java index 5fceba2..fe79822 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLogger.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLogger.java @@ -1,606 +1,606 @@ -/** - * Copyright (c) 2004-2012 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import java.io.PrintStream; -import java.util.Date; - -import org.slf4j.Logger; -import org.slf4j.event.LoggingEvent; -import org.slf4j.helpers.FormattingTuple; -import org.slf4j.helpers.MarkerIgnoringBase; -import org.slf4j.helpers.MessageFormatter; -import org.slf4j.spi.LocationAwareLogger; - -/** - *

- * Simple implementation of {@link Logger} that sends all enabled log messages, - * for all defined loggers, to the console ({@code System.err}). The following - * system properties are supported to configure the behavior of this logger: - *

- * - *
    - *
  • org.slf4j.simpleLogger.logFile - The output target which can - * be the path to a file, or the special values "System.out" and - * "System.err". Default is "System.err".
  • - * - *
  • org.slf4j.simpleLogger.cacheOutputStream - If the output - * target is set to "System.out" or "System.err" (see preceding entry), by - * default, logs will be output to the latest value referenced by - * System.out/err variables. By setting this - * parameter to true, the output stream will be cached, i.e. assigned once at - * initialization time and re-used independently of the current value referenced by - * System.out/err. - *
  • - * - *
  • org.slf4j.simpleLogger.defaultLogLevel - Default log level - * for all instances of SimpleLogger. Must be one of ("trace", "debug", "info", - * "warn", "error" or "off"). If not specified, defaults to "info".
  • - * - *
  • org.slf4j.simpleLogger.log.a.b.c - Logging detail - * level for a SimpleLogger instance named "a.b.c". Right-side value must be one - * of "trace", "debug", "info", "warn", "error" or "off". When a SimpleLogger - * named "a.b.c" is initialized, its level is assigned from this property. If - * unspecified, the level of nearest parent logger will be used, and if none is - * set, then the value specified by - * org.slf4j.simpleLogger.defaultLogLevel will be used.
  • - * - *
  • org.slf4j.simpleLogger.showDateTime - Set to - * true if you want the current date and time to be included in - * output messages. Default is false
  • - * - *
  • org.slf4j.simpleLogger.dateTimeFormat - The date and time - * format to be used in the output messages. The pattern describing the date and - * time format is defined by - * SimpleDateFormat. If the format is not specified or is - * invalid, the number of milliseconds since start up will be output.
  • - * - *
  • org.slf4j.simpleLogger.showThreadName -Set to - * true if you want to output the current thread name. Defaults to - * true.
  • - * - *
  • org.slf4j.simpleLogger.showLogName - Set to - * true if you want the Logger instance name to be included in - * output messages. Defaults to true.
  • - * - *
  • org.slf4j.simpleLogger.showShortLogName - Set to - * true if you want the last component of the name to be included - * in output messages. Defaults to false.
  • - * - *
  • org.slf4j.simpleLogger.levelInBrackets - Should the level - * string be output in brackets? Defaults to false.
  • - * - *
  • org.slf4j.simpleLogger.warnLevelString - The string value - * output for the warn level. Defaults to WARN.
  • - * - *
- * - *

- * In addition to looking for system properties with the names specified above, - * this implementation also checks for a class loader resource named - * "simplelogger.properties", and includes any matching definitions - * from this resource (if it exists). - *

- * - *

- * With no configuration, the default output includes the relative time in - * milliseconds, thread name, the level, logger name, and the message followed - * by the line separator for the host. In log4j terms it amounts to the "%r [%t] - * %level %logger - %m%n" pattern. - *

- *

- * Sample output follows. - *

- * - *
- * 176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
- * 225 [main] INFO examples.SortAlgo - Entered the sort method.
- * 304 [main] INFO examples.SortAlgo - Dump of integer array:
- * 317 [main] INFO examples.SortAlgo - Element [0] = 0
- * 331 [main] INFO examples.SortAlgo - Element [1] = 1
- * 343 [main] INFO examples.Sort - The next log statement should be an error message.
- * 346 [main] ERROR examples.SortAlgo - Tried to dump an uninitialized array.
- *   at org.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
- *   at org.log4j.examples.Sort.main(Sort.java:64)
- * 467 [main] INFO  examples.Sort - Exiting main method.
- * 
- * - *

- * This implementation is heavily inspired by - * Apache Commons Logging's - * SimpleLog. - *

- * - * @author Ceki Gülcü - * @author Scott Sanders - * @author Rod Waldhoff - * @author Robert Burrell Donkin - * @author Cédrik LIME - */ -public class SimpleLogger extends MarkerIgnoringBase { - - private static final long serialVersionUID = -632788891211436180L; - - private static long START_TIME = System.currentTimeMillis(); - - protected static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT; - protected static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT; - protected static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT; - protected static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT; - protected static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT; - // The OFF level can only be used in configuration files to disable logging. - // It has - // no printing method associated with it in o.s.Logger interface. - protected static final int LOG_LEVEL_OFF = LOG_LEVEL_ERROR + 10; - - private static boolean INITIALIZED = false; - static SimpleLoggerConfiguration CONFIG_PARAMS = null; - - static void lazyInit() { - if (INITIALIZED) { - return; - } - INITIALIZED = true; - init(); - } - - // external software might be invoking this method directly. Do not rename - // or change its semantics. - static void init() { - CONFIG_PARAMS = new SimpleLoggerConfiguration(); - CONFIG_PARAMS.init(); - } - - /** The current log level */ - protected int currentLogLevel = LOG_LEVEL_INFO; - /** The short name of this simple log instance */ - private transient String shortLogName = null; - - /** - * All system properties used by SimpleLogger start with this - * prefix - */ - public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger."; - - public static final String LOG_KEY_PREFIX = SimpleLogger.SYSTEM_PREFIX + "log."; - - public static final String CACHE_OUTPUT_STREAM_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "cacheOutputStream"; - - public static final String WARN_LEVEL_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "warnLevelString"; - - public static final String LEVEL_IN_BRACKETS_KEY = SimpleLogger.SYSTEM_PREFIX + "levelInBrackets"; - - public static final String LOG_FILE_KEY = SimpleLogger.SYSTEM_PREFIX + "logFile"; - - public static final String SHOW_SHORT_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showShortLogName"; - - public static final String SHOW_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showLogName"; - - public static final String SHOW_THREAD_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showThreadName"; - - public static final String DATE_TIME_FORMAT_KEY = SimpleLogger.SYSTEM_PREFIX + "dateTimeFormat"; - - public static final String SHOW_DATE_TIME_KEY = SimpleLogger.SYSTEM_PREFIX + "showDateTime"; - - public static final String DEFAULT_LOG_LEVEL_KEY = SimpleLogger.SYSTEM_PREFIX + "defaultLogLevel"; - - /** - * Package access allows only {@link SimpleLoggerFactory} to instantiate - * SimpleLogger instances. - */ - SimpleLogger(String name) { - this.name = name; - - String levelString = recursivelyComputeLevelString(); - if (levelString != null) { - this.currentLogLevel = SimpleLoggerConfiguration.stringToLevel(levelString); - } else { - this.currentLogLevel = CONFIG_PARAMS.defaultLogLevel; - } - } - - String recursivelyComputeLevelString() { - String tempName = name; - String levelString = null; - int indexOfLastDot = tempName.length(); - while ((levelString == null) && (indexOfLastDot > -1)) { - tempName = tempName.substring(0, indexOfLastDot); - levelString = CONFIG_PARAMS.getStringProperty(SimpleLogger.LOG_KEY_PREFIX + tempName, null); - indexOfLastDot = String.valueOf(tempName).lastIndexOf("."); - } - return levelString; - } - - /** - * This is our internal implementation for logging regular - * (non-parameterized) log messages. - * - * @param level - * One of the LOG_LEVEL_XXX constants defining the log level - * @param message - * The message itself - * @param t - * The exception whose stack trace should be logged - */ - private void log(int level, String message, Throwable t) { - if (!isLevelEnabled(level)) { - return; - } - - StringBuilder buf = new StringBuilder(32); - - // Append date-time if so configured - if (CONFIG_PARAMS.showDateTime) { - if (CONFIG_PARAMS.dateFormatter != null) { - buf.append(getFormattedDate()); - buf.append(' '); - } else { - buf.append(System.currentTimeMillis() - START_TIME); - buf.append(' '); - } - } - - // Append current thread name if so configured - if (CONFIG_PARAMS.showThreadName) { - buf.append('['); - buf.append(Thread.currentThread().getName()); - buf.append("] "); - } - - if (CONFIG_PARAMS.levelInBrackets) - buf.append('['); - - // Append a readable representation of the log level - String levelStr = renderLevel(level); - buf.append(levelStr); - if (CONFIG_PARAMS.levelInBrackets) - buf.append(']'); - buf.append(' '); - - // Append the name of the log instance if so configured - if (CONFIG_PARAMS.showShortLogName) { - if (shortLogName == null) - shortLogName = computeShortName(); - buf.append(String.valueOf(shortLogName)).append(" - "); - } else if (CONFIG_PARAMS.showLogName) { - buf.append(String.valueOf(name)).append(" - "); - } - - // Append the message - buf.append(message); - - write(buf, t); - - } - - protected String renderLevel(int level) { - switch (level) { - case LOG_LEVEL_TRACE: - return "TRACE"; - case LOG_LEVEL_DEBUG: - return ("DEBUG"); - case LOG_LEVEL_INFO: - return "INFO"; - case LOG_LEVEL_WARN: - return CONFIG_PARAMS.warnLevelString; - case LOG_LEVEL_ERROR: - return "ERROR"; - } - throw new IllegalStateException("Unrecognized level [" + level + "]"); - } - - void write(StringBuilder buf, Throwable t) { - PrintStream targetStream = CONFIG_PARAMS.outputChoice.getTargetPrintStream(); - - targetStream.println(buf.toString()); - writeThrowable(t, targetStream); - targetStream.flush(); - } - - protected void writeThrowable(Throwable t, PrintStream targetStream) { - if (t != null) { - t.printStackTrace(targetStream); - } - } - - private String getFormattedDate() { - Date now = new Date(); - String dateText; - synchronized (CONFIG_PARAMS.dateFormatter) { - dateText = CONFIG_PARAMS.dateFormatter.format(now); - } - return dateText; - } - - private String computeShortName() { - return name.substring(name.lastIndexOf(".") + 1); - } - - /** - * For formatted messages, first substitute arguments and then log. - * - * @param level - * @param format - * @param arg1 - * @param arg2 - */ - private void formatAndLog(int level, String format, Object arg1, Object arg2) { - if (!isLevelEnabled(level)) { - return; - } - FormattingTuple tp = MessageFormatter.format(format, arg1, arg2); - log(level, tp.getMessage(), tp.getThrowable()); - } - - /** - * For formatted messages, first substitute arguments and then log. - * - * @param level - * @param format - * @param arguments - * a list of 3 ore more arguments - */ - private void formatAndLog(int level, String format, Object... arguments) { - if (!isLevelEnabled(level)) { - return; - } - FormattingTuple tp = MessageFormatter.arrayFormat(format, arguments); - log(level, tp.getMessage(), tp.getThrowable()); - } - - /** - * Is the given log level currently enabled? - * - * @param logLevel - * is this level enabled? - */ - protected boolean isLevelEnabled(int logLevel) { - // log level are numerically ordered so can use simple numeric - // comparison - return (logLevel >= currentLogLevel); - } - - /** Are {@code trace} messages currently enabled? */ - public boolean isTraceEnabled() { - return isLevelEnabled(LOG_LEVEL_TRACE); - } - - /** - * A simple implementation which logs messages of level TRACE according to - * the format outlined above. - */ - public void trace(String msg) { - log(LOG_LEVEL_TRACE, msg, null); - } - - /** - * Perform single parameter substitution before logging the message of level - * TRACE according to the format outlined above. - */ - public void trace(String format, Object param1) { - formatAndLog(LOG_LEVEL_TRACE, format, param1, null); - } - - /** - * Perform double parameter substitution before logging the message of level - * TRACE according to the format outlined above. - */ - public void trace(String format, Object param1, Object param2) { - formatAndLog(LOG_LEVEL_TRACE, format, param1, param2); - } - - /** - * Perform double parameter substitution before logging the message of level - * TRACE according to the format outlined above. - */ - public void trace(String format, Object... argArray) { - formatAndLog(LOG_LEVEL_TRACE, format, argArray); - } - - /** Log a message of level TRACE, including an exception. */ - public void trace(String msg, Throwable t) { - log(LOG_LEVEL_TRACE, msg, t); - } - - /** Are {@code debug} messages currently enabled? */ - public boolean isDebugEnabled() { - return isLevelEnabled(LOG_LEVEL_DEBUG); - } - - /** - * A simple implementation which logs messages of level DEBUG according to - * the format outlined above. - */ - public void debug(String msg) { - log(LOG_LEVEL_DEBUG, msg, null); - } - - /** - * Perform single parameter substitution before logging the message of level - * DEBUG according to the format outlined above. - */ - public void debug(String format, Object param1) { - formatAndLog(LOG_LEVEL_DEBUG, format, param1, null); - } - - /** - * Perform double parameter substitution before logging the message of level - * DEBUG according to the format outlined above. - */ - public void debug(String format, Object param1, Object param2) { - formatAndLog(LOG_LEVEL_DEBUG, format, param1, param2); - } - - /** - * Perform double parameter substitution before logging the message of level - * DEBUG according to the format outlined above. - */ - public void debug(String format, Object... argArray) { - formatAndLog(LOG_LEVEL_DEBUG, format, argArray); - } - - /** Log a message of level DEBUG, including an exception. */ - public void debug(String msg, Throwable t) { - log(LOG_LEVEL_DEBUG, msg, t); - } - - /** Are {@code info} messages currently enabled? */ - public boolean isInfoEnabled() { - return isLevelEnabled(LOG_LEVEL_INFO); - } - - /** - * A simple implementation which logs messages of level INFO according to - * the format outlined above. - */ - public void info(String msg) { - log(LOG_LEVEL_INFO, msg, null); - } - - /** - * Perform single parameter substitution before logging the message of level - * INFO according to the format outlined above. - */ - public void info(String format, Object arg) { - formatAndLog(LOG_LEVEL_INFO, format, arg, null); - } - - /** - * Perform double parameter substitution before logging the message of level - * INFO according to the format outlined above. - */ - public void info(String format, Object arg1, Object arg2) { - formatAndLog(LOG_LEVEL_INFO, format, arg1, arg2); - } - - /** - * Perform double parameter substitution before logging the message of level - * INFO according to the format outlined above. - */ - public void info(String format, Object... argArray) { - formatAndLog(LOG_LEVEL_INFO, format, argArray); - } - - /** Log a message of level INFO, including an exception. */ - public void info(String msg, Throwable t) { - log(LOG_LEVEL_INFO, msg, t); - } - - /** Are {@code warn} messages currently enabled? */ - public boolean isWarnEnabled() { - return isLevelEnabled(LOG_LEVEL_WARN); - } - - /** - * A simple implementation which always logs messages of level WARN - * according to the format outlined above. - */ - public void warn(String msg) { - log(LOG_LEVEL_WARN, msg, null); - } - - /** - * Perform single parameter substitution before logging the message of level - * WARN according to the format outlined above. - */ - public void warn(String format, Object arg) { - formatAndLog(LOG_LEVEL_WARN, format, arg, null); - } - - /** - * Perform double parameter substitution before logging the message of level - * WARN according to the format outlined above. - */ - public void warn(String format, Object arg1, Object arg2) { - formatAndLog(LOG_LEVEL_WARN, format, arg1, arg2); - } - - /** - * Perform double parameter substitution before logging the message of level - * WARN according to the format outlined above. - */ - public void warn(String format, Object... argArray) { - formatAndLog(LOG_LEVEL_WARN, format, argArray); - } - - /** Log a message of level WARN, including an exception. */ - public void warn(String msg, Throwable t) { - log(LOG_LEVEL_WARN, msg, t); - } - - /** Are {@code error} messages currently enabled? */ - public boolean isErrorEnabled() { - return isLevelEnabled(LOG_LEVEL_ERROR); - } - - /** - * A simple implementation which always logs messages of level ERROR - * according to the format outlined above. - */ - public void error(String msg) { - log(LOG_LEVEL_ERROR, msg, null); - } - - /** - * Perform single parameter substitution before logging the message of level - * ERROR according to the format outlined above. - */ - public void error(String format, Object arg) { - formatAndLog(LOG_LEVEL_ERROR, format, arg, null); - } - - /** - * Perform double parameter substitution before logging the message of level - * ERROR according to the format outlined above. - */ - public void error(String format, Object arg1, Object arg2) { - formatAndLog(LOG_LEVEL_ERROR, format, arg1, arg2); - } - - /** - * Perform double parameter substitution before logging the message of level - * ERROR according to the format outlined above. - */ - public void error(String format, Object... argArray) { - formatAndLog(LOG_LEVEL_ERROR, format, argArray); - } - - /** Log a message of level ERROR, including an exception. */ - public void error(String msg, Throwable t) { - log(LOG_LEVEL_ERROR, msg, t); - } - - public void log(LoggingEvent event) { - int levelInt = event.getLevel().toInt(); - - if (!isLevelEnabled(levelInt)) { - return; - } - FormattingTuple tp = MessageFormatter.arrayFormat(event.getMessage(), event.getArgumentArray(), event.getThrowable()); - log(levelInt, tp.getMessage(), event.getThrowable()); - } - -} +/** + * Copyright (c) 2004-2012 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import java.io.PrintStream; +import java.util.Date; + +import org.slf4j.Logger; +import org.slf4j.event.LoggingEvent; +import org.slf4j.helpers.FormattingTuple; +import org.slf4j.helpers.MarkerIgnoringBase; +import org.slf4j.helpers.MessageFormatter; +import org.slf4j.spi.LocationAwareLogger; + +/** + *

+ * Simple implementation of {@link Logger} that sends all enabled log messages, + * for all defined loggers, to the console ({@code System.err}). The following + * system properties are supported to configure the behavior of this logger: + *

+ * + *
    + *
  • org.slf4j.simpleLogger.logFile - The output target which can + * be the path to a file, or the special values "System.out" and + * "System.err". Default is "System.err".
  • + * + *
  • org.slf4j.simpleLogger.cacheOutputStream - If the output + * target is set to "System.out" or "System.err" (see preceding entry), by + * default, logs will be output to the latest value referenced by + * System.out/err variables. By setting this + * parameter to true, the output stream will be cached, i.e. assigned once at + * initialization time and re-used independently of the current value referenced by + * System.out/err. + *
  • + * + *
  • org.slf4j.simpleLogger.defaultLogLevel - Default log level + * for all instances of SimpleLogger. Must be one of ("trace", "debug", "info", + * "warn", "error" or "off"). If not specified, defaults to "info".
  • + * + *
  • org.slf4j.simpleLogger.log.a.b.c - Logging detail + * level for a SimpleLogger instance named "a.b.c". Right-side value must be one + * of "trace", "debug", "info", "warn", "error" or "off". When a SimpleLogger + * named "a.b.c" is initialized, its level is assigned from this property. If + * unspecified, the level of nearest parent logger will be used, and if none is + * set, then the value specified by + * org.slf4j.simpleLogger.defaultLogLevel will be used.
  • + * + *
  • org.slf4j.simpleLogger.showDateTime - Set to + * true if you want the current date and time to be included in + * output messages. Default is false
  • + * + *
  • org.slf4j.simpleLogger.dateTimeFormat - The date and time + * format to be used in the output messages. The pattern describing the date and + * time format is defined by + * SimpleDateFormat. If the format is not specified or is + * invalid, the number of milliseconds since start up will be output.
  • + * + *
  • org.slf4j.simpleLogger.showThreadName -Set to + * true if you want to output the current thread name. Defaults to + * true.
  • + * + *
  • org.slf4j.simpleLogger.showLogName - Set to + * true if you want the Logger instance name to be included in + * output messages. Defaults to true.
  • + * + *
  • org.slf4j.simpleLogger.showShortLogName - Set to + * true if you want the last component of the name to be included + * in output messages. Defaults to false.
  • + * + *
  • org.slf4j.simpleLogger.levelInBrackets - Should the level + * string be output in brackets? Defaults to false.
  • + * + *
  • org.slf4j.simpleLogger.warnLevelString - The string value + * output for the warn level. Defaults to WARN.
  • + * + *
+ * + *

+ * In addition to looking for system properties with the names specified above, + * this implementation also checks for a class loader resource named + * "simplelogger.properties", and includes any matching definitions + * from this resource (if it exists). + *

+ * + *

+ * With no configuration, the default output includes the relative time in + * milliseconds, thread name, the level, logger name, and the message followed + * by the line separator for the host. In log4j terms it amounts to the "%r [%t] + * %level %logger - %m%n" pattern. + *

+ *

+ * Sample output follows. + *

+ * + *
+ * 176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
+ * 225 [main] INFO examples.SortAlgo - Entered the sort method.
+ * 304 [main] INFO examples.SortAlgo - Dump of integer array:
+ * 317 [main] INFO examples.SortAlgo - Element [0] = 0
+ * 331 [main] INFO examples.SortAlgo - Element [1] = 1
+ * 343 [main] INFO examples.Sort - The next log statement should be an error message.
+ * 346 [main] ERROR examples.SortAlgo - Tried to dump an uninitialized array.
+ *   at org.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
+ *   at org.log4j.examples.Sort.main(Sort.java:64)
+ * 467 [main] INFO  examples.Sort - Exiting main method.
+ * 
+ * + *

+ * This implementation is heavily inspired by + * Apache Commons Logging's + * SimpleLog. + *

+ * + * @author Ceki Gülcü + * @author Scott Sanders + * @author Rod Waldhoff + * @author Robert Burrell Donkin + * @author Cédrik LIME + */ +public class SimpleLogger extends MarkerIgnoringBase { + + private static final long serialVersionUID = -632788891211436180L; + + private static long START_TIME = System.currentTimeMillis(); + + protected static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT; + protected static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT; + protected static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT; + protected static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT; + protected static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT; + // The OFF level can only be used in configuration files to disable logging. + // It has + // no printing method associated with it in o.s.Logger interface. + protected static final int LOG_LEVEL_OFF = LOG_LEVEL_ERROR + 10; + + private static boolean INITIALIZED = false; + static SimpleLoggerConfiguration CONFIG_PARAMS = null; + + static void lazyInit() { + if (INITIALIZED) { + return; + } + INITIALIZED = true; + init(); + } + + // external software might be invoking this method directly. Do not rename + // or change its semantics. + static void init() { + CONFIG_PARAMS = new SimpleLoggerConfiguration(); + CONFIG_PARAMS.init(); + } + + /** The current log level */ + protected int currentLogLevel = LOG_LEVEL_INFO; + /** The short name of this simple log instance */ + private transient String shortLogName = null; + + /** + * All system properties used by SimpleLogger start with this + * prefix + */ + public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger."; + + public static final String LOG_KEY_PREFIX = SimpleLogger.SYSTEM_PREFIX + "log."; + + public static final String CACHE_OUTPUT_STREAM_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "cacheOutputStream"; + + public static final String WARN_LEVEL_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "warnLevelString"; + + public static final String LEVEL_IN_BRACKETS_KEY = SimpleLogger.SYSTEM_PREFIX + "levelInBrackets"; + + public static final String LOG_FILE_KEY = SimpleLogger.SYSTEM_PREFIX + "logFile"; + + public static final String SHOW_SHORT_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showShortLogName"; + + public static final String SHOW_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showLogName"; + + public static final String SHOW_THREAD_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showThreadName"; + + public static final String DATE_TIME_FORMAT_KEY = SimpleLogger.SYSTEM_PREFIX + "dateTimeFormat"; + + public static final String SHOW_DATE_TIME_KEY = SimpleLogger.SYSTEM_PREFIX + "showDateTime"; + + public static final String DEFAULT_LOG_LEVEL_KEY = SimpleLogger.SYSTEM_PREFIX + "defaultLogLevel"; + + /** + * Package access allows only {@link SimpleLoggerFactory} to instantiate + * SimpleLogger instances. + */ + SimpleLogger(String name) { + this.name = name; + + String levelString = recursivelyComputeLevelString(); + if (levelString != null) { + this.currentLogLevel = SimpleLoggerConfiguration.stringToLevel(levelString); + } else { + this.currentLogLevel = CONFIG_PARAMS.defaultLogLevel; + } + } + + String recursivelyComputeLevelString() { + String tempName = name; + String levelString = null; + int indexOfLastDot = tempName.length(); + while ((levelString == null) && (indexOfLastDot > -1)) { + tempName = tempName.substring(0, indexOfLastDot); + levelString = CONFIG_PARAMS.getStringProperty(SimpleLogger.LOG_KEY_PREFIX + tempName, null); + indexOfLastDot = String.valueOf(tempName).lastIndexOf("."); + } + return levelString; + } + + /** + * This is our internal implementation for logging regular + * (non-parameterized) log messages. + * + * @param level + * One of the LOG_LEVEL_XXX constants defining the log level + * @param message + * The message itself + * @param t + * The exception whose stack trace should be logged + */ + private void log(int level, String message, Throwable t) { + if (!isLevelEnabled(level)) { + return; + } + + StringBuilder buf = new StringBuilder(32); + + // Append date-time if so configured + if (CONFIG_PARAMS.showDateTime) { + if (CONFIG_PARAMS.dateFormatter != null) { + buf.append(getFormattedDate()); + buf.append(' '); + } else { + buf.append(System.currentTimeMillis() - START_TIME); + buf.append(' '); + } + } + + // Append current thread name if so configured + if (CONFIG_PARAMS.showThreadName) { + buf.append('['); + buf.append(Thread.currentThread().getName()); + buf.append("] "); + } + + if (CONFIG_PARAMS.levelInBrackets) + buf.append('['); + + // Append a readable representation of the log level + String levelStr = renderLevel(level); + buf.append(levelStr); + if (CONFIG_PARAMS.levelInBrackets) + buf.append(']'); + buf.append(' '); + + // Append the name of the log instance if so configured + if (CONFIG_PARAMS.showShortLogName) { + if (shortLogName == null) + shortLogName = computeShortName(); + buf.append(String.valueOf(shortLogName)).append(" - "); + } else if (CONFIG_PARAMS.showLogName) { + buf.append(String.valueOf(name)).append(" - "); + } + + // Append the message + buf.append(message); + + write(buf, t); + + } + + protected String renderLevel(int level) { + switch (level) { + case LOG_LEVEL_TRACE: + return "TRACE"; + case LOG_LEVEL_DEBUG: + return ("DEBUG"); + case LOG_LEVEL_INFO: + return "INFO"; + case LOG_LEVEL_WARN: + return CONFIG_PARAMS.warnLevelString; + case LOG_LEVEL_ERROR: + return "ERROR"; + } + throw new IllegalStateException("Unrecognized level [" + level + "]"); + } + + void write(StringBuilder buf, Throwable t) { + PrintStream targetStream = CONFIG_PARAMS.outputChoice.getTargetPrintStream(); + + targetStream.println(buf.toString()); + writeThrowable(t, targetStream); + targetStream.flush(); + } + + protected void writeThrowable(Throwable t, PrintStream targetStream) { + if (t != null) { + t.printStackTrace(targetStream); + } + } + + private String getFormattedDate() { + Date now = new Date(); + String dateText; + synchronized (CONFIG_PARAMS.dateFormatter) { + dateText = CONFIG_PARAMS.dateFormatter.format(now); + } + return dateText; + } + + private String computeShortName() { + return name.substring(name.lastIndexOf(".") + 1); + } + + /** + * For formatted messages, first substitute arguments and then log. + * + * @param level + * @param format + * @param arg1 + * @param arg2 + */ + private void formatAndLog(int level, String format, Object arg1, Object arg2) { + if (!isLevelEnabled(level)) { + return; + } + FormattingTuple tp = MessageFormatter.format(format, arg1, arg2); + log(level, tp.getMessage(), tp.getThrowable()); + } + + /** + * For formatted messages, first substitute arguments and then log. + * + * @param level + * @param format + * @param arguments + * a list of 3 ore more arguments + */ + private void formatAndLog(int level, String format, Object... arguments) { + if (!isLevelEnabled(level)) { + return; + } + FormattingTuple tp = MessageFormatter.arrayFormat(format, arguments); + log(level, tp.getMessage(), tp.getThrowable()); + } + + /** + * Is the given log level currently enabled? + * + * @param logLevel + * is this level enabled? + */ + protected boolean isLevelEnabled(int logLevel) { + // log level are numerically ordered so can use simple numeric + // comparison + return (logLevel >= currentLogLevel); + } + + /** Are {@code trace} messages currently enabled? */ + public boolean isTraceEnabled() { + return isLevelEnabled(LOG_LEVEL_TRACE); + } + + /** + * A simple implementation which logs messages of level TRACE according to + * the format outlined above. + */ + public void trace(String msg) { + log(LOG_LEVEL_TRACE, msg, null); + } + + /** + * Perform single parameter substitution before logging the message of level + * TRACE according to the format outlined above. + */ + public void trace(String format, Object param1) { + formatAndLog(LOG_LEVEL_TRACE, format, param1, null); + } + + /** + * Perform double parameter substitution before logging the message of level + * TRACE according to the format outlined above. + */ + public void trace(String format, Object param1, Object param2) { + formatAndLog(LOG_LEVEL_TRACE, format, param1, param2); + } + + /** + * Perform double parameter substitution before logging the message of level + * TRACE according to the format outlined above. + */ + public void trace(String format, Object... argArray) { + formatAndLog(LOG_LEVEL_TRACE, format, argArray); + } + + /** Log a message of level TRACE, including an exception. */ + public void trace(String msg, Throwable t) { + log(LOG_LEVEL_TRACE, msg, t); + } + + /** Are {@code debug} messages currently enabled? */ + public boolean isDebugEnabled() { + return isLevelEnabled(LOG_LEVEL_DEBUG); + } + + /** + * A simple implementation which logs messages of level DEBUG according to + * the format outlined above. + */ + public void debug(String msg) { + log(LOG_LEVEL_DEBUG, msg, null); + } + + /** + * Perform single parameter substitution before logging the message of level + * DEBUG according to the format outlined above. + */ + public void debug(String format, Object param1) { + formatAndLog(LOG_LEVEL_DEBUG, format, param1, null); + } + + /** + * Perform double parameter substitution before logging the message of level + * DEBUG according to the format outlined above. + */ + public void debug(String format, Object param1, Object param2) { + formatAndLog(LOG_LEVEL_DEBUG, format, param1, param2); + } + + /** + * Perform double parameter substitution before logging the message of level + * DEBUG according to the format outlined above. + */ + public void debug(String format, Object... argArray) { + formatAndLog(LOG_LEVEL_DEBUG, format, argArray); + } + + /** Log a message of level DEBUG, including an exception. */ + public void debug(String msg, Throwable t) { + log(LOG_LEVEL_DEBUG, msg, t); + } + + /** Are {@code info} messages currently enabled? */ + public boolean isInfoEnabled() { + return isLevelEnabled(LOG_LEVEL_INFO); + } + + /** + * A simple implementation which logs messages of level INFO according to + * the format outlined above. + */ + public void info(String msg) { + log(LOG_LEVEL_INFO, msg, null); + } + + /** + * Perform single parameter substitution before logging the message of level + * INFO according to the format outlined above. + */ + public void info(String format, Object arg) { + formatAndLog(LOG_LEVEL_INFO, format, arg, null); + } + + /** + * Perform double parameter substitution before logging the message of level + * INFO according to the format outlined above. + */ + public void info(String format, Object arg1, Object arg2) { + formatAndLog(LOG_LEVEL_INFO, format, arg1, arg2); + } + + /** + * Perform double parameter substitution before logging the message of level + * INFO according to the format outlined above. + */ + public void info(String format, Object... argArray) { + formatAndLog(LOG_LEVEL_INFO, format, argArray); + } + + /** Log a message of level INFO, including an exception. */ + public void info(String msg, Throwable t) { + log(LOG_LEVEL_INFO, msg, t); + } + + /** Are {@code warn} messages currently enabled? */ + public boolean isWarnEnabled() { + return isLevelEnabled(LOG_LEVEL_WARN); + } + + /** + * A simple implementation which always logs messages of level WARN + * according to the format outlined above. + */ + public void warn(String msg) { + log(LOG_LEVEL_WARN, msg, null); + } + + /** + * Perform single parameter substitution before logging the message of level + * WARN according to the format outlined above. + */ + public void warn(String format, Object arg) { + formatAndLog(LOG_LEVEL_WARN, format, arg, null); + } + + /** + * Perform double parameter substitution before logging the message of level + * WARN according to the format outlined above. + */ + public void warn(String format, Object arg1, Object arg2) { + formatAndLog(LOG_LEVEL_WARN, format, arg1, arg2); + } + + /** + * Perform double parameter substitution before logging the message of level + * WARN according to the format outlined above. + */ + public void warn(String format, Object... argArray) { + formatAndLog(LOG_LEVEL_WARN, format, argArray); + } + + /** Log a message of level WARN, including an exception. */ + public void warn(String msg, Throwable t) { + log(LOG_LEVEL_WARN, msg, t); + } + + /** Are {@code error} messages currently enabled? */ + public boolean isErrorEnabled() { + return isLevelEnabled(LOG_LEVEL_ERROR); + } + + /** + * A simple implementation which always logs messages of level ERROR + * according to the format outlined above. + */ + public void error(String msg) { + log(LOG_LEVEL_ERROR, msg, null); + } + + /** + * Perform single parameter substitution before logging the message of level + * ERROR according to the format outlined above. + */ + public void error(String format, Object arg) { + formatAndLog(LOG_LEVEL_ERROR, format, arg, null); + } + + /** + * Perform double parameter substitution before logging the message of level + * ERROR according to the format outlined above. + */ + public void error(String format, Object arg1, Object arg2) { + formatAndLog(LOG_LEVEL_ERROR, format, arg1, arg2); + } + + /** + * Perform double parameter substitution before logging the message of level + * ERROR according to the format outlined above. + */ + public void error(String format, Object... argArray) { + formatAndLog(LOG_LEVEL_ERROR, format, argArray); + } + + /** Log a message of level ERROR, including an exception. */ + public void error(String msg, Throwable t) { + log(LOG_LEVEL_ERROR, msg, t); + } + + public void log(LoggingEvent event) { + int levelInt = event.getLevel().toInt(); + + if (!isLevelEnabled(levelInt)) { + return; + } + FormattingTuple tp = MessageFormatter.arrayFormat(event.getMessage(), event.getArgumentArray(), event.getThrowable()); + log(levelInt, tp.getMessage(), event.getThrowable()); + } + +} diff --git a/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerConfiguration.java b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerConfiguration.java old file mode 100644 new file mode 100755 index d538b0f..08c0b05 100755 --- a/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerConfiguration.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerConfiguration.java @@ -1,186 +1,186 @@ -package org.slf4j.impl; - -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.PrintStream; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Properties; - -import org.slf4j.helpers.Util; -import org.slf4j.impl.OutputChoice.OutputChoiceType; - -/** - * This class holds configuration values for {@link SimpleLogger}. The - * values are computed at runtime. See {@link SimpleLogger} documentation for - * more information. - * - * - * @author Ceki Gülcü - * @author Scott Sanders - * @author Rod Waldhoff - * @author Robert Burrell Donkin - * @author Cédrik LIME - * - * @since 1.7.25 - */ -public class SimpleLoggerConfiguration { - - private static final String CONFIGURATION_FILE = "simplelogger.properties"; - - static int DEFAULT_LOG_LEVEL_DEFAULT = SimpleLogger.LOG_LEVEL_INFO; - int defaultLogLevel = DEFAULT_LOG_LEVEL_DEFAULT; - - private static final boolean SHOW_DATE_TIME_DEFAULT = false; - boolean showDateTime = SHOW_DATE_TIME_DEFAULT; - - private static final String DATE_TIME_FORMAT_STR_DEFAULT = null; - private static String dateTimeFormatStr = DATE_TIME_FORMAT_STR_DEFAULT; - - DateFormat dateFormatter = null; - - private static final boolean SHOW_THREAD_NAME_DEFAULT = true; - boolean showThreadName = SHOW_THREAD_NAME_DEFAULT; - - final static boolean SHOW_LOG_NAME_DEFAULT = true; - boolean showLogName = SHOW_LOG_NAME_DEFAULT; - - private static final boolean SHOW_SHORT_LOG_NAME_DEFAULT = false; - boolean showShortLogName = SHOW_SHORT_LOG_NAME_DEFAULT; - - private static final boolean LEVEL_IN_BRACKETS_DEFAULT = false; - boolean levelInBrackets = LEVEL_IN_BRACKETS_DEFAULT; - - private static String LOG_FILE_DEFAULT = "System.err"; - private String logFile = LOG_FILE_DEFAULT; - OutputChoice outputChoice = null; - - private static final boolean CACHE_OUTPUT_STREAM_DEFAULT = false; - private boolean cacheOutputStream = CACHE_OUTPUT_STREAM_DEFAULT; - - private static final String WARN_LEVELS_STRING_DEFAULT = "WARN"; - String warnLevelString = WARN_LEVELS_STRING_DEFAULT; - - private final Properties properties = new Properties(); - - void init() { - loadProperties(); - - String defaultLogLevelString = getStringProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, null); - if (defaultLogLevelString != null) - defaultLogLevel = stringToLevel(defaultLogLevelString); - - showLogName = getBooleanProperty(SimpleLogger.SHOW_LOG_NAME_KEY, SimpleLoggerConfiguration.SHOW_LOG_NAME_DEFAULT); - showShortLogName = getBooleanProperty(SimpleLogger.SHOW_SHORT_LOG_NAME_KEY, SHOW_SHORT_LOG_NAME_DEFAULT); - showDateTime = getBooleanProperty(SimpleLogger.SHOW_DATE_TIME_KEY, SHOW_DATE_TIME_DEFAULT); - showThreadName = getBooleanProperty(SimpleLogger.SHOW_THREAD_NAME_KEY, SHOW_THREAD_NAME_DEFAULT); - dateTimeFormatStr = getStringProperty(SimpleLogger.DATE_TIME_FORMAT_KEY, DATE_TIME_FORMAT_STR_DEFAULT); - levelInBrackets = getBooleanProperty(SimpleLogger.LEVEL_IN_BRACKETS_KEY, LEVEL_IN_BRACKETS_DEFAULT); - warnLevelString = getStringProperty(SimpleLogger.WARN_LEVEL_STRING_KEY, WARN_LEVELS_STRING_DEFAULT); - - logFile = getStringProperty(SimpleLogger.LOG_FILE_KEY, logFile); - - cacheOutputStream = getBooleanProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, CACHE_OUTPUT_STREAM_DEFAULT); - outputChoice = computeOutputChoice(logFile, cacheOutputStream); - - if (dateTimeFormatStr != null) { - try { - dateFormatter = new SimpleDateFormat(dateTimeFormatStr); - } catch (IllegalArgumentException e) { - Util.report("Bad date format in " + CONFIGURATION_FILE + "; will output relative time", e); - } - } - } - - private void loadProperties() { - // Add props from the resource simplelogger.properties - InputStream in = AccessController.doPrivileged(new PrivilegedAction() { - public InputStream run() { - ClassLoader threadCL = Thread.currentThread().getContextClassLoader(); - if (threadCL != null) { - return threadCL.getResourceAsStream(CONFIGURATION_FILE); - } else { - return ClassLoader.getSystemResourceAsStream(CONFIGURATION_FILE); - } - } - }); - if (null != in) { - try { - properties.load(in); - } catch (java.io.IOException e) { - // ignored - } finally { - try { - in.close(); - } catch (java.io.IOException e) { - // ignored - } - } - } - } - - String getStringProperty(String name, String defaultValue) { - String prop = getStringProperty(name); - return (prop == null) ? defaultValue : prop; - } - - boolean getBooleanProperty(String name, boolean defaultValue) { - String prop = getStringProperty(name); - return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop); - } - - String getStringProperty(String name) { - String prop = null; - try { - prop = System.getProperty(name); - } catch (SecurityException e) { - ; // Ignore - } - return (prop == null) ? properties.getProperty(name) : prop; - } - - static int stringToLevel(String levelStr) { - if ("trace".equalsIgnoreCase(levelStr)) { - return SimpleLogger.LOG_LEVEL_TRACE; - } else if ("debug".equalsIgnoreCase(levelStr)) { - return SimpleLogger.LOG_LEVEL_DEBUG; - } else if ("info".equalsIgnoreCase(levelStr)) { - return SimpleLogger.LOG_LEVEL_INFO; - } else if ("warn".equalsIgnoreCase(levelStr)) { - return SimpleLogger.LOG_LEVEL_WARN; - } else if ("error".equalsIgnoreCase(levelStr)) { - return SimpleLogger.LOG_LEVEL_ERROR; - } else if ("off".equalsIgnoreCase(levelStr)) { - return SimpleLogger.LOG_LEVEL_OFF; - } - // assume INFO by default - return SimpleLogger.LOG_LEVEL_INFO; - } - - private static OutputChoice computeOutputChoice(String logFile, boolean cacheOutputStream) { - if ("System.err".equalsIgnoreCase(logFile)) - if (cacheOutputStream) - return new OutputChoice(OutputChoiceType.CACHED_SYS_ERR); - else - return new OutputChoice(OutputChoiceType.SYS_ERR); - else if ("System.out".equalsIgnoreCase(logFile)) { - if (cacheOutputStream) - return new OutputChoice(OutputChoiceType.CACHED_SYS_OUT); - else - return new OutputChoice(OutputChoiceType.SYS_OUT); - } else { - try { - FileOutputStream fos = new FileOutputStream(logFile); - PrintStream printStream = new PrintStream(fos); - return new OutputChoice(printStream); - } catch (FileNotFoundException e) { - Util.report("Could not open [" + logFile + "]. Defaulting to System.err", e); - return new OutputChoice(OutputChoiceType.SYS_ERR); - } - } - } - -} +package org.slf4j.impl; + +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.PrintStream; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Properties; + +import org.slf4j.helpers.Util; +import org.slf4j.impl.OutputChoice.OutputChoiceType; + +/** + * This class holds configuration values for {@link SimpleLogger}. The + * values are computed at runtime. See {@link SimpleLogger} documentation for + * more information. + * + * + * @author Ceki Gülcü + * @author Scott Sanders + * @author Rod Waldhoff + * @author Robert Burrell Donkin + * @author Cédrik LIME + * + * @since 1.7.25 + */ +public class SimpleLoggerConfiguration { + + private static final String CONFIGURATION_FILE = "simplelogger.properties"; + + static int DEFAULT_LOG_LEVEL_DEFAULT = SimpleLogger.LOG_LEVEL_INFO; + int defaultLogLevel = DEFAULT_LOG_LEVEL_DEFAULT; + + private static final boolean SHOW_DATE_TIME_DEFAULT = false; + boolean showDateTime = SHOW_DATE_TIME_DEFAULT; + + private static final String DATE_TIME_FORMAT_STR_DEFAULT = null; + private static String dateTimeFormatStr = DATE_TIME_FORMAT_STR_DEFAULT; + + DateFormat dateFormatter = null; + + private static final boolean SHOW_THREAD_NAME_DEFAULT = true; + boolean showThreadName = SHOW_THREAD_NAME_DEFAULT; + + final static boolean SHOW_LOG_NAME_DEFAULT = true; + boolean showLogName = SHOW_LOG_NAME_DEFAULT; + + private static final boolean SHOW_SHORT_LOG_NAME_DEFAULT = false; + boolean showShortLogName = SHOW_SHORT_LOG_NAME_DEFAULT; + + private static final boolean LEVEL_IN_BRACKETS_DEFAULT = false; + boolean levelInBrackets = LEVEL_IN_BRACKETS_DEFAULT; + + private static String LOG_FILE_DEFAULT = "System.err"; + private String logFile = LOG_FILE_DEFAULT; + OutputChoice outputChoice = null; + + private static final boolean CACHE_OUTPUT_STREAM_DEFAULT = false; + private boolean cacheOutputStream = CACHE_OUTPUT_STREAM_DEFAULT; + + private static final String WARN_LEVELS_STRING_DEFAULT = "WARN"; + String warnLevelString = WARN_LEVELS_STRING_DEFAULT; + + private final Properties properties = new Properties(); + + void init() { + loadProperties(); + + String defaultLogLevelString = getStringProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, null); + if (defaultLogLevelString != null) + defaultLogLevel = stringToLevel(defaultLogLevelString); + + showLogName = getBooleanProperty(SimpleLogger.SHOW_LOG_NAME_KEY, SimpleLoggerConfiguration.SHOW_LOG_NAME_DEFAULT); + showShortLogName = getBooleanProperty(SimpleLogger.SHOW_SHORT_LOG_NAME_KEY, SHOW_SHORT_LOG_NAME_DEFAULT); + showDateTime = getBooleanProperty(SimpleLogger.SHOW_DATE_TIME_KEY, SHOW_DATE_TIME_DEFAULT); + showThreadName = getBooleanProperty(SimpleLogger.SHOW_THREAD_NAME_KEY, SHOW_THREAD_NAME_DEFAULT); + dateTimeFormatStr = getStringProperty(SimpleLogger.DATE_TIME_FORMAT_KEY, DATE_TIME_FORMAT_STR_DEFAULT); + levelInBrackets = getBooleanProperty(SimpleLogger.LEVEL_IN_BRACKETS_KEY, LEVEL_IN_BRACKETS_DEFAULT); + warnLevelString = getStringProperty(SimpleLogger.WARN_LEVEL_STRING_KEY, WARN_LEVELS_STRING_DEFAULT); + + logFile = getStringProperty(SimpleLogger.LOG_FILE_KEY, logFile); + + cacheOutputStream = getBooleanProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, CACHE_OUTPUT_STREAM_DEFAULT); + outputChoice = computeOutputChoice(logFile, cacheOutputStream); + + if (dateTimeFormatStr != null) { + try { + dateFormatter = new SimpleDateFormat(dateTimeFormatStr); + } catch (IllegalArgumentException e) { + Util.report("Bad date format in " + CONFIGURATION_FILE + "; will output relative time", e); + } + } + } + + private void loadProperties() { + // Add props from the resource simplelogger.properties + InputStream in = AccessController.doPrivileged(new PrivilegedAction() { + public InputStream run() { + ClassLoader threadCL = Thread.currentThread().getContextClassLoader(); + if (threadCL != null) { + return threadCL.getResourceAsStream(CONFIGURATION_FILE); + } else { + return ClassLoader.getSystemResourceAsStream(CONFIGURATION_FILE); + } + } + }); + if (null != in) { + try { + properties.load(in); + } catch (java.io.IOException e) { + // ignored + } finally { + try { + in.close(); + } catch (java.io.IOException e) { + // ignored + } + } + } + } + + String getStringProperty(String name, String defaultValue) { + String prop = getStringProperty(name); + return (prop == null) ? defaultValue : prop; + } + + boolean getBooleanProperty(String name, boolean defaultValue) { + String prop = getStringProperty(name); + return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop); + } + + String getStringProperty(String name) { + String prop = null; + try { + prop = System.getProperty(name); + } catch (SecurityException e) { + ; // Ignore + } + return (prop == null) ? properties.getProperty(name) : prop; + } + + static int stringToLevel(String levelStr) { + if ("trace".equalsIgnoreCase(levelStr)) { + return SimpleLogger.LOG_LEVEL_TRACE; + } else if ("debug".equalsIgnoreCase(levelStr)) { + return SimpleLogger.LOG_LEVEL_DEBUG; + } else if ("info".equalsIgnoreCase(levelStr)) { + return SimpleLogger.LOG_LEVEL_INFO; + } else if ("warn".equalsIgnoreCase(levelStr)) { + return SimpleLogger.LOG_LEVEL_WARN; + } else if ("error".equalsIgnoreCase(levelStr)) { + return SimpleLogger.LOG_LEVEL_ERROR; + } else if ("off".equalsIgnoreCase(levelStr)) { + return SimpleLogger.LOG_LEVEL_OFF; + } + // assume INFO by default + return SimpleLogger.LOG_LEVEL_INFO; + } + + private static OutputChoice computeOutputChoice(String logFile, boolean cacheOutputStream) { + if ("System.err".equalsIgnoreCase(logFile)) + if (cacheOutputStream) + return new OutputChoice(OutputChoiceType.CACHED_SYS_ERR); + else + return new OutputChoice(OutputChoiceType.SYS_ERR); + else if ("System.out".equalsIgnoreCase(logFile)) { + if (cacheOutputStream) + return new OutputChoice(OutputChoiceType.CACHED_SYS_OUT); + else + return new OutputChoice(OutputChoiceType.SYS_OUT); + } else { + try { + FileOutputStream fos = new FileOutputStream(logFile); + PrintStream printStream = new PrintStream(fos); + return new OutputChoice(printStream); + } catch (FileNotFoundException e) { + Util.report("Could not open [" + logFile + "]. Defaulting to System.err", e); + return new OutputChoice(OutputChoiceType.SYS_ERR); + } + } + } + +} diff --git a/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerFactory.java b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerFactory.java index 0732bfb..9a851f8 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerFactory.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerFactory.java @@ -1,74 +1,74 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.slf4j.Logger; -import org.slf4j.ILoggerFactory; - -/** - * An implementation of {@link ILoggerFactory} which always returns - * {@link SimpleLogger} instances. - * - * @author Ceki Gülcü - */ -public class SimpleLoggerFactory implements ILoggerFactory { - - ConcurrentMap loggerMap; - - public SimpleLoggerFactory() { - loggerMap = new ConcurrentHashMap(); - SimpleLogger.lazyInit(); - } - - /** - * Return an appropriate {@link SimpleLogger} instance by name. - */ - public Logger getLogger(String name) { - Logger simpleLogger = loggerMap.get(name); - if (simpleLogger != null) { - return simpleLogger; - } else { - Logger newInstance = new SimpleLogger(name); - Logger oldInstance = loggerMap.putIfAbsent(name, newInstance); - return oldInstance == null ? newInstance : oldInstance; - } - } - - /** - * Clear the internal logger cache. - * - * This method is intended to be called by classes (in the same package) for - * testing purposes. This method is internal. It can be modified, renamed or - * removed at any time without notice. - * - * You are strongly discouraged from calling this method in production code. - */ - void reset() { - loggerMap.clear(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.slf4j.Logger; +import org.slf4j.ILoggerFactory; + +/** + * An implementation of {@link ILoggerFactory} which always returns + * {@link SimpleLogger} instances. + * + * @author Ceki Gülcü + */ +public class SimpleLoggerFactory implements ILoggerFactory { + + ConcurrentMap loggerMap; + + public SimpleLoggerFactory() { + loggerMap = new ConcurrentHashMap(); + SimpleLogger.lazyInit(); + } + + /** + * Return an appropriate {@link SimpleLogger} instance by name. + */ + public Logger getLogger(String name) { + Logger simpleLogger = loggerMap.get(name); + if (simpleLogger != null) { + return simpleLogger; + } else { + Logger newInstance = new SimpleLogger(name); + Logger oldInstance = loggerMap.putIfAbsent(name, newInstance); + return oldInstance == null ? newInstance : oldInstance; + } + } + + /** + * Clear the internal logger cache. + * + * This method is intended to be called by classes (in the same package) for + * testing purposes. This method is internal. It can be modified, renamed or + * removed at any time without notice. + * + * You are strongly discouraged from calling this method in production code. + */ + void reset() { + loggerMap.clear(); + } +} diff --git a/slf4j-simple/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/slf4j-simple/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index ae1ad27..23b6c87 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,81 +1,81 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - * - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - /** - * Declare the version of the SLF4J API this implementation is compiled against. - * The value of this field is modified with each major release. - */ - // to avoid constant folding by the compiler, this field must *not* be final - public static String REQUESTED_API_VERSION = "1.6.99"; // !final - - private static final String loggerFactoryClassStr = SimpleLoggerFactory.class.getName(); - - /** - * The ILoggerFactory instance returned by the {@link #getLoggerFactory} - * method should always be the same object - */ - private final ILoggerFactory loggerFactory; - - private StaticLoggerBinder() { - loggerFactory = new SimpleLoggerFactory(); - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + * + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is modified with each major release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; // !final + + private static final String loggerFactoryClassStr = SimpleLoggerFactory.class.getName(); + + /** + * The ILoggerFactory instance returned by the {@link #getLoggerFactory} + * method should always be the same object + */ + private final ILoggerFactory loggerFactory; + + private StaticLoggerBinder() { + loggerFactory = new SimpleLoggerFactory(); + } + + public ILoggerFactory getLoggerFactory() { + return loggerFactory; + } + + public String getLoggerFactoryClassStr() { + return loggerFactoryClassStr; + } +} diff --git a/slf4j-simple/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/slf4j-simple/src/main/java/org/slf4j/impl/StaticMDCBinder.java index dccb05a..a88f2bf 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,66 +1,66 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import org.slf4j.helpers.NOPMDCAdapter; -import org.slf4j.spi.MDCAdapter; - -/** - * This implementation is bound to {@link NOPMDCAdapter}. - * - * @author Ceki Gülcü - */ -public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - - private StaticMDCBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMDCBinder singleton - * @since 1.7.14 - */ - public static final StaticMDCBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link StaticMDCBinder}. - */ - public MDCAdapter getMDCA() { - return new NOPMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return NOPMDCAdapter.class.getName(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import org.slf4j.helpers.NOPMDCAdapter; +import org.slf4j.spi.MDCAdapter; + +/** + * This implementation is bound to {@link NOPMDCAdapter}. + * + * @author Ceki Gülcü + */ +public class StaticMDCBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMDCBinder singleton + * @since 1.7.14 + */ + public static final StaticMDCBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link StaticMDCBinder}. + */ + public MDCAdapter getMDCA() { + return new NOPMDCAdapter(); + } + + public String getMDCAdapterClassStr() { + return NOPMDCAdapter.class.getName(); + } +} diff --git a/slf4j-simple/src/main/java/org/slf4j/impl/StaticMarkerBinder.java b/slf4j-simple/src/main/java/org/slf4j/impl/StaticMarkerBinder.java index cef7875..f8527af 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,78 +1,78 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ - -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Return the singleton of this class. - * - * @return the StaticMarkerBinder singleton - * @since 1.7.14 - */ - public static StaticMarkerBinder getSingleton() { - return SINGLETON; - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Return the singleton of this class. + * + * @return the StaticMarkerBinder singleton + * @since 1.7.14 + */ + public static StaticMarkerBinder getSingleton() { + return SINGLETON; + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + +} diff --git a/slf4j-simple/src/main/resources/META-INF/MANIFEST.MF b/slf4j-simple/src/main/resources/META-INF/MANIFEST.MF old file mode 100644 new file mode 100755 index 081988f..3d15864 100755 --- a/slf4j-simple/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-simple/src/main/resources/META-INF/MANIFEST.MF @@ -1,13 +1,13 @@ -Implementation-Title: slf4j-simple -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.simple -Bundle-Name: slf4j-simple -Bundle-Vendor: SLF4J.ORG -Require-Bundle: slf4j.api -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, - org.slf4j.spi;version=${parsedVersion.osgiVersion}, - org.slf4j.helpers;version=${parsedVersion.osgiVersion}, - org.slf4j.event;version=${parsedVersion.osgiVersion} +Implementation-Title: slf4j-simple +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.simple +Bundle-Name: slf4j-simple +Bundle-Vendor: SLF4J.ORG +Require-Bundle: slf4j.api +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, + org.slf4j.spi;version=${parsedVersion.osgiVersion}, + org.slf4j.helpers;version=${parsedVersion.osgiVersion}, + org.slf4j.event;version=${parsedVersion.osgiVersion} Fragment-Host: slf4j.apidiff --git a/slf4j-simple/src/test/java/org/slf4j/DetectLoggerNameMismatchTest.java b/slf4j-simple/src/test/java/org/slf4j/DetectLoggerNameMismatchTest.java old file mode 100644 new file mode 100755 index 10939e1..fd1b83d 100755 --- a/slf4j-simple/src/test/java/org/slf4j/DetectLoggerNameMismatchTest.java +++ b/slf4j-simple/src/test/java/org/slf4j/DetectLoggerNameMismatchTest.java @@ -1,136 +1,136 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Tests that detecting logger name mismatches works and doesn't cause problems - * or trigger if disabled. - *

- * This test can't live inside slf4j-api because the NOP Logger doesn't - * remember its name. - * - * @author Alexander Dorokhine - * @author Ceki Gülcü - */ -public class DetectLoggerNameMismatchTest { - - private static final String MISMATCH_STRING = "Detected logger name mismatch"; - - private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - private final PrintStream oldErr = System.err; - - @Before - public void setUp() { - System.setErr(new PrintStream(byteArrayOutputStream)); - } - - @After - public void tearDown() { - setTrialEnabled(false); - System.setErr(oldErr); - } - - /* - * Pass in the wrong class to the Logger with the check disabled, and make sure there are no errors. - */ - @Test - public void testNoTriggerWithoutProperty() { - setTrialEnabled(false); - Logger logger = LoggerFactory.getLogger(String.class); - assertEquals("java.lang.String", logger.getName()); - assertMismatchDetected(false); - } - - /* - * Pass in the wrong class to the Logger with the check enabled, and make sure there ARE errors. - */ - @Test - public void testTriggerWithProperty() { - setTrialEnabled(true); - LoggerFactory.getLogger(String.class); - String s = String.valueOf(byteArrayOutputStream); - assertMismatchDetected(true); - } - - /* - * Checks the whole error message to ensure all the names show up correctly. - */ - @Test - public void testTriggerWholeMessage() { - setTrialEnabled(true); - LoggerFactory.getLogger(String.class); - boolean success = String.valueOf(byteArrayOutputStream).contains( - "Detected logger name mismatch. Given name: \"java.lang.String\"; " + "computed name: \"org.slf4j.DetectLoggerNameMismatchTest\"."); - assertTrue("Actual value of byteArrayOutputStream: " + String.valueOf(byteArrayOutputStream), success); - } - - /* - * Checks that there are no errors with the check enabled if the class matches. - */ - @Test - public void testPassIfMatch() { - setTrialEnabled(true); - Logger logger = LoggerFactory.getLogger(DetectLoggerNameMismatchTest.class); - assertEquals("org.slf4j.DetectLoggerNameMismatchTest", logger.getName()); - assertMismatchDetected(false); - } - - private void assertMismatchDetected(boolean mismatchDetected) { - assertEquals(mismatchDetected, String.valueOf(byteArrayOutputStream).contains(MISMATCH_STRING)); - } - - @Test - public void verifyLoggerDefinedInBaseWithOverridenGetClassMethod() { - setTrialEnabled(true); - Square square = new Square(); - assertEquals("org.slf4j.Square", square.logger.getName()); - assertMismatchDetected(false); - } - - private static void setTrialEnabled(boolean enabled) { - // The system property is read into a static variable at initialization time - // so we cannot just reset the system property to test this feature. - // Therefore we set the variable directly. - LoggerFactory.DETECT_LOGGER_NAME_MISMATCH = enabled; - } -} - -// Used for testing that inheritance is ignored by the checker. -class ShapeBase { - public Logger logger = LoggerFactory.getLogger(getClass()); -} - -class Square extends ShapeBase { -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests that detecting logger name mismatches works and doesn't cause problems + * or trigger if disabled. + *

+ * This test can't live inside slf4j-api because the NOP Logger doesn't + * remember its name. + * + * @author Alexander Dorokhine + * @author Ceki Gülcü + */ +public class DetectLoggerNameMismatchTest { + + private static final String MISMATCH_STRING = "Detected logger name mismatch"; + + private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + private final PrintStream oldErr = System.err; + + @Before + public void setUp() { + System.setErr(new PrintStream(byteArrayOutputStream)); + } + + @After + public void tearDown() { + setTrialEnabled(false); + System.setErr(oldErr); + } + + /* + * Pass in the wrong class to the Logger with the check disabled, and make sure there are no errors. + */ + @Test + public void testNoTriggerWithoutProperty() { + setTrialEnabled(false); + Logger logger = LoggerFactory.getLogger(String.class); + assertEquals("java.lang.String", logger.getName()); + assertMismatchDetected(false); + } + + /* + * Pass in the wrong class to the Logger with the check enabled, and make sure there ARE errors. + */ + @Test + public void testTriggerWithProperty() { + setTrialEnabled(true); + LoggerFactory.getLogger(String.class); + String s = String.valueOf(byteArrayOutputStream); + assertMismatchDetected(true); + } + + /* + * Checks the whole error message to ensure all the names show up correctly. + */ + @Test + public void testTriggerWholeMessage() { + setTrialEnabled(true); + LoggerFactory.getLogger(String.class); + boolean success = String.valueOf(byteArrayOutputStream).contains( + "Detected logger name mismatch. Given name: \"java.lang.String\"; " + "computed name: \"org.slf4j.DetectLoggerNameMismatchTest\"."); + assertTrue("Actual value of byteArrayOutputStream: " + String.valueOf(byteArrayOutputStream), success); + } + + /* + * Checks that there are no errors with the check enabled if the class matches. + */ + @Test + public void testPassIfMatch() { + setTrialEnabled(true); + Logger logger = LoggerFactory.getLogger(DetectLoggerNameMismatchTest.class); + assertEquals("org.slf4j.DetectLoggerNameMismatchTest", logger.getName()); + assertMismatchDetected(false); + } + + private void assertMismatchDetected(boolean mismatchDetected) { + assertEquals(mismatchDetected, String.valueOf(byteArrayOutputStream).contains(MISMATCH_STRING)); + } + + @Test + public void verifyLoggerDefinedInBaseWithOverridenGetClassMethod() { + setTrialEnabled(true); + Square square = new Square(); + assertEquals("org.slf4j.Square", square.logger.getName()); + assertMismatchDetected(false); + } + + private static void setTrialEnabled(boolean enabled) { + // The system property is read into a static variable at initialization time + // so we cannot just reset the system property to test this feature. + // Therefore we set the variable directly. + LoggerFactory.DETECT_LOGGER_NAME_MISMATCH = enabled; + } +} + +// Used for testing that inheritance is ignored by the checker. +class ShapeBase { + public Logger logger = LoggerFactory.getLogger(getClass()); +} + +class Square extends ShapeBase { +} diff --git a/slf4j-simple/src/test/java/org/slf4j/InvocationTest.java b/slf4j-simple/src/test/java/org/slf4j/InvocationTest.java index d21dfe2..33b20eb 100644 --- a/slf4j-simple/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-simple/src/test/java/org/slf4j/InvocationTest.java @@ -1,139 +1,139 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import static org.junit.Assert.assertNull; - -import java.io.PrintStream; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - * - */ -public class InvocationTest { - - PrintStream old = System.err; - - @Before - public void setUp() throws Exception { - System.setErr(new SilentPrintStream(old)); - } - - @After - public void tearDown() throws Exception { - - System.setErr(old); - } - - @Test - public void test1() { - Logger logger = LoggerFactory.getLogger("test1"); - logger.debug("Hello world."); - } - - @Test - public void test2() { - Integer i1 = new Integer(1); - Integer i2 = new Integer(2); - Integer i3 = new Integer(3); - Exception e = new Exception("This is a test exception."); - Logger logger = LoggerFactory.getLogger("test2"); - - logger.debug("Hello world 1."); - logger.debug("Hello world {}", i1); - logger.debug("val={} val={}", i1, i2); - logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); - - logger.debug("Hello world 2", e); - logger.info("Hello world 2."); - - logger.warn("Hello world 3."); - logger.warn("Hello world 3", e); - - logger.error("Hello world 4."); - logger.error("Hello world {}", new Integer(3)); - logger.error("Hello world 4.", e); - } - - // http://jira.qos.ch/browse/SLF4J-69 - // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=78 - @Test - public void testNullParameter_BUG78() { - Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78"); - String[] parameters = null; - String msg = "hello {}"; - logger.info(msg, (Object[]) parameters); - } - - @Test - public void testNull() { - Logger logger = LoggerFactory.getLogger("testNull"); - logger.debug(null); - logger.info(null); - logger.warn(null); - logger.error(null); - - Exception e = new Exception("This is a test exception."); - logger.debug(null, e); - logger.info(null, e); - logger.warn(null, e); - logger.error(null, e); - } - - @Test - public void testMarker() { - Logger logger = LoggerFactory.getLogger("testMarker"); - Marker blue = MarkerFactory.getMarker("BLUE"); - logger.debug(blue, "hello"); - logger.info(blue, "hello"); - logger.warn(blue, "hello"); - logger.error(blue, "hello"); - - logger.debug(blue, "hello {}", "world"); - logger.info(blue, "hello {}", "world"); - logger.warn(blue, "hello {}", "world"); - logger.error(blue, "hello {}", "world"); - - logger.debug(blue, "hello {} and {} ", "world", "universe"); - logger.info(blue, "hello {} and {} ", "world", "universe"); - logger.warn(blue, "hello {} and {} ", "world", "universe"); - logger.error(blue, "hello {} and {} ", "world", "universe"); - } - - @Test - public void testMDC() { - MDC.put("k", "v"); - assertNull(MDC.get("k")); - MDC.remove("k"); - assertNull(MDC.get("k")); - MDC.clear(); - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import static org.junit.Assert.assertNull; + +import java.io.PrintStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * Test whether invoking the SLF4J API causes problems or not. + * + * @author Ceki Gulcu + * + */ +public class InvocationTest { + + PrintStream old = System.err; + + @Before + public void setUp() throws Exception { + System.setErr(new SilentPrintStream(old)); + } + + @After + public void tearDown() throws Exception { + + System.setErr(old); + } + + @Test + public void test1() { + Logger logger = LoggerFactory.getLogger("test1"); + logger.debug("Hello world."); + } + + @Test + public void test2() { + Integer i1 = new Integer(1); + Integer i2 = new Integer(2); + Integer i3 = new Integer(3); + Exception e = new Exception("This is a test exception."); + Logger logger = LoggerFactory.getLogger("test2"); + + logger.debug("Hello world 1."); + logger.debug("Hello world {}", i1); + logger.debug("val={} val={}", i1, i2); + logger.debug("val={} val={} val={}", new Object[] { i1, i2, i3 }); + + logger.debug("Hello world 2", e); + logger.info("Hello world 2."); + + logger.warn("Hello world 3."); + logger.warn("Hello world 3", e); + + logger.error("Hello world 4."); + logger.error("Hello world {}", new Integer(3)); + logger.error("Hello world 4.", e); + } + + // http://jira.qos.ch/browse/SLF4J-69 + // formerly http://bugzilla.slf4j.org/show_bug.cgi?id=78 + @Test + public void testNullParameter_BUG78() { + Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78"); + String[] parameters = null; + String msg = "hello {}"; + logger.info(msg, (Object[]) parameters); + } + + @Test + public void testNull() { + Logger logger = LoggerFactory.getLogger("testNull"); + logger.debug(null); + logger.info(null); + logger.warn(null); + logger.error(null); + + Exception e = new Exception("This is a test exception."); + logger.debug(null, e); + logger.info(null, e); + logger.warn(null, e); + logger.error(null, e); + } + + @Test + public void testMarker() { + Logger logger = LoggerFactory.getLogger("testMarker"); + Marker blue = MarkerFactory.getMarker("BLUE"); + logger.debug(blue, "hello"); + logger.info(blue, "hello"); + logger.warn(blue, "hello"); + logger.error(blue, "hello"); + + logger.debug(blue, "hello {}", "world"); + logger.info(blue, "hello {}", "world"); + logger.warn(blue, "hello {}", "world"); + logger.error(blue, "hello {}", "world"); + + logger.debug(blue, "hello {} and {} ", "world", "universe"); + logger.info(blue, "hello {} and {} ", "world", "universe"); + logger.warn(blue, "hello {} and {} ", "world", "universe"); + logger.error(blue, "hello {} and {} ", "world", "universe"); + } + + @Test + public void testMDC() { + MDC.put("k", "v"); + assertNull(MDC.get("k")); + MDC.remove("k"); + assertNull(MDC.get("k")); + MDC.clear(); + } +} diff --git a/slf4j-simple/src/test/java/org/slf4j/LoggerFactoryFriend.java b/slf4j-simple/src/test/java/org/slf4j/LoggerFactoryFriend.java old file mode 100644 new file mode 100755 index edf5fcf..4398d3b 100755 --- a/slf4j-simple/src/test/java/org/slf4j/LoggerFactoryFriend.java +++ b/slf4j-simple/src/test/java/org/slf4j/LoggerFactoryFriend.java @@ -1,7 +1,7 @@ -package org.slf4j; - -public class LoggerFactoryFriend { - static public void reset() { - LoggerFactory.reset(); - } -} +package org.slf4j; + +public class LoggerFactoryFriend { + static public void reset() { + LoggerFactory.reset(); + } +} diff --git a/slf4j-simple/src/test/java/org/slf4j/SilentPrintStream.java b/slf4j-simple/src/test/java/org/slf4j/SilentPrintStream.java index 5e7b257..1d710d9 100644 --- a/slf4j-simple/src/test/java/org/slf4j/SilentPrintStream.java +++ b/slf4j-simple/src/test/java/org/slf4j/SilentPrintStream.java @@ -1,46 +1,46 @@ -/** - * Copyright (c) 2004-2011 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j; - -import java.io.PrintStream; - -public class SilentPrintStream extends PrintStream { - - PrintStream other; - - public SilentPrintStream(PrintStream ps) { - super(ps); - other = ps; - } - - public void print(String s) { - } - - public void println(String s) { - } - - public void println(Object x) { - } -} +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j; + +import java.io.PrintStream; + +public class SilentPrintStream extends PrintStream { + + PrintStream other; + + public SilentPrintStream(PrintStream ps) { + super(ps); + other = ps; + } + + public void print(String s) { + } + + public void println(String s) { + } + + public void println(Object x) { + } +} diff --git a/slf4j-simple/src/test/java/org/slf4j/helpers/SimpleLoggerMultithreadedInitializationTest.java b/slf4j-simple/src/test/java/org/slf4j/helpers/SimpleLoggerMultithreadedInitializationTest.java index 967da70..853619d 100644 --- a/slf4j-simple/src/test/java/org/slf4j/helpers/SimpleLoggerMultithreadedInitializationTest.java +++ b/slf4j-simple/src/test/java/org/slf4j/helpers/SimpleLoggerMultithreadedInitializationTest.java @@ -1,112 +1,112 @@ -/** - * Copyright (c) 2004-2016 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.helpers; - -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.slf4j.LoggerFactoryFriend; -import org.slf4j.impl.SimpleLogger; - -public class SimpleLoggerMultithreadedInitializationTest extends MultithreadedInitializationTest { - // final static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2; - // private final List createdLoggers = Collections.synchronizedList(new ArrayList()); - // private final AtomicLong eventCount = new AtomicLong(0); - // - // private final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); - // - // final int diff = new Random().nextInt(10000); - static int NUM_LINES_IN_SLF4J_REPLAY_WARNING = 3; - private final PrintStream oldErr = System.err; - final String loggerName = this.getClass().getName(); - StringPrintStream sps = new StringPrintStream(oldErr, true); - - @Before - public void setup() { - System.out.println("THREAD_COUNT=" + THREAD_COUNT); - System.setErr(sps); - System.setProperty(SimpleLogger.LOG_FILE_KEY, "System.err"); - LoggerFactoryFriend.reset(); - } - - @After - public void tearDown() throws Exception { - LoggerFactoryFriend.reset(); - System.clearProperty(SimpleLogger.LOG_FILE_KEY); - System.setErr(oldErr); - } - - @Override - protected long getRecordedEventCount() { - return sps.stringList.size(); - }; - - @Override - protected int extraLogEvents() { - return NUM_LINES_IN_SLF4J_REPLAY_WARNING; - } - - static class StringPrintStream extends PrintStream { - - public static final String LINE_SEP = System.getProperty("line.separator"); - PrintStream other; - boolean duplicate = false; - - List stringList = Collections.synchronizedList(new ArrayList()); - - public StringPrintStream(PrintStream ps, boolean duplicate) { - super(ps); - other = ps; - this.duplicate = duplicate; - } - - public StringPrintStream(PrintStream ps) { - this(ps, false); - } - - public void print(String s) { - if (duplicate) - other.print(s); - stringList.add(s); - } - - public void println(String s) { - if (duplicate) - other.println(s); - stringList.add(s); - } - - public void println(Object o) { - if (duplicate) - other.println(o); - stringList.add(o.toString()); - } - } - -} +/** + * Copyright (c) 2004-2016 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.helpers; + +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.slf4j.LoggerFactoryFriend; +import org.slf4j.impl.SimpleLogger; + +public class SimpleLoggerMultithreadedInitializationTest extends MultithreadedInitializationTest { + // final static int THREAD_COUNT = 4 + Runtime.getRuntime().availableProcessors() * 2; + // private final List createdLoggers = Collections.synchronizedList(new ArrayList()); + // private final AtomicLong eventCount = new AtomicLong(0); + // + // private final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); + // + // final int diff = new Random().nextInt(10000); + static int NUM_LINES_IN_SLF4J_REPLAY_WARNING = 3; + private final PrintStream oldErr = System.err; + final String loggerName = this.getClass().getName(); + StringPrintStream sps = new StringPrintStream(oldErr, true); + + @Before + public void setup() { + System.out.println("THREAD_COUNT=" + THREAD_COUNT); + System.setErr(sps); + System.setProperty(SimpleLogger.LOG_FILE_KEY, "System.err"); + LoggerFactoryFriend.reset(); + } + + @After + public void tearDown() throws Exception { + LoggerFactoryFriend.reset(); + System.clearProperty(SimpleLogger.LOG_FILE_KEY); + System.setErr(oldErr); + } + + @Override + protected long getRecordedEventCount() { + return sps.stringList.size(); + }; + + @Override + protected int extraLogEvents() { + return NUM_LINES_IN_SLF4J_REPLAY_WARNING; + } + + static class StringPrintStream extends PrintStream { + + public static final String LINE_SEP = System.getProperty("line.separator"); + PrintStream other; + boolean duplicate = false; + + List stringList = Collections.synchronizedList(new ArrayList()); + + public StringPrintStream(PrintStream ps, boolean duplicate) { + super(ps); + other = ps; + this.duplicate = duplicate; + } + + public StringPrintStream(PrintStream ps) { + this(ps, false); + } + + public void print(String s) { + if (duplicate) + other.print(s); + stringList.add(s); + } + + public void println(String s) { + if (duplicate) + other.println(s); + stringList.add(s); + } + + public void println(Object o) { + if (duplicate) + other.println(o); + stringList.add(o.toString()); + } + } + +} diff --git a/slf4j-simple/src/test/java/org/slf4j/impl/SimpleLoggerTest.java b/slf4j-simple/src/test/java/org/slf4j/impl/SimpleLoggerTest.java index 4e1fe30..620e3ab 100644 --- a/slf4j-simple/src/test/java/org/slf4j/impl/SimpleLoggerTest.java +++ b/slf4j-simple/src/test/java/org/slf4j/impl/SimpleLoggerTest.java @@ -1,123 +1,123 @@ -/** - * Copyright (c) 2004-2012 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - */ -package org.slf4j.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SimpleLoggerTest { - - String A_KEY = SimpleLogger.LOG_KEY_PREFIX + "a"; - PrintStream original = System.out; - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - PrintStream replacement = new PrintStream(bout); - - @Before - public void before() { - System.setProperty(A_KEY, "info"); - } - - @After - public void after() { - System.clearProperty(A_KEY); - System.clearProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY); - System.setErr(original); - } - - @Test - public void emptyLoggerName() { - SimpleLogger simpleLogger = new SimpleLogger("a"); - assertEquals("info", simpleLogger.recursivelyComputeLevelString()); - } - - @Test - public void offLevel() { - System.setProperty(A_KEY, "off"); - SimpleLogger.init(); - SimpleLogger simpleLogger = new SimpleLogger("a"); - assertEquals("off", simpleLogger.recursivelyComputeLevelString()); - assertFalse(simpleLogger.isErrorEnabled()); - } - - @Test - public void loggerNameWithNoDots_WithLevel() { - SimpleLogger.init(); - SimpleLogger simpleLogger = new SimpleLogger("a"); - - assertEquals("info", simpleLogger.recursivelyComputeLevelString()); - } - - @Test - public void loggerNameWithOneDotShouldInheritFromParent() { - SimpleLogger simpleLogger = new SimpleLogger("a.b"); - assertEquals("info", simpleLogger.recursivelyComputeLevelString()); - } - - @Test - public void loggerNameWithNoDots_WithNoSetLevel() { - SimpleLogger simpleLogger = new SimpleLogger("x"); - assertNull(simpleLogger.recursivelyComputeLevelString()); - } - - @Test - public void loggerNameWithOneDot_NoSetLevel() { - SimpleLogger simpleLogger = new SimpleLogger("x.y"); - assertNull(simpleLogger.recursivelyComputeLevelString()); - } - - @Test - public void checkUseOfLastSystemStreamReference() { - SimpleLogger.init(); - SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName()); - - System.setErr(replacement); - simpleLogger.info("hello"); - replacement.flush(); - assertTrue(bout.toString().contains("INFO org.slf4j.impl.SimpleLoggerTest - hello")); - } - - @Test - public void checkUseOfCachedOutputStream() { - System.setErr(replacement); - System.setProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, "true"); - SimpleLogger.init(); - SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName()); - // change reference to original before logging - System.setErr(original); - - simpleLogger.info("hello"); - replacement.flush(); - assertTrue(bout.toString().contains("INFO org.slf4j.impl.SimpleLoggerTest - hello")); - } -} +/** + * Copyright (c) 2004-2012 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package org.slf4j.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SimpleLoggerTest { + + String A_KEY = SimpleLogger.LOG_KEY_PREFIX + "a"; + PrintStream original = System.out; + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + PrintStream replacement = new PrintStream(bout); + + @Before + public void before() { + System.setProperty(A_KEY, "info"); + } + + @After + public void after() { + System.clearProperty(A_KEY); + System.clearProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY); + System.setErr(original); + } + + @Test + public void emptyLoggerName() { + SimpleLogger simpleLogger = new SimpleLogger("a"); + assertEquals("info", simpleLogger.recursivelyComputeLevelString()); + } + + @Test + public void offLevel() { + System.setProperty(A_KEY, "off"); + SimpleLogger.init(); + SimpleLogger simpleLogger = new SimpleLogger("a"); + assertEquals("off", simpleLogger.recursivelyComputeLevelString()); + assertFalse(simpleLogger.isErrorEnabled()); + } + + @Test + public void loggerNameWithNoDots_WithLevel() { + SimpleLogger.init(); + SimpleLogger simpleLogger = new SimpleLogger("a"); + + assertEquals("info", simpleLogger.recursivelyComputeLevelString()); + } + + @Test + public void loggerNameWithOneDotShouldInheritFromParent() { + SimpleLogger simpleLogger = new SimpleLogger("a.b"); + assertEquals("info", simpleLogger.recursivelyComputeLevelString()); + } + + @Test + public void loggerNameWithNoDots_WithNoSetLevel() { + SimpleLogger simpleLogger = new SimpleLogger("x"); + assertNull(simpleLogger.recursivelyComputeLevelString()); + } + + @Test + public void loggerNameWithOneDot_NoSetLevel() { + SimpleLogger simpleLogger = new SimpleLogger("x.y"); + assertNull(simpleLogger.recursivelyComputeLevelString()); + } + + @Test + public void checkUseOfLastSystemStreamReference() { + SimpleLogger.init(); + SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName()); + + System.setErr(replacement); + simpleLogger.info("hello"); + replacement.flush(); + assertTrue(bout.toString().contains("INFO org.slf4j.impl.SimpleLoggerTest - hello")); + } + + @Test + public void checkUseOfCachedOutputStream() { + System.setErr(replacement); + System.setProperty(SimpleLogger.CACHE_OUTPUT_STREAM_STRING_KEY, "true"); + SimpleLogger.init(); + SimpleLogger simpleLogger = new SimpleLogger(this.getClass().getName()); + // change reference to original before logging + System.setErr(original); + + simpleLogger.info("hello"); + replacement.flush(); + assertTrue(bout.toString().contains("INFO org.slf4j.impl.SimpleLoggerTest - hello")); + } +} diff --git a/slf4j-simple/src/test/resources/simplelogger.properties b/slf4j-simple/src/test/resources/simplelogger.properties index 208edac..5fdec06 100644 --- a/slf4j-simple/src/test/resources/simplelogger.properties +++ b/slf4j-simple/src/test/resources/simplelogger.properties @@ -1,34 +1,34 @@ -# SLF4J's SimpleLogger configuration file -# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err. - -# Default logging detail level for all instances of SimpleLogger. -# Must be one of ("trace", "debug", "info", "warn", or "error"). -# If not specified, defaults to "info". -#org.slf4j.simpleLogger.defaultLogLevel=info - -# Logging detail level for a SimpleLogger instance named "xxxxx". -# Must be one of ("trace", "debug", "info", "warn", or "error"). -# If not specified, the default logging detail level is used. -#org.slf4j.simpleLogger.log.xxxxx= - -# Set to true if you want the current date and time to be included in output messages. -# Default is false, and will output the number of milliseconds elapsed since startup. -#org.slf4j.simpleLogger.showDateTime=false - -# The date and time format to be used in the output messages. -# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. -# If the format is not specified or is invalid, the default format is used. -# The default format is yyyy-MM-dd HH:mm:ss:SSS Z. -#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z - -# Set to true if you want to output the current thread name. -# Defaults to true. -#org.slf4j.simpleLogger.showThreadName=true - -# Set to true if you want the Logger instance name to be included in output messages. -# Defaults to true. -#org.slf4j.simpleLogger.showLogName=true - -# Set to true if you want the last component of the name to be included in output messages. -# Defaults to false. -#org.slf4j.simpleLogger.showShortLogName=false +# SLF4J's SimpleLogger configuration file +# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err. + +# Default logging detail level for all instances of SimpleLogger. +# Must be one of ("trace", "debug", "info", "warn", or "error"). +# If not specified, defaults to "info". +#org.slf4j.simpleLogger.defaultLogLevel=info + +# Logging detail level for a SimpleLogger instance named "xxxxx". +# Must be one of ("trace", "debug", "info", "warn", or "error"). +# If not specified, the default logging detail level is used. +#org.slf4j.simpleLogger.log.xxxxx= + +# Set to true if you want the current date and time to be included in output messages. +# Default is false, and will output the number of milliseconds elapsed since startup. +#org.slf4j.simpleLogger.showDateTime=false + +# The date and time format to be used in the output messages. +# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. +# If the format is not specified or is invalid, the default format is used. +# The default format is yyyy-MM-dd HH:mm:ss:SSS Z. +#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z + +# Set to true if you want to output the current thread name. +# Defaults to true. +#org.slf4j.simpleLogger.showThreadName=true + +# Set to true if you want the Logger instance name to be included in output messages. +# Defaults to true. +#org.slf4j.simpleLogger.showLogName=true + +# Set to true if you want the last component of the name to be included in output messages. +# Defaults to false. +#org.slf4j.simpleLogger.showShortLogName=false diff --git a/slf4j-site/LICENSE.txt b/slf4j-site/LICENSE.txt new file mode 100644 index 0000000..508a272 --- /dev/null +++ b/slf4j-site/LICENSE.txt @@ -0,0 +1,24 @@ +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-site/pom.xml b/slf4j-site/pom.xml old file mode 100644 new file mode 100755 index 183e998..53eea33 100755 --- a/slf4j-site/pom.xml +++ b/slf4j-site/pom.xml @@ -1,44 +1,68 @@ - - - - 4.0.0 - - - org.slf4j - slf4j-parent - 1.7.25 - - - slf4j-site - - jar - SLF4J Site - SLF4J Site - http://www.slf4j.org - - - - - ${project.basedir}/src/site/pages - - ../../../target/site - true - - - ${project.basedir}/src/main/resources - - - - - org.apache.maven.plugins - maven-site-plugin - ${maven-site-plugin.version} - - ${project.parent.basedir}/target/site - - - - - - \ No newline at end of file + + + + 4.0.0 + + + org.slf4j + slf4j-parent + 1.7.26 + + + slf4j-site + + jar + SLF4J Site + SLF4J Site + http://www.slf4j.org + + + + + ${project.basedir}/src/site/pages + + ../../../target/site + true + + + ${project.basedir}/src/main/resources + + + + + + org.apache.maven.plugins + maven-source-plugin + ${maven-source-plugin.version} + + + **/META-INF/* + + + + x** + + + + + package + + jar + + + + + + + org.apache.maven.plugins + maven-site-plugin + ${maven-site-plugin.version} + + ${project.parent.basedir}/target/site + + + + + + diff --git a/src/main/assembly/source.xml b/src/main/assembly/source.xml old file mode 100644 new file mode 100755 index aac5b32..0013471 100755 --- a/src/main/assembly/source.xml +++ b/src/main/assembly/source.xml @@ -1,342 +1,342 @@ - - dist - - zip - tar.gz - - - - - slf4j-api/ - slf4j-api/ - - pom.xml - - - - - slf4j-jcl/ - slf4j-jcl/ - - pom.xml - - - - - slf4j-jdk14/ - slf4j-jdk14/ - - pom.xml - - - - - slf4j-log4j12/ - slf4j-log4j12/ - - pom.xml - - - - - slf4j-nop/ - slf4j-nop/ - - pom.xml - - - - - slf4j-simple/ - slf4j-simple/ - - pom.xml - - - - - slf4j-android/ - slf4j-android/ - - pom.xml - - - - - slf4j-ext/ - slf4j-ext/ - - pom.xml - - - - - - jcl104-over-slf4j/ - jcl104-over-slf4j/ - - pom.xml - - - - - jcl-over-slf4j/ - jcl-over-slf4j/ - - pom.xml - - - - - jul-to-slf4j/ - jul-to-slf4j/ - - pom.xml - - - - - log4j-over-slf4j/ - log4j-over-slf4j/ - pom.xml - - - - osgi-over-slf4j/ - osgi-over-slf4j/ - pom.xml - - - - slf4j-site/ - slf4j-site/ - - pom.xml - - - - - slf4j-migrator/ - slf4j-migrator/ - - pom.xml - - - - - integration/ - integration/ - - pom.xml - build.xml - osgi-build.xml - lib/* - - - - - - slf4j-api/src/ - slf4j-api/src/ - - test/output/ - - - - - slf4j-jcl/src/ - slf4j-jcl/src/ - - - - slf4j-jdk14/src/ - slf4j-jdk14/src/ - - - - slf4j-log4j12/src/ - slf4j-log4j12/src/ - - - slf4j-nop/src/ - slf4j-nop/src/ - - - slf4j-simple/src/ - slf4j-simple/src/ - - - slf4j-android/src/ - slf4j-android/src/ - - - slf4j-ext/src/ - slf4j-ext/src/ - - - jcl-over-slf4j/src/ - jcl-over-slf4j/src/ - - - jul-to-slf4j/src/ - jul-to-slf4j/src/ - - - log4j-over-slf4j/src/ - log4j-over-slf4j/src/ - - - osgi-over-slf4j/src/ - osgi-over-slf4j/src/ - - - slf4j-site/src/ - slf4j-site/src/ - - - slf4j-migrator/src/ - slf4j-migrator/src/ - - - integration/src/ - integration/src/ - - - - - - slf4j-api/target/ - / - - slf4j-api-${project.version}-sources.jar - slf4j-api-${project.version}.jar - - - - - slf4j-jcl/target/ - / - - slf4j-jcl-${project.version}.jar - slf4j-jcl-${project.version}-sources.jar - - - - - slf4j-jdk14/target/ - / - - slf4j-jdk14-${project.version}-sources.jar - slf4j-jdk14-${project.version}.jar - - - - - slf4j-log4j12/target/ - / - - slf4j-log4j12-${project.version}.jar - slf4j-log4j12-${project.version}-sources.jar - - - - - slf4j-nop/target/ - / - - slf4j-nop-${project.version}.jar - slf4j-nop-${project.version}-sources.jar - - - - - slf4j-simple/target/ - / - - slf4j-simple-${project.version}-sources*.jar - slf4j-simple-${project.version}.jar - - - - - slf4j-android/target/ - / - - slf4j-android-${project.version}-sources*.jar - slf4j-android-${project.version}.jar - - - - - - slf4j-ext/target/ - / - - slf4j-ext-${project.version}-sources*.jar - slf4j-ext-${project.version}.jar - - - - - - jcl-over-slf4j/target/ - / - - jcl-over-slf4j-${project.version}-sources.jar - jcl-over-slf4j-${project.version}.jar - - - - jul-to-slf4j/target/ - / - - jul-to-slf4j-${project.version}-sources.jar - jul-to-slf4j-${project.version}.jar - - - - log4j-over-slf4j/target/ - / - - log4j-over-slf4j-${project.version}.jar - log4j-over-slf4j-${project.version}-sources.jar - - - - osgi-over-slf4j/target/ - / - - osgi-over-slf4j-${project.version}.jar - osgi-over-slf4j-${project.version}-sources.jar - - - - - slf4j-migrator/target/ - / - - slf4j-migrator-${project.version}.jar - - - - - - target/site - /site - - dist/* - - - - - - - src/ - README* - LICENSE* - pom.xml - - - - + + dist + + zip + tar.gz + + + + + slf4j-api/ + slf4j-api/ + + pom.xml + + + + + slf4j-jcl/ + slf4j-jcl/ + + pom.xml + + + + + slf4j-jdk14/ + slf4j-jdk14/ + + pom.xml + + + + + slf4j-log4j12/ + slf4j-log4j12/ + + pom.xml + + + + + slf4j-nop/ + slf4j-nop/ + + pom.xml + + + + + slf4j-simple/ + slf4j-simple/ + + pom.xml + + + + + slf4j-android/ + slf4j-android/ + + pom.xml + + + + + slf4j-ext/ + slf4j-ext/ + + pom.xml + + + + + + jcl104-over-slf4j/ + jcl104-over-slf4j/ + + pom.xml + + + + + jcl-over-slf4j/ + jcl-over-slf4j/ + + pom.xml + + + + + jul-to-slf4j/ + jul-to-slf4j/ + + pom.xml + + + + + log4j-over-slf4j/ + log4j-over-slf4j/ + pom.xml + + + + osgi-over-slf4j/ + osgi-over-slf4j/ + pom.xml + + + + slf4j-site/ + slf4j-site/ + + pom.xml + + + + + slf4j-migrator/ + slf4j-migrator/ + + pom.xml + + + + + integration/ + integration/ + + pom.xml + build.xml + osgi-build.xml + lib/* + + + + + + slf4j-api/src/ + slf4j-api/src/ + + test/output/ + + + + + slf4j-jcl/src/ + slf4j-jcl/src/ + + + + slf4j-jdk14/src/ + slf4j-jdk14/src/ + + + + slf4j-log4j12/src/ + slf4j-log4j12/src/ + + + slf4j-nop/src/ + slf4j-nop/src/ + + + slf4j-simple/src/ + slf4j-simple/src/ + + + slf4j-android/src/ + slf4j-android/src/ + + + slf4j-ext/src/ + slf4j-ext/src/ + + + jcl-over-slf4j/src/ + jcl-over-slf4j/src/ + + + jul-to-slf4j/src/ + jul-to-slf4j/src/ + + + log4j-over-slf4j/src/ + log4j-over-slf4j/src/ + + + osgi-over-slf4j/src/ + osgi-over-slf4j/src/ + + + slf4j-site/src/ + slf4j-site/src/ + + + slf4j-migrator/src/ + slf4j-migrator/src/ + + + integration/src/ + integration/src/ + + + + + + slf4j-api/target/ + / + + slf4j-api-${project.version}-sources.jar + slf4j-api-${project.version}.jar + + + + + slf4j-jcl/target/ + / + + slf4j-jcl-${project.version}.jar + slf4j-jcl-${project.version}-sources.jar + + + + + slf4j-jdk14/target/ + / + + slf4j-jdk14-${project.version}-sources.jar + slf4j-jdk14-${project.version}.jar + + + + + slf4j-log4j12/target/ + / + + slf4j-log4j12-${project.version}.jar + slf4j-log4j12-${project.version}-sources.jar + + + + + slf4j-nop/target/ + / + + slf4j-nop-${project.version}.jar + slf4j-nop-${project.version}-sources.jar + + + + + slf4j-simple/target/ + / + + slf4j-simple-${project.version}-sources*.jar + slf4j-simple-${project.version}.jar + + + + + slf4j-android/target/ + / + + slf4j-android-${project.version}-sources*.jar + slf4j-android-${project.version}.jar + + + + + + slf4j-ext/target/ + / + + slf4j-ext-${project.version}-sources*.jar + slf4j-ext-${project.version}.jar + + + + + + jcl-over-slf4j/target/ + / + + jcl-over-slf4j-${project.version}-sources.jar + jcl-over-slf4j-${project.version}.jar + + + + jul-to-slf4j/target/ + / + + jul-to-slf4j-${project.version}-sources.jar + jul-to-slf4j-${project.version}.jar + + + + log4j-over-slf4j/target/ + / + + log4j-over-slf4j-${project.version}.jar + log4j-over-slf4j-${project.version}-sources.jar + + + + osgi-over-slf4j/target/ + / + + osgi-over-slf4j-${project.version}.jar + osgi-over-slf4j-${project.version}-sources.jar + + + + + slf4j-migrator/target/ + / + + slf4j-migrator-${project.version}.jar + + + + + + target/site + /site + + dist/* + + + + + + + src/ + README* + LICENSE* + pom.xml + + + + diff --git a/src/main/javadocHeaders.xml b/src/main/javadocHeaders.xml index b011d99..a0fccd4 100644 --- a/src/main/javadocHeaders.xml +++ b/src/main/javadocHeaders.xml @@ -1,10 +1,10 @@ - - - /** - * - */ - - (\s|\t)*/\*.*$ - .*\*/(\s|\t)*$ - + + + /** + * + */ + + (\s|\t)*/\*.*$ + .*\*/(\s|\t)*$ + diff --git a/src/main/licenseHeader.txt b/src/main/licenseHeader.txt index 9c43535..cfef8df 100644 --- a/src/main/licenseHeader.txt +++ b/src/main/licenseHeader.txt @@ -1,22 +1,22 @@ -Copyright (c) 2004-2011 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +Copyright (c) 2004-2011 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/test b/test new file mode 100644 index 0000000..e69de29