diff --git a/codeStyle.xml b/codeStyle.xml index 25659d32..355c4b1d 100644 --- a/codeStyle.xml +++ b/codeStyle.xml @@ -1,295 +1,295 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + - + + + + + + + + + - - - - - - - + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/integration/src/test/java/integrator/Activator.java b/integration/src/test/java/integrator/Activator.java index 55920296..f1b5c789 100644 --- a/integration/src/test/java/integrator/Activator.java +++ b/integration/src/test/java/integrator/Activator.java @@ -37,24 +37,24 @@ import org.slf4j.LoggerFactory; */ public class Activator implements BundleActivator { - private BundleContext m_context = null; + 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(); + 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; } - return null; - } } \ No newline at end of file diff --git a/integration/src/test/java/org/slf4j/CompatibilityAssertionTest.java b/integration/src/test/java/org/slf4j/CompatibilityAssertionTest.java index 84f096fa..021ef137 100644 --- a/integration/src/test/java/org/slf4j/CompatibilityAssertionTest.java +++ b/integration/src/test/java/org/slf4j/CompatibilityAssertionTest.java @@ -32,31 +32,30 @@ 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); - } + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } + public CompatibilityAssertionTest(String name) { + super(name); + } - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } - - 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)); - } + 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 80cca58f..80c9b00e 100644 --- a/integration/src/test/java/org/slf4j/IncompatibleMultiBindingAssertionTest.java +++ b/integration/src/test/java/org/slf4j/IncompatibleMultiBindingAssertionTest.java @@ -32,44 +32,43 @@ 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); + 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) { + public IncompatibleMultiBindingAssertionTest(String name) { + super(name); } - 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."); - } + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } - void assertMsgContains(List strList, int index, String msg) { - assertTrue(((String) strList.get(index)).contains(msg)); - } + 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 631ca097..af678ccd 100644 --- a/integration/src/test/java/org/slf4j/MissingSingletonMethodAssertionTest.java +++ b/integration/src/test/java/org/slf4j/MissingSingletonMethodAssertionTest.java @@ -31,57 +31,53 @@ 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); + 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.")); + 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 138b1704..8d1cb598 100644 --- a/integration/src/test/java/org/slf4j/MultiBindingAssertionTest.java +++ b/integration/src/test/java/org/slf4j/MultiBindingAssertionTest.java @@ -32,37 +32,37 @@ 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); + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); - public MultiBindingAssertionTest(String name) { - super(name); - } + public MultiBindingAssertionTest(String name) { + super(name); + } - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } + 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 ["); - } + 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)); - } + 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 47a118ce..200b745f 100644 --- a/integration/src/test/java/org/slf4j/StringPrintStream.java +++ b/integration/src/test/java/org/slf4j/StringPrintStream.java @@ -30,28 +30,27 @@ 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 static final String LINE_SEP = System.getProperty("line.separator"); + PrintStream other; + List stringList = new ArrayList(); - public void print(String s) { - other.print(s); - stringList.add(s); - } + public StringPrintStream(PrintStream ps) { + super(ps); + other = ps; + } - public void println(String s) { - other.println(s); - stringList.add(s); - } - - public void println(Object o) { - other.println(o); - stringList.add(o.toString()); - } + 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 535e74e7..c6d90e03 100644 --- a/integration/src/test/java/org/slf4j/VersionMismatchAssertionTest.java +++ b/integration/src/test/java/org/slf4j/VersionMismatchAssertionTest.java @@ -31,37 +31,37 @@ 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); + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); - public VersionMismatchAssertionTest(String name) { - super(name); - } + public VersionMismatchAssertionTest(String name) { + super(name); + } - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } + 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.*")); + public void test() throws Exception { + Logger logger = LoggerFactory.getLogger(this.getClass()); + String msg = "hello world " + diff; + logger.info(msg); - String s1 = (String) sps.stringList.get(1); - assertTrue(s1.contains(LoggerFactory.VERSION_MISMATCH)); + String s0 = (String) sps.stringList.get(0); + assertTrue(s0.matches("SLF4J: The requested version .* by your slf4j binding is not compatible with.*")); - String s2 = (String) sps.stringList.get(2); - assertTrue(s2.contains(msg)); + 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/test_osgi/BundleTest.java b/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java index 854e9b4a..920f228d 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java +++ b/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java @@ -30,30 +30,30 @@ 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(); - } + FrameworkErrorListener fel = new FrameworkErrorListener(); + CheckingBundleListener mbl = new CheckingBundleListener(); - protected void tearDown() throws Exception { - super.tearDown(); - felixHost.stop(); - } + FelixHost felixHost = new FelixHost(fel, mbl); - 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(); + 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()); } - // 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 0940e2fb..ef4a0349 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java +++ b/integration/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java @@ -33,35 +33,34 @@ import org.osgi.framework.BundleListener; public class CheckingBundleListener implements BundleListener { - List eventList = new ArrayList(); + 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); + public void bundleChanged(BundleEvent be) { + eventList.add(be); } - } - 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; - } + 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; } - 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 980c0cb6..204b8c23 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/FelixHost.java +++ b/integration/src/test/java/org/slf4j/test_osgi/FelixHost.java @@ -45,84 +45,75 @@ import org.osgi.framework.Constants; */ public class FelixHost { - private Felix felix = null; + private Felix felix = null; - Properties otherProps = new Properties(); + Properties otherProps = new Properties(); - final FrameworkErrorListener frameworkErrorListener; - final CheckingBundleListener myBundleListener; + 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(false); - // 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_PROPERY, - AutoProcessor.AUTO_DEPLOY_DIR_VALUE); - otherProps.put(AutoProcessor.AUTO_DEPLOY_ACTION_PROPERY, - 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 FelixHost(FrameworkErrorListener frameworkErrorListener, CheckingBundleListener myBundleListener) { + this.frameworkErrorListener = frameworkErrorListener; + this.myBundleListener = myBundleListener; } - } - public void stop() throws BundleException { - felix.stop(); - } + public void doLaunch() { + // Create a case-insensitive configuration property map. + StringMap configMap = new StringMap(false); + // 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"); - public Bundle[] getInstalledBundles() { - // Use the system bundle activator to gain external - // access to the set of installed bundles. - return null;// m_activator.getBundles(); - } + 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_PROPERY, AutoProcessor.AUTO_DEPLOY_DIR_VALUE); + otherProps.put(AutoProcessor.AUTO_DEPLOY_ACTION_PROPERY, 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(); + } } \ No newline at end of file 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 8342938e..2f9458d8 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java +++ b/integration/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java @@ -32,32 +32,31 @@ 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 List errorList = new ArrayList(); - public void dumpAll() { - for(int i = 0; i < errorList.size(); i++) { - FrameworkEvent fe = (FrameworkEvent) errorList.get(i); - dump(fe); + 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/src/main/java/org/apache/commons/logging/Log.java b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/Log.java index 50f6d48c..779c4d9d 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 @@ -62,10 +62,8 @@ package org.apache.commons.logging; */ public interface Log { - // ----------------------------------------------------- Logging Properties - /** *

Is debug logging currently enabled?

* @@ -75,7 +73,6 @@ public interface Log { */ public boolean isDebugEnabled(); - /** *

Is error logging currently enabled?

* @@ -85,7 +82,6 @@ public interface Log { */ public boolean isErrorEnabled(); - /** *

Is fatal logging currently enabled?

* @@ -95,7 +91,6 @@ public interface Log { */ public boolean isFatalEnabled(); - /** *

Is info logging currently enabled?

* @@ -107,7 +102,6 @@ public interface Log { */ public boolean isInfoEnabled(); - /** *

Is trace logging currently enabled?

* @@ -119,7 +113,6 @@ public interface Log { */ public boolean isTraceEnabled(); - /** *

Is warn logging currently enabled?

* @@ -129,10 +122,8 @@ public interface Log { */ public boolean isWarnEnabled(); - // -------------------------------------------------------- Logging Methods - /** *

Log a message with trace log level.

* @@ -140,7 +131,6 @@ public interface Log { */ public void trace(Object message); - /** *

Log an error with trace log level.

* @@ -149,7 +139,6 @@ public interface Log { */ public void trace(Object message, Throwable t); - /** *

Log a message with debug log level.

* @@ -157,7 +146,6 @@ public interface Log { */ public void debug(Object message); - /** *

Log an error with debug log level.

* @@ -166,7 +154,6 @@ public interface Log { */ public void debug(Object message, Throwable t); - /** *

Log a message with info log level.

* @@ -174,7 +161,6 @@ public interface Log { */ public void info(Object message); - /** *

Log an error with info log level.

* @@ -183,7 +169,6 @@ public interface Log { */ public void info(Object message, Throwable t); - /** *

Log a message with warn log level.

* @@ -191,7 +176,6 @@ public interface Log { */ public void warn(Object message); - /** *

Log an error with warn log level.

* @@ -200,7 +184,6 @@ public interface Log { */ public void warn(Object message, Throwable t); - /** *

Log a message with error log level.

* @@ -208,7 +191,6 @@ public interface Log { */ public void error(Object message); - /** *

Log an error with error log level.

* @@ -217,7 +199,6 @@ public interface Log { */ public void error(Object message, Throwable t); - /** *

Log a message with fatal log level.

* @@ -225,7 +206,6 @@ public interface Log { */ public void fatal(Object message); - /** *

Log an error with fatal log level.

* @@ -234,5 +214,4 @@ public interface Log { */ 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 0490c5e9..668f413d 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 @@ -33,61 +33,61 @@ package org.apache.commons.logging; public class LogConfigurationException extends RuntimeException { - private static final long serialVersionUID = 8486587136871052495L; + private static final long serialVersionUID = 8486587136871052495L; - /** - * Construct a new exception with null as its detail message. - */ - public LogConfigurationException() { - super(); - } + /** + * 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 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) { + /** + * 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); + 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 - } + /** + * 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; + /** + * 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); - } + /** + * 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 dd12e850..275aab30 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 @@ -36,387 +36,373 @@ import org.apache.commons.logging.impl.SLF4JLogFactory; @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 String UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J = "http://www.slf4j.org/codes.html#unsupported_operation_in_jcl_over_slf4j"; - static LogFactory logFactory = new SLF4JLogFactory(); + 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 (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 (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 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 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"; + /** + * 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"; + /** + * 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"; - /** - *

- * 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; + /** + * 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"; - /** - * Protected constructor that is not available for public use. - */ - protected LogFactory() { - } + /** + *

+ * 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"; - // --------------------------------------------------------- Public Methods + /** + * 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; - /** - * 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); + /** + *

+ * This property is not used but preserved here for compatibility. + */ + protected static LogFactory nullClassLoaderFactory = null; - /** - * 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", ie is the same as the - * return value of the Object.toString() method, but works even when the - * specified object's class has overidden 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 constructor that is not available for public use. + */ + protected LogFactory() { } - } - // protected methods which were added in JCL 1.1. These are not used - // by SLF4JLogFactory + // --------------------------------------------------------- Public Methods - /** - * 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); - } + /** + * 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); - /** - * 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); - } + /** + * 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(); - /** - * 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); - } + /** + * 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; - /** - * 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); - } + /** + *

+ * 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", ie is the same as the + * return value of the Object.toString() method, but works even when the + * specified object's class has overidden 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); + } } \ No newline at end of file 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 3f2b221d..45e99a4a 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 @@ -30,116 +30,116 @@ import org.apache.commons.logging.Log; * @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; + private static final long serialVersionUID = 561423906191706148L; - /** Convenience constructor */ - public NoOpLog() { - } + /** Convenience constructor */ + public NoOpLog() { + } - /** Base constructor */ - public NoOpLog(String name) { - } + /** Base constructor */ + public NoOpLog(String name) { + } - /** Do nothing */ - public void trace(Object message) { - } + /** Do nothing */ + public void trace(Object message) { + } - /** Do nothing */ - public void trace(Object message, Throwable t) { - } + /** Do nothing */ + public void trace(Object message, Throwable t) { + } - /** Do nothing */ - public void debug(Object message) { - } + /** Do nothing */ + public void debug(Object message) { + } - /** Do nothing */ - public void debug(Object message, Throwable t) { - } + /** Do nothing */ + public void debug(Object message, Throwable t) { + } - /** Do nothing */ - public void info(Object message) { - } + /** Do nothing */ + public void info(Object message) { + } - /** Do nothing */ - public void info(Object message, Throwable t) { - } + /** Do nothing */ + public void info(Object message, Throwable t) { + } - /** Do nothing */ - public void warn(Object message) { - } + /** Do nothing */ + public void warn(Object message) { + } - /** Do nothing */ - public void warn(Object message, Throwable t) { - } + /** Do nothing */ + public void warn(Object message, Throwable t) { + } - /** Do nothing */ - public void error(Object message) { - } + /** Do nothing */ + public void error(Object message) { + } - /** Do nothing */ - public void error(Object message, Throwable t) { - } + /** Do nothing */ + public void error(Object message, Throwable t) { + } - /** Do nothing */ - public void fatal(Object message) { - } + /** Do nothing */ + public void fatal(Object message) { + } - /** Do nothing */ - public void fatal(Object message, Throwable t) { - } + /** Do nothing */ + public void fatal(Object message, Throwable t) { + } - /** - * Debug is never enabled. - * - * @return false - */ - public final boolean isDebugEnabled() { - return false; - } + /** + * Debug is never enabled. + * + * @return false + */ + public final boolean isDebugEnabled() { + return false; + } - /** - * Error is never enabled. - * - * @return false - */ - public final boolean isErrorEnabled() { - 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; - } + /** + * Fatal is never enabled. + * + * @return false + */ + public final boolean isFatalEnabled() { + return false; + } - /** - * Info is never enabled. - * - * @return false - */ - public final boolean isInfoEnabled() { - 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; - } + /** + * Trace is never enabled. + * + * @return false + */ + public final boolean isTraceEnabled() { + return false; + } - /** - * Warn is never enabled. - * - * @return false - */ - public final boolean isWarnEnabled() { - 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 e14e71ec..ef48be67 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 @@ -36,231 +36,219 @@ import org.slf4j.spi.LocationAwareLogger; */ public class SLF4JLocationAwareLog implements Log, Serializable { - private static final long serialVersionUID = -2379157579039314822L; + private static final long serialVersionUID = -2379157579039314822L; - // used to store this logger's name to recreate it after serialization - protected String name; + // 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; + // 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(); + private static final String FQCN = SLF4JLocationAwareLog.class.getName(); - SLF4JLocationAwareLog(LocationAwareLogger logger) { - this.logger = logger; - this.name = logger.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(); - } + /** + * 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 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 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 isWarnEnabled() { + return logger.isWarnEnabled(); + } - /** - * Directly delegates to the wrapped org.slf4j.Logger instance. - */ - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } + /** + * 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(); - } + /** + * 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 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 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 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 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 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 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 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 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 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 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 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); - } + /** + * 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); - } + /** + * 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); + } } \ No newline at end of file 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 2f654356..5ee59f7b 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 @@ -35,217 +35,217 @@ import org.slf4j.LoggerFactory; */ public class SLF4JLog implements Log, Serializable { - private static final long serialVersionUID = 680728617011167209L; + private static final long serialVersionUID = 680728617011167209L; - // used to store this logger's name to recreate it after serialization - protected String name; + // 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; + // 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(); - } + 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 isDebugEnabled() { + return logger.isDebugEnabled(); + } - /** - * Directly delegates to the wrapped org.slf4j.Logger instance. - */ - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } + /** + * 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(); - } + /** + * 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(); - } + /** + * 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(); - } + /** + * 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(); - } + /** + * 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 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 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 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 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 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 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 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 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 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 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 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); - } + /** + * 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); - } + /** + * 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); + } } \ No newline at end of file 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 bea2ba78..d715c59f 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 @@ -52,170 +52,168 @@ import java.util.concurrent.ConcurrentMap; @SuppressWarnings("rawtypes") public class SLF4JLogFactory extends LogFactory { - // ----------------------------------------------------------- Constructors + // ----------------------------------------------------------- Constructors - /** - * The {@link org.apache.commons.logging.Log}instances that have already been - * created, keyed by logger name. - */ - ConcurrentMap loggerMap; + /** + * 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); + /** + * 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); + } + + } } \ No newline at end of file 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 2b4858ce..46b5d70e 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 @@ -77,612 +77,607 @@ import org.apache.commons.logging.LogConfigurationException; */ 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 formating 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); - 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) + 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 formating 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 { - 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()); - } + prop = System.getProperty(name); + } catch (SecurityException e) { + ; // Ignore } - } catch (NoSuchMethodException e) { - // Assume we are running on JDK 1.1 - ; // ignore - } + return (prop == null) ? simpleLogProps.getProperty(name) : prop; } - if (classLoader == null) { - classLoader = SimpleLog.class.getClassLoader(); + private static String getStringProperty(String name, String dephault) { + String prop = getStringProperty(name); + return (prop == null) ? dephault : prop; } - // Return the selected class loader - return classLoader; - } + private static boolean getBooleanProperty(String name, boolean dephault) { + String prop = getStringProperty(name); + return (prop == null) ? dephault : "true".equalsIgnoreCase(prop); + } - 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); + // 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); + 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/test/java/org/apache/commons/logging/InvokeJCLTest.java b/jcl-over-slf4j/src/test/java/org/apache/commons/logging/InvokeJCLTest.java index f881e15f..ef5d23cb 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 @@ -27,59 +27,57 @@ package org.apache.commons.logging; import junit.framework.TestCase; - public class InvokeJCLTest extends TestCase { - 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()); - } - - 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"); + 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()); + } - log.error(null); - log.error("error message"); + public void testPrintAPI() { + Log log = LogFactory.getLog(InvokeJCLTest.class); + Exception e = new Exception("just testing"); - log.fatal(null); - log.fatal("fatal message"); - + log.trace(null); + log.trace("trace 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); - } + 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 d14825cf..017d6b84 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 @@ -39,52 +39,51 @@ import org.slf4j.spi.LocationAwareLogger; public class SerializationTest extends TestCase { - ObjectInputStream ois; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos; + ObjectInputStream ois; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos; - public SerializationTest(String name) { - super(name); - } + public SerializationTest(String name) { + super(name); + } - protected void setUp() throws Exception { - oos = new ObjectOutputStream(baos); - super.setUp(); - } + protected void setUp() throws Exception { + oos = new ObjectOutputStream(baos); + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); - oos.close(); - } + protected void tearDown() throws Exception { + super.tearDown(); + oos.close(); + } - public void verify() throws IOException, ClassNotFoundException { - ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray()); - ois = new ObjectInputStream(bis); + 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(); - } + Log resuscitatedLog = (Log) ois.readObject(); + // tests that the "private transient Logger logger" field is non-null + resuscitatedLog.debug(""); + resuscitatedLog.isDebugEnabled(); + } - public void testSLF4JLog() throws Exception { - JDK14LoggerFactory factory = new JDK14LoggerFactory(); - SLF4JLog log = new SLF4JLog(factory.getLogger("x")); - oos.writeObject(log); - verify(); - } + public void testSLF4JLog() throws Exception { + JDK14LoggerFactory factory = new JDK14LoggerFactory(); + SLF4JLog log = new SLF4JLog(factory.getLogger("x")); + oos.writeObject(log); + verify(); + } - public void testSmoke() throws Exception { - Log log = LogFactory.getLog("testing"); - oos.writeObject(log); - verify(); - } + public void testSmoke() throws Exception { + Log log = LogFactory.getLog("testing"); + oos.writeObject(log); + verify(); + } - public void testLocationAware() throws Exception { - JDK14LoggerFactory factory = new JDK14LoggerFactory(); - SLF4JLocationAwareLog log = new SLF4JLocationAwareLog( - (LocationAwareLogger) factory.getLogger("x")); - oos.writeObject(log); - verify(); - } + 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/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java b/jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java index 4ca5320d..72576a03 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 @@ -98,210 +98,206 @@ import org.slf4j.spi.LocationAwareLogger; */ 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"; + // 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(); + 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; + /** + * 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()); } - 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://bugzilla.slf4j.org/show_bug.cgi?id=212 - if (params != null && params.length > 0) { - message = MessageFormat.format(message, params); - } - 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; + private static java.util.logging.Logger getRootLogger() { + return LogManager.getLogManager().getLogger(""); } - 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://bugzilla.slf4j.org/show_bug.cgi?id=108 - if (message == null) { - message = ""; + /** + * 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]); + } + } } - if (slf4jLogger instanceof LocationAwareLogger) { - callLocationAwareLogger((LocationAwareLogger) slf4jLogger, record); - } else { - callPlainSLF4JLogger(slf4jLogger, record); + + /** + * 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://bugzilla.slf4j.org/show_bug.cgi?id=212 + if (params != null && params.length > 0) { + message = MessageFormat.format(message, params); + } + 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://bugzilla.slf4j.org/show_bug.cgi?id=108 + if (message == null) { + message = ""; + } + if (slf4jLogger instanceof LocationAwareLogger) { + callLocationAwareLogger((LocationAwareLogger) slf4jLogger, record); + } else { + callPlainSLF4JLogger(slf4jLogger, record); + } } - } } 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 cbba1a85..e5fb5f3b 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 @@ -32,22 +32,22 @@ 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 List list = new ArrayList(); + + public boolean extractLocationInfo = false; + + protected void append(LoggingEvent event) { + list.add(event); + if (extractLocationInfo) { + event.getLocationInformation(); + } } - } - public void close() { - } + public void close() { + } - public boolean requiresLayout() { - return false; - } + 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 689c8778..17e2329e 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 @@ -35,81 +35,78 @@ import org.slf4j.LoggerFactory; public class SLF4JBridgeHandlerPerfTest extends TestCase { - static String LOGGER_NAME = "yay"; - static int RUN_LENGTH = 100*1000; + static String LOGGER_NAME = "yay"; + static int RUN_LENGTH = 100 * 1000; + // set to false to test enabled logging performance + boolean disabledLogger = true; - // 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(""); + 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; + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(LOGGER_NAME); + org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(LOGGER_NAME); - public SLF4JBridgeHandlerPerfTest(String arg0) { - super(arg0); - } + Handler[] existingHandlers; - protected void setUp() throws Exception { - super.setUp(); - 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]); + public SLF4JBridgeHandlerPerfTest(String arg0) { + super(arg0); } - log4jRoot = org.apache.log4j.Logger.getRootLogger(); - log4jRoot.addAppender(fileAppender); - } - protected void tearDown() throws Exception { - super.tearDown(); - SLF4JBridgeHandler.uninstall(); - fileAppender.close(); - log4jRoot.getLoggerRepository().resetConfiguration(); - for (int i = 0; i < existingHandlers.length; i++) { - julRootLogger.addHandler(existingHandlers[i]); - } - } + protected void setUp() throws Exception { + super.setUp(); + fileAppender = new FileAppender(new PatternLayout("%r [%t] %p %c %x - %m%n"), "target/test-output/toto.log"); - double julLoggerLoop() { - long start = System.nanoTime(); - for (int i = 0; i < RUN_LENGTH; i++) { - julLogger.info("jul"); + existingHandlers = julRootLogger.getHandlers(); + for (int i = 0; i < existingHandlers.length; i++) { + julRootLogger.removeHandler(existingHandlers[i]); + } + log4jRoot = org.apache.log4j.Logger.getRootLogger(); + log4jRoot.addAppender(fileAppender); } - 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"); + protected void tearDown() throws Exception { + super.tearDown(); + SLF4JBridgeHandler.uninstall(); + fileAppender.close(); + log4jRoot.getLoggerRepository().resetConfiguration(); + for (int i = 0; i < existingHandlers.length; i++) { + julRootLogger.addHandler(existingHandlers[i]); + } } - long end = System.nanoTime(); - return (end - start) * 1.0 / RUN_LENGTH; - } - - public void testPerf() { - SLF4JBridgeHandler.install(); - - if(disabledLogger) { - log4jRoot.setLevel(org.apache.log4j.Level.ERROR); + + 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; + } + + 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)); } - 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 index 4874bdfd..a413cdbe 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 @@ -35,152 +35,147 @@ import org.apache.log4j.spi.LoggingEvent; public class SLF4JBridgeHandlerTest extends TestCase { - static String LOGGER_NAME = "yay"; + 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"); + ListAppender listAppender = new ListAppender(); + org.apache.log4j.Logger log4jRoot; + java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger("yay"); - public SLF4JBridgeHandlerTest(String arg0) { - super(arg0); - } + public SLF4JBridgeHandlerTest(String arg0) { + super(arg0); + } - protected void setUp() throws Exception { - super.setUp(); - listAppender.extractLocationInfo = true; - log4jRoot = org.apache.log4j.Logger.getRootLogger(); - log4jRoot.addAppender(listAppender); - log4jRoot.setLevel(org.apache.log4j.Level.TRACE); - } + protected void setUp() throws Exception { + super.setUp(); + listAppender.extractLocationInfo = true; + log4jRoot = org.apache.log4j.Logger.getRootLogger(); + log4jRoot.addAppender(listAppender); + log4jRoot.setLevel(org.apache.log4j.Level.TRACE); + } - protected void tearDown() throws Exception { - super.tearDown(); - SLF4JBridgeHandler.uninstall(); - log4jRoot.getLoggerRepository().resetConfiguration(); - } + protected void tearDown() throws Exception { + super.tearDown(); + SLF4JBridgeHandler.uninstall(); + log4jRoot.getLoggerRepository().resetConfiguration(); + } - 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()); + 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()); - } + // 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()); + } - public void testLevels() { - SLF4JBridgeHandler.install(); - String msg = "msg"; - julLogger.setLevel(Level.ALL); + 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); + 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); - } + 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); + } - public void testLogWithResourceBundle() { - SLF4JBridgeHandler.install(); + 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; + 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); + 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()); - } + julResourceBundleLogger.info(msg); + assertEquals(1, listAppender.list.size()); + LoggingEvent le = (LoggingEvent) listAppender.list.get(0); + assertEquals(LOGGER_NAME, le.getLoggerName()); + assertEquals(expectedMsg, le.getMessage()); + } - public void testLogWithResourceBundleWithParameters() { - SLF4JBridgeHandler.install(); + public void testLogWithResourceBundleWithParameters() { + SLF4JBridgeHandler.install(); - String resourceBundleName = "org.slf4j.bridge.testLogStrings"; - ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); + String resourceBundleName = "org.slf4j.bridge.testLogStrings"; + ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); - java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger - .getLogger("foo", 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 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 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 + 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 + julLogger.log(Level.INFO, resourceKey3, params3); // 4th log - assertEquals(4, listAppender.list.size()); + assertEquals(4, listAppender.list.size()); - LoggingEvent le = null; + LoggingEvent le = null; - le = (LoggingEvent) listAppender.list.get(0); - assertEquals("foo", le.getLoggerName()); - assertEquals(expectedMsg1, le.getMessage()); + 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(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(2); + assertEquals("foo", le.getLoggerName()); + assertEquals(expectedMsg3, le.getMessage()); - le = (LoggingEvent) listAppender.list.get(3); - assertEquals("yay", le.getLoggerName()); - assertEquals(expectedMsg3, le.getMessage()); - } + le = (LoggingEvent) listAppender.list.get(3); + assertEquals("yay", le.getLoggerName()); + assertEquals(expectedMsg3, le.getMessage()); + } - public void testLogWithPlaceholderNoParameters() { - SLF4JBridgeHandler.install(); - String msg = "msg {non-number-string}"; - julLogger.logp(Level.INFO, "SLF4JBridgeHandlerTest", "testLogWithPlaceholderNoParameters", msg, new Object[0]); + 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()); - } + assertEquals(1, listAppender.list.size()); + LoggingEvent le = (LoggingEvent) listAppender.list.get(0); + assertEquals(LOGGER_NAME, le.getLoggerName()); + assertEquals(msg, le.getMessage()); + } - void assertLevel(int index, org.apache.log4j.Level expectedLevel) { - LoggingEvent le = (LoggingEvent) listAppender.list.get(index); - assertEquals(expectedLevel, le.getLevel()); - } + void assertLevel(int index, org.apache.log4j.Level expectedLevel) { + LoggingEvent le = (LoggingEvent) listAppender.list.get(index); + assertEquals(expectedLevel, le.getLevel()); + } } 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 76233096..3df673fb 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 @@ -29,106 +29,103 @@ import org.apache.log4j.spi.LoggingEvent; */ public interface Appender { - /** - * Add a filter to the end of the filter list. - * - * @since 0.9.0 - */ - void addFilter(Filter newFilter); + /** + * 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(); + /** + * 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(); + /** + * 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(); + /** + * 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); + /** + * 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(); - /** - * 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 ErrorHandler} for this appender. - * - * @since 0.9.0 - */ - public void setErrorHandler(ErrorHandler errorHandler); + /** + * Set the {@link Layout} for this appender. + * + * @since 0.8.1 + */ + public void setLayout(Layout layout); - /** - * Returns the {@link ErrorHandler} for this appender. - * - * @since 1.1 - */ - public ErrorHandler getErrorHandler(); + /** + * Returns this appenders layout. + * + * @since 1.1 + */ + public Layout getLayout(); - /** - * Set the {@link Layout} for this appender. - * - * @since 0.8.1 - */ - public void setLayout(Layout layout); + /** + * 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); - /** - * 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(); + /** + * 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 dd94dbd8..447c3b56 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 @@ -19,15 +19,15 @@ import org.apache.log4j.spi.OptionHandler; public class AppenderSkeleton implements OptionHandler { - public void setLayout(Layout layout) { - } + public void setLayout(Layout layout) { + } - public void setName(String name) { - } + public void setName(String name) { + } - public void activateOptions() { - } + public void activateOptions() { + } - public void setThreshold(Priority threshold) { - } + 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 fe9dd6ba..4209ca54 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 @@ -20,12 +20,12 @@ package org.apache.log4j; * A minimal (nop) implementation of BasicConfigurator. */ public class BasicConfigurator { - public static void configure() { - } + public static void configure() { + } - public static void configure(Appender appender) { - } + public static void configure(Appender appender) { + } - public static void resetConfiguration() { - } + 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 c64b7a3b..8ed11ff8 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 @@ -43,314 +43,304 @@ import java.util.Enumeration; @SuppressWarnings("rawtypes") public class Category { - private static final String CATEGORY_FQCN = Category.class.getName(); + private static final String CATEGORY_FQCN = Category.class.getName(); - private String name; + private String name; - protected org.slf4j.Logger slf4jLogger; - private org.slf4j.spi.LocationAwareLogger locationAwareLogger; + protected org.slf4j.Logger slf4jLogger; + private org.slf4j.spi.LocationAwareLogger locationAwareLogger; - private static Marker FATAL_MARKER = MarkerFactory.getMarker("FATAL"); + 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; + 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 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; + public static Category getInstance(Class clazz) { + return Log4jLoggerFactory.getLogger(clazz.getName()); } - if (slf4jLogger.isDebugEnabled()) { - return Level.DEBUG; + + public static Category getInstance(String name) { + return Log4jLoggerFactory.getLogger(name); } - if (slf4jLogger.isInfoEnabled()) { - return Level.INFO; + + public final Category getParent() { + return null; } - if (slf4jLogger.isWarnEnabled()) { - return Level.WARN; + + /** + * Returns the obvious. + * + * @return + */ + public String getName() { + return name; } - 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 tob {@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(); + public Enumeration getAllAppenders() { + return NullEnumeration.getInstance(); } - 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; - } + /** + * 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; } - } - /** - * 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://bugzilla.slf4j.org/show_bug.cgi?id=168 - 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); + /** + * 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; } - } - protected final String convertToString(Object message) { - if (message == null) { - return (String) message; - } else { - return message.toString(); + /** + * @deprecated Please use {@link #getLevel} instead. + */ + final public Level getPriority() { + return null; } - } - public void setAdditivity(boolean additive) { - // nothing to do - } - - public void addAppender(Appender newAppender) { - // nothing to do - } - - public void setLevel(Level level) { - // nothing to do - } + /** + * 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 tob {@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://bugzilla.slf4j.org/show_bug.cgi?id=168 + 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 + } } 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 index dd61f07a..27e1f491 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 @@ -17,15 +17,15 @@ package org.apache.log4j; public class FileAppender extends WriterAppender { - public FileAppender() { - } + public FileAppender() { + } - public FileAppender(Layout layout, String filename) { - } + public FileAppender(Layout layout, String filename) { + } - public FileAppender(Layout layout, String filename, boolean append) { - } + public FileAppender(Layout layout, String filename, boolean append) { + } - public FileAppender(Layout layout, String filename, boolean append, boolean bufferedIO, int bufferSize) { - } + public FileAppender(Layout layout, String filename, boolean append, boolean bufferedIO, int bufferSize) { + } } 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 49cd038c..62ef578e 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 @@ -18,6 +18,7 @@ // Nicholas Wolff package org.apache.log4j; + import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -38,139 +39,145 @@ import java.io.Serializable; */ public class Level extends Priority implements Serializable { - /** - * TRACE level integer value. - * @since 1.2.12 + /** + * 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. */ - public static final int TRACE_INT = 5000; + final static public Level WARN = new Level(WARN_INT, "WARN", 4); - // match jboss' xlevel - public static final int X_TRACE_INT = DEBUG_INT - 100; + /** + 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 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 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 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 TRACE Level designates finer-grained + * informational events than the DEBUGERROR 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 ALL has the lowest possible rank and is intended to + turn on all logging. */ + final static public Level ALL = new Level(ALL_INT, "ALL", 7); - /** - The WARN level designates potentially harmful situations. - */ - final static public Level WARN = new Level(WARN_INT, "WARN", 4); + /** + * Serialization version id. + */ + static final long serialVersionUID = 3491141966387921974L; - /** - 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; + /** + 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 the value of - defaultLevel. - */ - public - static - Level toLevel(String sArg, Level defaultLevel) { - if(sArg == null) - return defaultLevel; - - String s = sArg.toUpperCase(); + /** + 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); + } - 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; - } + /** + 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. @@ -179,13 +186,13 @@ public class Level extends Priority implements Serializable { * @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 = ""; - } + s.defaultReadObject(); + level = s.readInt(); + syslogEquivalent = s.readInt(); + levelStr = s.readUTF(); + if (levelStr == null) { + levelStr = ""; + } } /** @@ -208,13 +215,13 @@ public class Level extends Priority implements Serializable { */ private Object readResolve() throws ObjectStreamException { // - // if the deserizalized object is exactly an instance of Level + // if the deserizalized object is exactly an instance of Level // if (getClass() == Level.class) { return toLevel(level); } // - // extension of Level can't substitute stock item + // 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 8f591a56..738b6a6c 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 @@ -33,46 +33,45 @@ import java.util.concurrent.ConcurrentMap; */ class Log4jLoggerFactory { - // String, Logger - private static ConcurrentMap log4jLoggers = new ConcurrentHashMap(); + // String, Logger + private static ConcurrentMap log4jLoggers = new ConcurrentHashMap(); - private static final String LOG4J_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#log4jDelegationLoop"; + private static final String LOG4J_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#log4jDelegationLoop"; - // check for delegation loops - static { - try { - Class.forName("org.slf4j.impl.Log4jLoggerFactory"); - String part1 = "Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError. "; - String part2 = "See also " + LOG4J_DELEGATION_LOOP_URL - + " for more details."; + // check for delegation loops + static { + try { + Class.forName("org.slf4j.impl.Log4jLoggerFactory"); + String part1 = "Detected both log4j-over-slf4j.jar AND 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 + Util.report(part1); + Util.report(part2); + throw new IllegalStateException(part1 + part2); + } catch (ClassNotFoundException e) { + // this is the good case + } } - } - 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) { + 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; + 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 73c44931..51c9c85d 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 @@ -37,51 +37,51 @@ import java.util.Vector; @SuppressWarnings("rawtypes") public class LogManager { - public static Logger getRootLogger() { - return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); - } + 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 String name) { + return Log4jLoggerFactory.getLogger(name); + } - public static Logger getLogger(final Class clazz) { - return Log4jLoggerFactory.getLogger(clazz.getName()); - } + public static Logger getLogger(final Class clazz) { + return Log4jLoggerFactory.getLogger(clazz.getName()); + } - /** - * Returns a logger instance created by loggerFactory. This method was requested in - * bug #234. 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); - } + /** + * Returns a logger instance created by loggerFactory. This method was requested in + * bug #234. 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(); - } + /** + * 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 shutdown() { + } - /** - * Implemented as NOP. - */ - public static void resetConfiguration() { - } + /** + * 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 8e1bb2f2..12ec1761 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 @@ -30,56 +30,55 @@ import org.slf4j.spi.LocationAwareLogger; * */ @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); - } + private static final String LOGGER_FQCN = Logger.class.getName(); - public static Logger getLogger(String name, LoggerFactory loggerFactory) { - return Log4jLoggerFactory.getLogger(name,loggerFactory); - } + protected Logger(String name) { + super(name); + } - 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); - } + public static Logger getLogger(String name) { + return Log4jLoggerFactory.getLogger(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); - } + public static Logger getLogger(String name, LoggerFactory loggerFactory) { + return Log4jLoggerFactory.getLogger(name, loggerFactory); + } - /** - * 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); - } + 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 edc5524b..c4a8eff4 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 @@ -21,45 +21,44 @@ 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 void put(String key, String value) { + org.slf4j.MDC.put(key, value); } - } - - 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); + public static void put(String key, Object value) { + if (value != null) { + put(key, value.toString()); + } else { + put(key, null); + } } - else { - return new Hashtable(); + + 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 8df9f7a3..b8e89295 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 @@ -28,75 +28,75 @@ import java.util.Stack; public class NDC { - public final static String PREFIX = "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); + 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; - } + @SuppressWarnings("rawtypes") + public static Stack cloneStack() { + return null; } - return i; - } - public static String pop() { - int next = getDepth(); - if (next == 0) { - return ""; + @SuppressWarnings("rawtypes") + public static void inherit(Stack stack) { } - 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 ""; + static public String get() { + return null; } - 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); - } + public static int getDepth() { + int i = 0; + while (true) { + String val = MDC.get(PREFIX + i); + if (val != null) { + i++; + } else { + break; + } + } + return i; + } - static public void remove() { - clear(); - } + 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; + } - static public void setMaxDepth(int maxDepth) { - } + 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 ca2268d5..a38df63b 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 @@ -24,12 +24,12 @@ package org.apache.log4j; * */ public class PatternLayout extends Layout { - public PatternLayout() { - super(); - } + public PatternLayout() { + super(); + } - public PatternLayout(String pattern) { - 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 7d629e63..bb4f8d4a 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 @@ -27,168 +27,144 @@ package org.apache.log4j; @author Ceki Gülcü */ public class Priority { - transient int level; - transient String levelStr; - transient int syslogEquivalent; + 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; + 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#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#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#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#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); + /** + * @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; + /** + * Default constructor for deserialization. + */ + protected Priority() { + level = DEBUG_INT; + levelStr = "DEBUG"; + syslogEquivalent = 7; } - } - /** - Return the syslog equivalent of this priority as an integer. - */ - public - final - int getSyslogEquivalent() { - return syslogEquivalent; - } + /** + 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; + } + } - - /** - 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. + /** + Return the syslog equivalent of this priority as an integer. + */ + public final int getSyslogEquivalent() { + return syslogEquivalent; + } - */ - public - boolean isGreaterOrEqual(Priority r) { - return level >= r.level; - } + /** + 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. - /** - Return all possible priorities as an array of Level objects in - descending order. + */ + public boolean isGreaterOrEqual(Priority r) { + return level >= r.level; + } - @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}; - } + /** + 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 string representation of this priority. + */ + final public String toString() { + return levelStr; + } - /** - Returns the integer representation of this level. - */ - public - final - int toInt() { - return level; - } + /** + 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(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)} 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(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); - } + /** + * @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); + } } \ No newline at end of file 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 b1ec759b..baf4c136 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 @@ -26,27 +26,27 @@ 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(Properties properties) { + } - public static void configure(String configFilename) { - } + public static void configure(String configFilename) { + } - public static void configure(java.net.URL configURL) { - } + public static void configure(java.net.URL configURL) { + } - public static void configureAndWatch(String configFilename) { - } + public static void configureAndWatch(String configFilename) { + } - public static void configureAndWatch(String configFilename, long delay) { - } + public static void configureAndWatch(String configFilename, long delay) { + } - public void doConfigure(Properties properties, LoggerRepository hierarchy) { - } + public void doConfigure(Properties properties, LoggerRepository hierarchy) { + } - public void doConfigure(String configFileName, LoggerRepository hierarchy) { - } + public void doConfigure(String configFileName, LoggerRepository hierarchy) { + } - public void doConfigure(URL configURL, 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 a971e061..b3295974 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 @@ -26,25 +26,24 @@ import java.io.IOException; * */ public class RollingFileAppender { - public RollingFileAppender() { - super(); - } + public RollingFileAppender() { + super(); + } - public RollingFileAppender(Layout layout, String filename) throws IOException { - super(); - } + public RollingFileAppender(Layout layout, String filename) throws IOException { + super(); + } - public RollingFileAppender(Layout layout, String filename, boolean append) - throws IOException { - super(); - } + public RollingFileAppender(Layout layout, String filename, boolean append) throws IOException { + super(); + } - public void setMaxBackupIndex(int maxBackups) { - // nothing to do - } + public void setMaxBackupIndex(int maxBackups) { + // nothing to do + } - public void setMaximumFileSize(long maxFileSize) { - // nothing to do - } + public void setMaximumFileSize(long maxFileSize) { + // nothing to do + } } 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 68ca1ca0..01157ab7 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 @@ -34,146 +34,128 @@ package org.apache.log4j.helpers; */ public class LogLog { - /** - Defining this value makes log4j print log4j-internal debug - statements to System.out. + /** + Defining this value makes log4j print log4j-internal debug + statements to System.out. -

The value of this string is log4j.debug. +

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"; +

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. - /** - Defining this value makes log4j components print log4j-internal - debug statements to System.out. +

The value of this string is log4j.configDebug. -

The value of this string is log4j.configDebug. +

Note that the search for all option names is case sensitive. -

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"; - @deprecated Use {@link #DEBUG_KEY} instead. - */ - public static final String CONFIG_DEBUG_KEY="log4j.configDebug"; + protected static boolean debugEnabled = false; - protected static boolean debugEnabled = false; + /** + In quietMode not even errors generate any output. + */ + private static boolean quietMode = 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 "; - 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); + static { } - } - /** - 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); + /** + Allows to enable/disable log4j internal logging. + */ + static public void setInternalDebugging(boolean enabled) { + debugEnabled = enabled; } - } - - /** - 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(); + /** + 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); + } } - } - /** - 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(); + /** + 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 37a2f2fd..9c92396f 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 @@ -28,20 +28,20 @@ import java.util.NoSuchElementException; */ @SuppressWarnings("rawtypes") public class NullEnumeration implements Enumeration { - private static final NullEnumeration instance = new NullEnumeration(); + private static final NullEnumeration instance = new NullEnumeration(); - private NullEnumeration() { - } + private NullEnumeration() { + } - public static NullEnumeration getInstance() { - return instance; - } + public static NullEnumeration getInstance() { + return instance; + } - public boolean hasMoreElements() { - return false; - } + public boolean hasMoreElements() { + return false; + } - public Object nextElement() { - throw new NoSuchElementException(); - } + public Object nextElement() { + throw new NoSuchElementException(); + } } \ No newline at end of file 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 49beafc5..abf75609 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 @@ -16,7 +16,6 @@ package org.apache.log4j.spi; - import org.apache.log4j.spi.LoggerRepository; import java.net.URL; @@ -28,28 +27,26 @@ import java.net.URL; */ 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 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"; + /** + 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. - /** - 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); + @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/HierarchyEventListener.java b/log4j-over-slf4j/src/main/java/org/apache/log4j/spi/HierarchyEventListener.java index 15496658..a774949e 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 @@ -28,16 +28,11 @@ import org.apache.log4j.*; */ public interface HierarchyEventListener { + // public + // void categoryCreationEvent(Category cat); - //public - //void categoryCreationEvent(Category cat); - - - public - void addAppenderEvent(Category cat, Appender appender); - - public - void removeAppenderEvent(Category cat, Appender appender); + 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 55975bfc..c3e756d7 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 @@ -31,7 +31,6 @@ import org.apache.log4j.Logger; */ public interface LoggerFactory { - public - Logger makeNewLoggerInstance(String name); + 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 243af1fa..4decdb78 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 @@ -75,11 +75,9 @@ public interface LoggerRepository { public Logger getRootLogger(); - public - abstract Logger exists(String name); + public abstract Logger exists(String name); - public - abstract void shutdown(); + public abstract void shutdown(); @SuppressWarnings("rawtypes") public Enumeration getCurrentLoggers(); @@ -90,11 +88,8 @@ public interface LoggerRepository { @SuppressWarnings("rawtypes") public Enumeration getCurrentCategories(); + public abstract void fireAddAppenderEvent(Category logger, Appender appender); - public - abstract void fireAddAppenderEvent(Category logger, Appender appender); - - public - abstract void resetConfiguration(); + public abstract void resetConfiguration(); } 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 291b94ef..c1e0150b 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 @@ -17,6 +17,6 @@ package org.apache.log4j.spi; public interface OptionHandler { - void activateOptions(); + 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 ffb98e00..c133716d 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 @@ -25,43 +25,42 @@ 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(Element element) { + } - public static void configure(String filename) throws FactoryConfigurationError { - } + public static void configure(String filename) throws FactoryConfigurationError { + } - static public void configure(URL url) throws FactoryConfigurationError { - } + static public void configure(URL url) throws FactoryConfigurationError { + } - static public void configureAndWatch(String configFilename) { - } + static public void configureAndWatch(String configFilename) { + } - public static void configureAndWatch(String configFilename, long delay) { - } + public static void configureAndWatch(String configFilename, long delay) { + } - public void doConfigure(Element element, LoggerRepository repository) { - } + public void doConfigure(Element element, LoggerRepository repository) { + } - public void doConfigure(InputStream inputStream, LoggerRepository repository) throws FactoryConfigurationError { - } + public void doConfigure(InputStream inputStream, LoggerRepository repository) throws FactoryConfigurationError { + } - public void doConfigure(Reader reader, LoggerRepository repository) throws FactoryConfigurationError { - } + public void doConfigure(Reader reader, LoggerRepository repository) throws FactoryConfigurationError { + } - public void doConfigure(String filename, LoggerRepository repository) { - } + public void doConfigure(String filename, LoggerRepository repository) { + } - public void doConfigure(URL url, LoggerRepository repository) { - } + public void doConfigure(URL url, LoggerRepository repository) { + } - public static String subst(String value, Properties props) { - return value; - } + public static String subst(String value, Properties props) { + return value; + } } 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 e2e54385..74c2cd3b 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 @@ -31,31 +31,30 @@ import junit.framework.TestCase; */ public class NDCTest extends TestCase { + public void setUp() { + assertEquals(0, NDC.getDepth()); + } - public void setUp() { - assertEquals(0, NDC.getDepth()); - } + public void tearDown() { + NDC.clear(); + } - public void tearDown() { - NDC.clear(); - } + public void testSmoke() { + NDC.push("a"); + String back = NDC.pop(); + assertEquals("a", back); + } - public void testSmoke() { - NDC.push("a"); - String back = NDC.pop(); - assertEquals("a", back); - } + public void testPop() { + NDC.push("peek"); + String back = NDC.peek(); + assertEquals("peek", back); + } - public void testPop() { - NDC.push("peek"); - String back = NDC.peek(); - assertEquals("peek", back); - } - - public void testClear() { - NDC.push("clear"); - NDC.clear(); - assertEquals(0, NDC.getDepth()); - } + 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 c321c21e..50edf2d3 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 @@ -30,22 +30,22 @@ 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"); + 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); - } + 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 6b55c905..c97d5666 100644 --- a/log4j-over-slf4j/src/test/java/org/dummy/Bug131.java +++ b/log4j-over-slf4j/src/test/java/org/dummy/Bug131.java @@ -34,35 +34,35 @@ import org.apache.log4j.Logger; public class Bug131 extends TestCase { - public void testBug131() { + 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"); + 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; + 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()); + 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 9ce42cc5..f6cfe63f 100644 --- a/log4j-over-slf4j/src/test/java/org/dummy/Bug139.java +++ b/log4j-over-slf4j/src/test/java/org/dummy/Bug139.java @@ -34,24 +34,24 @@ import org.apache.log4j.Logger; public class Bug139 extends TestCase { - 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"); + 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; + 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()); + log4jLogger.log(org.apache.log4j.Level.DEBUG, "hello" + (++n)); + log4jCategory.log(org.apache.log4j.Level.DEBUG, "world" + (++n)); - for (int i = 0; i < n; i++) { - LogRecord logRecord = (LogRecord) listHandler.list.get(i); - assertEquals("test", logRecord.getSourceMethodName()); + 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 17fe85ca..c29ebfa1 100644 --- a/log4j-over-slf4j/src/test/java/org/dummy/ListHandler.java +++ b/log4j-over-slf4j/src/test/java/org/dummy/ListHandler.java @@ -31,19 +31,19 @@ import java.util.logging.LogRecord; public class ListHandler extends Handler { - List list = new ArrayList(); - - public void close() throws SecurityException { + List list = new ArrayList(); - } + public void close() throws SecurityException { - public void flush() { + } - } + public void flush() { - public void publish(LogRecord logRecord) { - logRecord.getSourceClassName(); - list.add(logRecord); - } + } + + public void publish(LogRecord logRecord) { + logRecord.getSourceClassName(); + list.add(logRecord); + } } 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 06d19f9a..8ac9039b 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 @@ -49,7 +49,7 @@ import org.osgi.service.log.LogService; public class Activator implements BundleActivator { /** * - * Implements BundleActivator.start() to register a + * Implements BundleActivator.start() to register a * LogServiceFactory. * * @param bundleContext the framework context for the bundle 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 3de2e1ce..c626a2c4 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 @@ -43,18 +43,23 @@ import org.osgi.framework.ServiceRegistration; * @version $Rev$, $Date$ */ public class LogServiceFactory implements ServiceFactory { - /* (non-Javadoc) - * @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle, org.osgi.framework.ServiceRegistration) + /* + * (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) + /* + * (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. + // 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 30d52574..c020c4e7 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 @@ -48,162 +48,159 @@ import org.slf4j.LoggerFactory; */ public class LogServiceImpl implements LogService { - private static final String UNKNOWN = "[Unknown]"; + private static final String UNKNOWN = "[Unknown]"; - private final Logger delegate; + private final Logger delegate; + /** + * Creates a new instance of LogServiceImpl. + * + * @param bundle The bundle to create a new LogService for. + */ + public LogServiceImpl(Bundle bundle) { - /** - * 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); + } - 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) { - /* - * (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; + } + } - 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) { - /* - * (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; + } + } - 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) { - /* - * (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; + } + } - 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) { - /** - * 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); - StringBuilder output = new StringBuilder(); - if (sr != null) { - output.append('[').append(sr.toString()).append(']'); - } else { - output.append(UNKNOWN); - } - output.append(message); + return output.toString(); + } - 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) { - /* - * (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; - } - } + 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/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java b/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java index 347cddf3..8ed82f3c 100644 --- a/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java @@ -36,22 +36,22 @@ package org.slf4j; * @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); + + /** + * 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 c908e715..75702215 100644 --- a/slf4j-api/src/main/java/org/slf4j/IMarkerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/IMarkerFactory.java @@ -24,7 +24,6 @@ */ package org.slf4j; - /** * Implementations of this interface are used to manufacture {@link Marker} * instances. @@ -37,47 +36,46 @@ package org.slf4j; */ 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); + /** + * 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 e39727ce..93dd9945 100644 --- a/slf4j-api/src/main/java/org/slf4j/Logger.java +++ b/slf4j-api/src/main/java/org/slf4j/Logger.java @@ -63,686 +63,659 @@ package org.slf4j; */ 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); + /** + * 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 index 81450333..2f74c18b 100755 --- a/slf4j-api/src/main/java/org/slf4j/LoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/LoggerFactory.java @@ -61,288 +61,287 @@ import org.slf4j.impl.StaticLoggerBinder; */ public final class LoggerFactory { - static final String CODES_PREFIX = "http://www.slf4j.org/codes.html"; + 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 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 UNSUCCESSFUL_INIT_URL = CODES_PREFIX + "#unsuccessfulInit"; - static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory could not be successfully initialized. See also " - + UNSUCCESSFUL_INIT_URL; + static final String UNSUCCESSFUL_INIT_URL = CODES_PREFIX + "#unsuccessfulInit"; + static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory could not be successfully initialized. 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 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 int INITIALIZATION_STATE = UNINITIALIZED; - static SubstituteLoggerFactory TEMP_FACTORY = new SubstituteLoggerFactory(); - static NOPLoggerFactory NOP_FALLBACK_FACTORY = new NOPLoggerFactory(); + static int INITIALIZATION_STATE = UNINITIALIZED; + static SubstituteLoggerFactory TEMP_FACTORY = new SubstituteLoggerFactory(); + static NOPLoggerFactory NOP_FALLBACK_FACTORY = new NOPLoggerFactory(); - // Support for detecting mismatched logger names. - static final String DETECT_LOGGER_NAME_MISMATCH_PROPERTY = "slf4j.detectLoggerNameMismatch"; - static boolean DETECT_LOGGER_NAME_MISMATCH = Boolean.getBoolean(DETECT_LOGGER_NAME_MISMATCH_PROPERTY); + // Support for detecting mismatched logger names. + static final String DETECT_LOGGER_NAME_MISMATCH_PROPERTY = "slf4j.detectLoggerNameMismatch"; + static boolean DETECT_LOGGER_NAME_MISMATCH = Boolean.getBoolean(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" }; + /** + * 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; - TEMP_FACTORY = new SubstituteLoggerFactory(); - } - - 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.indexOf("org/slf4j/impl/StaticLoggerBinder") != -1) - return true; - if (msg.indexOf("org.slf4j.impl.StaticLoggerBinder") != -1) - return true; - return false; - } - - private final static void bind() { - try { - Set staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet(); - reportMultipleBindingAmbiguity(staticLoggerBinderPathSet); - // the next line does the binding - StaticLoggerBinder.getSingleton(); - INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION; - reportActualBinding(staticLoggerBinderPathSet); - fixSubstitutedLoggers(); - } 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.indexOf("org.slf4j.impl.StaticLoggerBinder.getSingleton()") != -1) { - 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); - } - } - - static void failedBinding(Throwable t) { - INITIALIZATION_STATE = FAILED_INITIALIZATION; - Util.report("Failed to instantiate SLF4J LoggerFactory", t); - } - - private final static void fixSubstitutedLoggers() { - List loggers = TEMP_FACTORY.getLoggers(); - - if (loggers.isEmpty()) { - return; + // private constructor prevents instantiation + private LoggerFactory() { } - 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); - for (SubstituteLogger subLogger : loggers) { - subLogger.setDelegate(getLogger(subLogger.getName())); - Util.report(subLogger.getName()); + /** + * 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; + TEMP_FACTORY = new SubstituteLoggerFactory(); } - TEMP_FACTORY.clear(); - } - - private final static void versionSanityCheck() { - try { - String requested = StaticLoggerBinder.REQUESTED_API_VERSION; - - boolean match = false; - for (int i = 0; i < API_COMPATIBILITY_LIST.length; i++) { - if (requested.startsWith(API_COMPATIBILITY_LIST[i])) { - match = true; + private final static void performInitialization() { + bind(); + if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) { + versionSanityCheck(); } - } - 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"; - - private 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 = (URL) paths.nextElement(); - staticLoggerBinderPathSet.add(path); - } - } catch (IOException ioe) { - Util.report("Error getting resources from path", ioe); + private static boolean messageContainsOrgSlf4jImplStaticLoggerBinder(String msg) { + if (msg == null) + return false; + if (msg.indexOf("org/slf4j/impl/StaticLoggerBinder") != -1) + return true; + if (msg.indexOf("org.slf4j.impl.StaticLoggerBinder") != -1) + return true; + return false; } - return staticLoggerBinderPathSet; - } - private static boolean isAmbiguousStaticLoggerBinderPathSet(Set staticLoggerBinderPathSet) { - return staticLoggerBinderPathSet.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 staticLoggerBinderPathSet) { - if (isAmbiguousStaticLoggerBinderPathSet(staticLoggerBinderPathSet)) { - Util.report("Class path contains multiple SLF4J bindings."); - Iterator iterator = staticLoggerBinderPathSet.iterator(); - while (iterator.hasNext()) { - URL path = (URL) iterator.next(); - Util.report("Found binding in [" + path + "]"); - } - Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation."); + private final static void bind() { + try { + Set staticLoggerBinderPathSet = findPossibleStaticLoggerBinderPathSet(); + reportMultipleBindingAmbiguity(staticLoggerBinderPathSet); + // the next line does the binding + StaticLoggerBinder.getSingleton(); + INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION; + reportActualBinding(staticLoggerBinderPathSet); + fixSubstitutedLoggers(); + } 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.indexOf("org.slf4j.impl.StaticLoggerBinder.getSingleton()") != -1) { + 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 reportActualBinding(Set staticLoggerBinderPathSet) { - if (isAmbiguousStaticLoggerBinderPathSet(staticLoggerBinderPathSet)) { - Util.report("Actual binding is of type [" + StaticLoggerBinder.getSingleton().getLoggerFactoryClassStr() + "]"); + static void failedBinding(Throwable t) { + INITIALIZATION_STATE = FAILED_INITIALIZATION; + Util.report("Failed to instantiate SLF4J LoggerFactory", t); } - } - /** - * 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); - } + private final static void fixSubstitutedLoggers() { + List loggers = TEMP_FACTORY.getLoggers(); - /** - * 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 (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"); - } + if (loggers.isEmpty()) { + return; + } + + 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); + for (SubstituteLogger subLogger : loggers) { + subLogger.setDelegate(getLogger(subLogger.getName())); + Util.report(subLogger.getName()); + } + + TEMP_FACTORY.clear(); } - return logger; - } - private static boolean nonMatchingClasses(Class clazz, Class autoComputedCallingClass) { - return !autoComputedCallingClass.isAssignableFrom(clazz); - } + private final static void versionSanityCheck() { + try { + String requested = StaticLoggerBinder.REQUESTED_API_VERSION; - /** - * 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) { - INITIALIZATION_STATE = ONGOING_INITIALIZATION; - performInitialization(); + boolean match = false; + for (int i = 0; i < API_COMPATIBILITY_LIST.length; i++) { + if (requested.startsWith(API_COMPATIBILITY_LIST[i])) { + 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); + } } - 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://bugzilla.slf4j.org/show_bug.cgi?id=106 - return TEMP_FACTORY; + + // 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"; + + private 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 = (URL) paths.nextElement(); + staticLoggerBinderPathSet.add(path); + } + } catch (IOException ioe) { + Util.report("Error getting resources from path", ioe); + } + return staticLoggerBinderPathSet; + } + + private static boolean isAmbiguousStaticLoggerBinderPathSet(Set staticLoggerBinderPathSet) { + return staticLoggerBinderPathSet.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 staticLoggerBinderPathSet) { + if (isAmbiguousStaticLoggerBinderPathSet(staticLoggerBinderPathSet)) { + Util.report("Class path contains multiple SLF4J bindings."); + Iterator iterator = staticLoggerBinderPathSet.iterator(); + while (iterator.hasNext()) { + URL path = (URL) iterator.next(); + Util.report("Found binding in [" + path + "]"); + } + Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation."); + } + } + + private static void reportActualBinding(Set staticLoggerBinderPathSet) { + if (isAmbiguousStaticLoggerBinderPathSet(staticLoggerBinderPathSet)) { + 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 (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) { + 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://bugzilla.slf4j.org/show_bug.cgi?id=106 + return TEMP_FACTORY; + } + throw new IllegalStateException("Unreachable code"); } - 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 b63ebd49..06981772 100644 --- a/slf4j-api/src/main/java/org/slf4j/MDC.java +++ b/slf4j-api/src/main/java/org/slf4j/MDC.java @@ -63,205 +63,197 @@ import org.slf4j.spi.MDCAdapter; */ 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; + 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; + /** + * 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; + private MDCCloseable(String key) { + this.key = key; + } + + public void close() { + MDC.remove(this.key); + } } - public void close() { - MDC.remove(this.key); - } - } - - private MDC() { - } - - static { - try { - mdcAdapter = StaticMDCBinder.SINGLETON.getMDCA(); - } catch (NoClassDefFoundError ncde) { - mdcAdapter = new NOPMDCAdapter(); - String msg = ncde.getMessage(); - if (msg != null && msg.indexOf("StaticMDCBinder") != -1) { - 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"); + private MDC() { } - 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"); + static { + try { + mdcAdapter = StaticMDCBinder.SINGLETON.getMDCA(); + } catch (NoClassDefFoundError ncde) { + mdcAdapter = new NOPMDCAdapter(); + String msg = ncde.getMessage(); + if (msg != null && msg.indexOf("StaticMDCBinder") != -1) { + 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); + } } - if (mdcAdapter == null) { - throw new IllegalStateException("MDCAdapter cannot be null. See also " - + NULL_MDCA_URL); + /** + * 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); } - 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); + /** + * 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); } - 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); + /** + * 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); } - 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); + /** + * 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); } - 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; - } + /** + * 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 3d6c100c..c6bfd5e2 100644 --- a/slf4j-api/src/main/java/org/slf4j/Marker.java +++ b/slf4j-api/src/main/java/org/slf4j/Marker.java @@ -41,102 +41,102 @@ import java.util.Iterator; */ public interface Marker extends Serializable { - /** - * This constant represents any marker, including a null marker. - */ - public final String ANY_MARKER = "*"; + /** + * 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 = "+"; + /** + * 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(); + /** + * 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); + /** + * 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); + /** + * 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(); + /** + * @deprecated Replaced by {@link #hasReferences()}. + */ + public boolean hasChildren(); - /** - * 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 have any references? + * + * @return true if this marker has one or more references, false otherwise. + */ + public boolean hasReferences(); - /** - * 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); + /** + * 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(); - /** - * 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); + /** + * 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); - /** - * 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(); + /** + * 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 84cfcb6b..8d50698d 100644 --- a/slf4j-api/src/main/java/org/slf4j/MarkerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/MarkerFactory.java @@ -42,55 +42,55 @@ import org.slf4j.impl.StaticMarkerBinder; * @author Ceki Gülcü */ public class MarkerFactory { - static IMarkerFactory markerFactory; + static IMarkerFactory markerFactory; - private MarkerFactory() { - } - - static { - try { - markerFactory = StaticMarkerBinder.SINGLETON.getMarkerFactory(); - } catch (NoClassDefFoundError e) { - markerFactory = new BasicMarkerFactory(); - - } catch (Exception e) { - // we should never get here - Util.report("Unexpected failure while binding MarkerFactory", e); + private MarkerFactory() { } - } - /** - * 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 markerFactory.getMarker(name); - } + static { + try { + markerFactory = StaticMarkerBinder.SINGLETON.getMarkerFactory(); + } catch (NoClassDefFoundError e) { + markerFactory = new BasicMarkerFactory(); - /** - * 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 markerFactory.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 markerFactory; - } + } 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 markerFactory.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 markerFactory.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 markerFactory; + } } \ No newline at end of file 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 6f07c7d2..67ab9b5a 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMDCAdapter.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMDCAdapter.java @@ -43,120 +43,119 @@ import java.util.Map; */ public class BasicMDCAdapter implements MDCAdapter { - private InheritableThreadLocal> inheritableThreadLocal - = new InheritableThreadLocal>(); + private InheritableThreadLocal> inheritableThreadLocal = new InheritableThreadLocal>(); - static boolean isJDK14() { - try { - String javaVersion = System.getProperty("java.version"); - return javaVersion.startsWith("1.4"); - } catch(SecurityException se) { - // punt and assume JDK 1.5 or later - return false; + static boolean isJDK14() { + try { + String javaVersion = System.getProperty("java.version"); + return javaVersion.startsWith("1.4"); + } catch (SecurityException se) { + // punt and assume JDK 1.5 or later + return false; + } } - } - static boolean IS_JDK14 = isJDK14(); + static boolean IS_JDK14 = isJDK14(); - - /** - * 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"); + /** + * 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 = (Map) inheritableThreadLocal.get(); + if (map == null) { + map = Collections. synchronizedMap(new HashMap()); + inheritableThreadLocal.set(map); + } + map.put(key, val); } - Map map = (Map) inheritableThreadLocal.get(); - if (map == null) { - map = Collections.synchronizedMap(new HashMap()); - inheritableThreadLocal.set(map); - } - map.put(key, val); - } - /** - * Get the context identified by the key parameter. - */ - public String get(String key) { - Map Map = (Map) inheritableThreadLocal.get(); - if ((Map != null) && (key != null)) { - return (String) Map.get(key); - } else { - return null; + /** + * Get the context identified by the key parameter. + */ + public String get(String key) { + Map Map = (Map) inheritableThreadLocal.get(); + if ((Map != null) && (key != null)) { + return (String) Map.get(key); + } else { + return null; + } } - } - /** - * Remove the the context identified by the key parameter. - */ - public void remove(String key) { - Map map = (Map) inheritableThreadLocal.get(); - if (map != null) { - map.remove(key); + /** + * Remove the the context identified by the key parameter. + */ + public void remove(String key) { + Map map = (Map) inheritableThreadLocal.get(); + if (map != null) { + map.remove(key); + } } - } - /** - * Clear all entries in the MDC. - */ - public void clear() { - Map map = (Map) inheritableThreadLocal.get(); - if (map != null) { - map.clear(); - // the InheritableThreadLocal.remove method was introduced in JDK 1.5 - // Thus, invoking clear() on previous JDK 1.4 will fail - if(isJDK14()) { - inheritableThreadLocal.set(null); - } else { - inheritableThreadLocal.remove(); - } + /** + * Clear all entries in the MDC. + */ + public void clear() { + Map map = (Map) inheritableThreadLocal.get(); + if (map != null) { + map.clear(); + // the InheritableThreadLocal.remove method was introduced in JDK 1.5 + // Thus, invoking clear() on previous JDK 1.4 will fail + if (isJDK14()) { + inheritableThreadLocal.set(null); + } else { + 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 = (Map) inheritableThreadLocal.get(); - if (map != null) { - return map.keySet(); - } else { - return null; + /** + * 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 = (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 = (Map) inheritableThreadLocal.get(); - if (oldMap != null) { - Map newMap = Collections.synchronizedMap(new HashMap()); - synchronized (oldMap) { - newMap.putAll(oldMap); - } - return newMap; - } else { - return null; - } - } - public void setContextMap(Map contextMap) { - Map map = Collections.synchronizedMap(new HashMap(contextMap)); - inheritableThreadLocal.set(map); - } + /** + * Return a copy of the current thread's context map. + * Returned value may be null. + * + */ + public Map getCopyOfContextMap() { + Map oldMap = (Map) inheritableThreadLocal.get(); + if (oldMap != null) { + Map newMap = Collections. synchronizedMap(new HashMap()); + synchronized (oldMap) { + newMap.putAll(oldMap); + } + return newMap; + } else { + return null; + } + } + + public void setContextMap(Map contextMap) { + Map map = Collections. synchronizedMap(new HashMap(contextMap)); + inheritableThreadLocal.set(map); + } } diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarker.java b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarker.java index 1b760ef8..b296d5d2 100755 --- a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarker.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarker.java @@ -39,159 +39,157 @@ import org.slf4j.Marker; */ public class BasicMarker implements Marker { - private static final long serialVersionUID = 1803952589649545191L; + private static final long serialVersionUID = 1803952589649545191L; - private final String name; - private List referenceList; + private final String name; + private List referenceList; - BasicMarker(String name) { - if (name == null) { - throw new IllegalArgumentException("A marker name cannot be null"); - } - this.name = name; - } - - public String getName() { - return name; - } - - public synchronized 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 its future "parent" as a reference - return; - } else { - // let's add the reference - if (referenceList == null) { - referenceList = new Vector(); - } - referenceList.add(reference); - } - - } - - public synchronized boolean hasReferences() { - return ((referenceList != null) && (referenceList.size() > 0)); - } - - public boolean hasChildren() { - return hasReferences(); - } - - public synchronized Iterator iterator() { - if (referenceList != null) { - return referenceList.iterator(); - } else { - List emptyList = Collections.emptyList(); - return emptyList.iterator(); - } - } - - public synchronized boolean remove(Marker referenceToRemove) { - if (referenceList == null) { - return false; - } - - int size = referenceList.size(); - for (int i = 0; i < size; i++) { - Marker m = (Marker) referenceList.get(i); - if (referenceToRemove.equals(m)) { - referenceList.remove(i); - return true; - } - } - return false; - } - - public boolean contains(Marker other) { - if (other == null) { - throw new IllegalArgumentException("Other cannot be null"); - } - - if (this.equals(other)) { - return true; - } - - if (hasReferences()) { - for (int i = 0; i < referenceList.size(); i++) { - Marker ref = (Marker) referenceList.get(i); - if (ref.contains(other)) { - return true; + BasicMarker(String name) { + if (name == null) { + throw new IllegalArgumentException("A marker name cannot be null"); } - } - } - 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"); + this.name = name; } - if (this.name.equals(name)) { - return true; + public String getName() { + return name; } - if (hasReferences()) { - for (int i = 0; i < referenceList.size(); i++) { - Marker ref = (Marker) referenceList.get(i); - if (ref.contains(name)) { - return true; + public synchronized 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 its future "parent" as a reference + return; + } else { + // let's add the reference + if (referenceList == null) { + referenceList = new Vector(); + } + referenceList.add(reference); + } + } - 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(); + public synchronized boolean hasReferences() { + return ((referenceList != null) && (referenceList.size() > 0)); } - Iterator it = this.iterator(); - Marker reference; - StringBuilder sb = new StringBuilder(this.getName()); - sb.append(' ').append(OPEN); - while (it.hasNext()) { - reference = (Marker) it.next(); - sb.append(reference.getName()); - if (it.hasNext()) { - sb.append(SEP); - } - } - sb.append(CLOSE); - return sb.toString(); - } + public boolean hasChildren() { + return hasReferences(); + } + + public synchronized Iterator iterator() { + if (referenceList != null) { + return referenceList.iterator(); + } else { + List emptyList = Collections.emptyList(); + return emptyList.iterator(); + } + } + + public synchronized boolean remove(Marker referenceToRemove) { + if (referenceList == null) { + return false; + } + + int size = referenceList.size(); + for (int i = 0; i < size; i++) { + Marker m = (Marker) referenceList.get(i); + if (referenceToRemove.equals(m)) { + referenceList.remove(i); + return true; + } + } + return false; + } + + public boolean contains(Marker other) { + if (other == null) { + throw new IllegalArgumentException("Other cannot be null"); + } + + if (this.equals(other)) { + return true; + } + + if (hasReferences()) { + for (int i = 0; i < referenceList.size(); i++) { + Marker ref = (Marker) referenceList.get(i); + 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 (int i = 0; i < referenceList.size(); i++) { + Marker ref = (Marker) referenceList.get(i); + 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 = (Marker) 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 2107b9c8..5139bb66 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarkerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarkerFactory.java @@ -41,62 +41,59 @@ import org.slf4j.Marker; */ 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() { - } + private final ConcurrentMap markerMap = new ConcurrentHashMap(); - /** - * 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"); + /** + * Regular users should not create + * BasicMarkerFactory instances. Marker + * instances can be obtained using the static {@link + * org.slf4j.MarkerFactory#getMarker} method. + */ + public BasicMarkerFactory() { } - 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); - } + /** + * 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"); + } - public boolean detachMarker(String name) { - if(name == null) { - return false; + 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); } - 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 2afe295b..8d49ba45 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/FormattingTuple.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/FormattingTuple.java @@ -30,48 +30,47 @@ package org.slf4j.helpers; * @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; - if(throwable == null) { - this.argArray = argArray; - } else { - this.argArray = trimmedCopy(argArray); + static public FormattingTuple NULL = new FormattingTuple(null); + + private String message; + private Throwable throwable; + private Object[] argArray; + + public FormattingTuple(String message) { + this(message, null, null); } - } - static Object[] trimmedCopy(Object[] argArray) { - if(argArray == null || argArray.length == 0) { - throw new IllegalStateException("non-sensical empty or null argument array"); + public FormattingTuple(String message, Object[] argArray, Throwable throwable) { + this.message = message; + this.throwable = throwable; + if (throwable == null) { + this.argArray = argArray; + } else { + this.argArray = trimmedCopy(argArray); + } } - final int trimemdLen = argArray.length -1; - Object[] trimmed = new Object[trimemdLen]; - System.arraycopy(argArray, 0, trimmed, 0, trimemdLen); - return trimmed; - } - - public String getMessage() { - return message; - } - public Object[] getArgArray() { - return argArray; - } + 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; + } - public Throwable getThrowable() { - return throwable; - } + 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 c128df5d..dd765384 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/MarkerIgnoringBase.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/MarkerIgnoringBase.java @@ -27,7 +27,6 @@ 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 @@ -38,131 +37,130 @@ import org.slf4j.Marker; */ public abstract class MarkerIgnoringBase extends NamedLoggerBase implements Logger { - private static final long serialVersionUID = 9044267456635152283L; + private static final long serialVersionUID = 9044267456635152283L; - public boolean isTraceEnabled(Marker marker) { - return isTraceEnabled(); - } - - public void trace(Marker marker, String msg) { - trace(msg); - } + public boolean isTraceEnabled(Marker marker) { + return isTraceEnabled(); + } - public void trace(Marker marker, String format, Object arg) { - trace(format, arg); - } + public void trace(Marker marker, String msg) { + trace(msg); + } - public void trace(Marker marker, String format, Object arg1, Object arg2) { - trace(format, arg1, arg2); - } + public void trace(Marker marker, String format, Object arg) { + trace(format, arg); + } - public void trace(Marker marker, String format, Object... arguments) { - trace(format, arguments); - } + public void trace(Marker marker, String format, Object arg1, Object arg2) { + trace(format, arg1, arg2); + } - public void trace(Marker marker, String msg, Throwable t) { - trace(msg, t); - } - - public boolean isDebugEnabled(Marker marker) { - return isDebugEnabled(); - } + public void trace(Marker marker, String format, Object... arguments) { + trace(format, arguments); + } - public void debug(Marker marker, String msg) { - debug(msg); - } + public void trace(Marker marker, String msg, Throwable t) { + trace(msg, t); + } - public void debug(Marker marker, String format, Object arg) { - debug(format, arg); - } + public boolean isDebugEnabled(Marker marker) { + return isDebugEnabled(); + } - public void debug(Marker marker, String format, Object arg1, Object arg2) { - debug(format, arg1, arg2); - } + public void debug(Marker marker, String msg) { + debug(msg); + } - public void debug(Marker marker, String format, Object... arguments) { - debug(format, arguments); - } + public void debug(Marker marker, String format, Object arg) { + debug(format, arg); + } - public void debug(Marker marker, String msg, Throwable t) { - debug(msg, t); - } + public void debug(Marker marker, String format, Object arg1, Object arg2) { + debug(format, arg1, arg2); + } - public boolean isInfoEnabled(Marker marker) { - return isInfoEnabled(); - } + public void debug(Marker marker, String format, Object... arguments) { + debug(format, arguments); + } - public void info(Marker marker, String msg) { - info(msg); - } + public void debug(Marker marker, String msg, Throwable t) { + debug(msg, t); + } - public void info(Marker marker, String format, Object arg) { - info(format, arg); - } + public boolean isInfoEnabled(Marker marker) { + return isInfoEnabled(); + } - public void info(Marker marker, String format, Object arg1, Object arg2) { - info(format, arg1, arg2); - } + public void info(Marker marker, String msg) { + info(msg); + } - public void info(Marker marker, String format, Object... arguments) { - info(format, arguments); - } + public void info(Marker marker, String format, Object arg) { + info(format, arg); + } - public void info(Marker marker, String msg, Throwable t) { - info(msg, t); - } + public void info(Marker marker, String format, Object arg1, Object arg2) { + info(format, arg1, arg2); + } - public boolean isWarnEnabled(Marker marker) { - return isWarnEnabled(); - } + public void info(Marker marker, String format, Object... arguments) { + info(format, arguments); + } - public void warn(Marker marker, String msg) { - warn(msg); - } + public void info(Marker marker, String msg, Throwable t) { + info(msg, t); + } - public void warn(Marker marker, String format, Object arg) { - warn(format, arg); - } + public boolean isWarnEnabled(Marker marker) { + return isWarnEnabled(); + } - public void warn(Marker marker, String format, Object arg1, Object arg2) { - warn(format, arg1, arg2); - } + public void warn(Marker marker, String msg) { + warn(msg); + } - public void warn(Marker marker, String format, Object... arguments) { - warn(format, arguments); - } + public void warn(Marker marker, String format, Object arg) { + warn(format, arg); + } - public void warn(Marker marker, String msg, Throwable t) { - warn(msg, t); - } + public void warn(Marker marker, String format, Object arg1, Object arg2) { + warn(format, arg1, arg2); + } - - public boolean isErrorEnabled(Marker marker) { - return isErrorEnabled(); - } + public void warn(Marker marker, String format, Object... arguments) { + warn(format, arguments); + } - public void error(Marker marker, String msg) { - error(msg); - } + public void warn(Marker marker, String msg, Throwable t) { + warn(msg, t); + } - public void error(Marker marker, String format, Object arg) { - error(format, arg); - } + public boolean isErrorEnabled(Marker marker) { + return isErrorEnabled(); + } - public void error(Marker marker, String format, Object arg1, Object arg2) { - error(format, arg1, arg2); - } + public void error(Marker marker, String msg) { + error(msg); + } - public void error(Marker marker, String format, Object... arguments) { - error(format, arguments); - } + public void error(Marker marker, String format, Object arg) { + error(format, arg); + } - public void error(Marker marker, String msg, Throwable t) { - error(msg, t); - } + 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() + ")"; + } - 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 index aa5081db..cbecbfc6 100755 --- a/slf4j-api/src/main/java/org/slf4j/helpers/MessageFormatter.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/MessageFormatter.java @@ -96,328 +96,317 @@ import java.util.Map; * @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 = '\\'; + 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 argument - * 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; + /** + * 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 argument + * 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 }); } - final Object lastEntry = argArray[argArray.length - 1]; - if (lastEntry instanceof Throwable) { - return (Throwable) lastEntry; - } - return null; - } - - /** - * Same principle as the {@link #format(String, Object)} and - * {@link #format(String, Object, Object)} methods except that any number of - * arguments can be passed in an array. - * - * @param messagePattern - * The message pattern which will be parsed and formatted - * @param argArray - * An array of arguments to be substituted in place of formatting - * anchors - * @return The formatted message - */ - final public static FormattingTuple arrayFormat(final String messagePattern, - final Object[] argArray) { - - Throwable throwableCandidate = getThrowableCandidate(argArray); - - if (messagePattern == null) { - return new FormattingTuple(null, argArray, throwableCandidate); + /** + * + * 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 }); } - 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, - throwableCandidate); - } else { // add the tail string which contains no variables and return - // the result. - sbuf.append(messagePattern.substring(i, messagePattern.length())); - return new FormattingTuple(sbuf.toString(), argArray, - throwableCandidate); + static final Throwable getThrowableCandidate(Object[] argArray) { + if (argArray == null || argArray.length == 0) { + return null; } - } else { - if (isEscapedDelimeter(messagePattern, j)) { - if (!isDoubleEscaped(messagePattern, j)) { - L--; // DELIM_START was escaped, thus should not be incremented - sbuf.append(messagePattern.substring(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.substring(i, j - 1)); - deeplyAppendParameter(sbuf, argArray[L], new HashMap()); - i = j + 2; - } + + final Object lastEntry = argArray[argArray.length - 1]; + if (lastEntry instanceof Throwable) { + return (Throwable) lastEntry; + } + return null; + } + + /** + * Same principle as the {@link #format(String, Object)} and + * {@link #format(String, Object, Object)} methods except that any number of + * arguments can be passed in an array. + * + * @param messagePattern + * The message pattern which will be parsed and formatted + * @param argArray + * An array of arguments to be substituted in place of formatting + * anchors + * @return The formatted message + */ + final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) { + + Throwable throwableCandidate = getThrowableCandidate(argArray); + + if (messagePattern == null) { + return new FormattingTuple(null, argArray, throwableCandidate); + } + + 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, throwableCandidate); + } else { // add the tail string which contains no variables and return + // the result. + sbuf.append(messagePattern.substring(i, messagePattern.length())); + return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); + } + } else { + if (isEscapedDelimeter(messagePattern, j)) { + if (!isDoubleEscaped(messagePattern, j)) { + L--; // DELIM_START was escaped, thus should not be incremented + sbuf.append(messagePattern.substring(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.substring(i, j - 1)); + deeplyAppendParameter(sbuf, argArray[L], new HashMap()); + i = j + 2; + } + } else { + // normal case + sbuf.append(messagePattern.substring(i, j)); + deeplyAppendParameter(sbuf, argArray[L], new HashMap()); + i = j + 2; + } + } + } + // append the characters following the last {} pair. + sbuf.append(messagePattern.substring(i, messagePattern.length())); + if (L < argArray.length - 1) { + return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); } else { - // normal case - sbuf.append(messagePattern.substring(i, j)); - deeplyAppendParameter(sbuf, argArray[L], new HashMap()); - i = j + 2; + return new FormattingTuple(sbuf.toString(), argArray, null); } - } - } - // append the characters following the last {} pair. - sbuf.append(messagePattern.substring(i, messagePattern.length())); - if (L < argArray.length - 1) { - return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); - } else { - return new FormattingTuple(sbuf.toString(), argArray, null); - } - } - - 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) { - System.err - .println("SLF4J: Failed toString() invocation on an object of type [" - + o.getClass().getName() + "]"); - t.printStackTrace(); - sbuf.append("[FAILED toString()]"); } - } + final static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { - 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("..."); + if (delimeterStartIndex == 0) { + return false; + } + char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1); + if (potentialEscape == ESCAPE_CHAR) { + return true; + } else { + return false; + } } - 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(", "); + final static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { + if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) { + return true; + } else { + return false; + } } - 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(", "); + // 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); + } + } } - 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 safeObjectAppend(StringBuilder sbuf, Object o) { + try { + String oAsString = o.toString(); + sbuf.append(oAsString); + } catch (Throwable t) { + System.err.println("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]"); + t.printStackTrace(); + sbuf.append("[FAILED toString()]"); + } - 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(", "); + 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(']'); } - 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(", "); + 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(']'); } - 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(", "); + 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(']'); } - 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(", "); + 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(']'); } - 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 a1709ddb..5e0909d8 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NOPLogger.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NOPLogger.java @@ -27,7 +27,6 @@ package org.slf4j.helpers; import org.slf4j.Logger; import org.slf4j.helpers.MarkerIgnoringBase; - /** * A direct NOP (no operation) implementation of {@link Logger}. * @@ -35,195 +34,187 @@ import org.slf4j.helpers.MarkerIgnoringBase; */ public class NOPLogger extends MarkerIgnoringBase { - private static final long serialVersionUID = -517220405410904473L; + private static final long serialVersionUID = -517220405410904473L; - /** - * The unique instance of NOPLogger. - */ - public static final NOPLogger NOP_LOGGER = new NOPLogger(); + /** + * 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() { - } + /** + * 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 the string value "NOP". + */ + public String getName() { + return "NOP"; + } - /** - * Always returns false. - * @return always false - */ - final public boolean isTraceEnabled() { - return false; - } + /** + * 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 msg) { + // NOP + } - /** A NOP implementation. */ - final public void trace(String format, Object arg) { - // 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 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 - } + /** A NOP implementation. */ + public final void trace(String format, Object... argArray) { + // NOP + } - /** - * Always returns false. - * @return always false - */ - final public boolean isDebugEnabled() { - return false; - } + /** A NOP implementation. */ + final public void trace(String msg, Throwable t) { + // NOP + } - /** A NOP implementation. */ - final public void debug(String msg) { - // NOP - } + /** + * Always returns false. + * @return always false + */ + final public boolean isDebugEnabled() { + return false; + } - /** A NOP implementation. */ - final public void debug(String format, Object arg) { - // NOP - } + /** A NOP implementation. */ + final public void debug(String msg) { + // NOP + } - /** A NOP implementation. */ - public final void debug(String format, Object arg1, Object arg2) { - // NOP - } + /** A NOP implementation. */ + final public void debug(String format, Object arg) { + // 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 - } + /** A NOP implementation. */ + public final void debug(String format, Object arg1, Object arg2) { + // NOP + } - /** - * Always returns false. - * @return always false - */ - final public boolean isInfoEnabled() { - // NOP - return false; - } + /** A NOP implementation. */ + public final void debug(String format, Object... argArray) { + // NOP + } + /** A NOP implementation. */ + final public void debug(String msg, Throwable t) { + // NOP + } - /** A NOP implementation. */ - final public void info(String msg) { - // NOP - } + /** + * Always returns false. + * @return always false + */ + final public boolean isInfoEnabled() { + // NOP + return false; + } - /** A NOP implementation. */ - final public void info(String format, Object arg1) { - // NOP - } + /** A NOP implementation. */ + final public void info(String msg) { + // 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 format, Object arg1) { + // NOP + } + /** A NOP implementation. */ + final public void info(String format, Object arg1, Object arg2) { + // NOP + } - /** A NOP implementation. */ - final public void info(String msg, Throwable t) { - // 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; - } + /** + * 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 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) { + // 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 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 void warn(String msg, Throwable t) { + // NOP + } + /** A NOP implementation. */ + final public boolean isErrorEnabled() { + return false; + } - /** 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 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) { - // NOP - } + /** A NOP implementation. */ + final public void error(String format, Object arg1, Object arg2) { + // 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. */ + public final void error(String format, Object... argArray) { + // NOP + } - - /** A NOP implementation. */ - final public void error(String msg, Throwable t) { - // 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 9d4a2974..b8a55dc9 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NOPLoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NOPLoggerFactory.java @@ -28,7 +28,6 @@ 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 @@ -37,13 +36,13 @@ import org.slf4j.helpers.NOPLogger; * @author Ceki Gülcü */ public class NOPLoggerFactory implements ILoggerFactory { - - public NOPLoggerFactory() { - // nothing to do - } - - public Logger getLogger(String name) { - return NOPLogger.NOP_LOGGER; - } + + 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 e902fc78..22f3ea45 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NOPMDCAdapter.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NOPMDCAdapter.java @@ -39,25 +39,25 @@ import org.slf4j.spi.MDCAdapter; */ public class NOPMDCAdapter implements MDCAdapter { - public void clear() { - } + public void clear() { + } - public String get(String key) { - return null; - } + public String get(String key) { + return null; + } - public void put(String key, String val) { - } + public void put(String key, String val) { + } - public void remove(String key) { - } + public void remove(String key) { + } - public Map getCopyOfContextMap() { - return null; - } + public Map getCopyOfContextMap() { + return null; + } - public void setContextMap(Map contextMap) { - // NOP - } + 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 35df402c..184c3942 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NamedLoggerBase.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NamedLoggerBase.java @@ -39,32 +39,32 @@ import org.slf4j.LoggerFactory; */ abstract class NamedLoggerBase implements Logger, Serializable { - private static final long serialVersionUID = 7535258609338176893L; + 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()); - } + 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 d7cfedfd..1c37977e 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLogger.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLogger.java @@ -292,12 +292,15 @@ public class SubstituteLogger implements Logger { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; SubstituteLogger that = (SubstituteLogger) o; - if (!name.equals(that.name)) return false; + if (!name.equals(that.name)) + return false; return true; } diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java b/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java index b5ca4ffc..0697e39f 100755 --- a/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java @@ -40,28 +40,28 @@ import java.util.concurrent.ConcurrentMap; */ public class SubstituteLoggerFactory implements ILoggerFactory { - final ConcurrentMap loggers = new ConcurrentHashMap(); + final ConcurrentMap loggers = new ConcurrentHashMap(); - public Logger getLogger(String name) { - SubstituteLogger logger = loggers.get(name); - if (logger == null) { - logger = new SubstituteLogger(name); - SubstituteLogger oldLogger = loggers.putIfAbsent(name, logger); - if (oldLogger != null) - logger = oldLogger; + public Logger getLogger(String name) { + SubstituteLogger logger = loggers.get(name); + if (logger == null) { + logger = new SubstituteLogger(name); + SubstituteLogger oldLogger = loggers.putIfAbsent(name, logger); + if (oldLogger != null) + logger = oldLogger; + } + return logger; } - return logger; - } - public List getLoggerNames() { - return new ArrayList(loggers.keySet()); - } + public List getLoggerNames() { + return new ArrayList(loggers.keySet()); + } - public List getLoggers() { - return new ArrayList(loggers.values()); - } + public List getLoggers() { + return new ArrayList(loggers.values()); + } - public void clear() { - loggers.clear(); - } + public void clear() { + loggers.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 index 4fd5c508..91a09837 100755 --- a/slf4j-api/src/main/java/org/slf4j/helpers/Util.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/Util.java @@ -24,7 +24,6 @@ */ package org.slf4j.helpers; - /** * An internal utility class. * @@ -33,7 +32,8 @@ package org.slf4j.helpers; */ public final class Util { - private Util() {} + private Util() { + } /** * In order to call {@link SecurityManager#getClassContext()}, which is a @@ -59,16 +59,14 @@ public final class Util { // Advance until Util is found int i; - for(i = 0; i < trace.length; i++) { - if(thisClassName.equals(trace[i].getName())) + 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"); + 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]; 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 7148e807..e6747e53 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -37,37 +37,37 @@ import org.slf4j.ILoggerFactory; * @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 usually modified with each 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"); - } + /** + * The unique instance of this class. + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - public String getLoggerFactoryClassStr() { - throw new UnsupportedOperationException("This code should never make it into slf4j-api.jar"); - } + /** + * 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 usually modified with each 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 e8d6fa82..4fd65f40 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -26,7 +26,6 @@ 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. @@ -35,25 +34,24 @@ import org.slf4j.spi.MDCAdapter; */ public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new 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"); - } - - /** - * 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"); - } + private StaticMDCBinder() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + + /** + * 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 90df3daf..0823b827 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -42,30 +42,29 @@ import org.slf4j.spi.MarkerFactoryBinder; */ 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"); - } - - /** - * 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"); - } - - + /** + * 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"); + } + + /** + * 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/spi/LocationAwareLogger.java b/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java index 5177f247..8e0a2070 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java @@ -39,23 +39,22 @@ import org.slf4j.Marker; */ public interface LocationAwareLogger extends Logger { - 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); - + 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 438cc08b..c0c2ca05 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/LoggerFactoryBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/LoggerFactoryBinder.java @@ -34,24 +34,24 @@ import org.slf4j.ILoggerFactory; */ 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(); + /** + * 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 intterogate this binder's intention - * which may be different from the {@link ILoggerFactory} instance it is able to - * yield in practice. The discrepency should only occur in case of errors. - * - * @return the class name of the intended {@link ILoggerFactory} instance - */ - public String getLoggerFactoryClassStr(); + /** + * The String form of the {@link ILoggerFactory} object that this + * LoggerFactoryBinder instance is intended to return. + * + *

This method allows the developer to intterogate this binder's intention + * which may be different from the {@link ILoggerFactory} instance it is able to + * yield in practice. The discrepency 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 20e47f0b..2e637cbe 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/MDCAdapter.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/MDCAdapter.java @@ -35,57 +35,57 @@ import java.util.Map; */ 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 code>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); + /** + * 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 code>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); + /** + * 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); + /** + * 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(); + /** + * 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); + /** + * 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 78b557cb..a71140c9 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/MarkerFactoryBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/MarkerFactoryBinder.java @@ -26,7 +26,6 @@ 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. @@ -35,24 +34,24 @@ import org.slf4j.IMarkerFactory; */ 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(); + /** + * 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 intterogate this binder's intention - * which may be different from the {@link IMarkerFactory} instance it is able to - * return. Such a discrepency should only occur in case of errors. - * - * @return the class name of the intended {@link IMarkerFactory} instance - */ - public String getMarkerFactoryClassStr(); + /** + * The String form of the {@link IMarkerFactory} object that this + * MarkerFactoryBinder instance is intended to return. + * + *

This method allows the developer to intterogate this binder's intention + * which may be different from the {@link IMarkerFactory} instance it is able to + * return. Such a discrepency 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/test/java/org/slf4j/BasicMarkerTest.java b/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java index 913a26ad..50471b59 100644 --- a/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java +++ b/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java @@ -37,160 +37,160 @@ import org.slf4j.helpers.BasicMarkerFactory; * @author Joern Huxhorn */ public class BasicMarkerTest extends TestCase { - 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"; + 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; + 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(); + short diff = Differentiator.getDiffentiator(); - blue = factory.getMarker(BLUE_STR); - red = factory.getMarker(RED_STR); - green = factory.getMarker(GREEN_STR); - comp = factory.getMarker(COMP_STR); - comp.add(blue); + public BasicMarkerTest() { + factory = new BasicMarkerFactory(); - multiComp = factory.getMarker(MULTI_COMP_STR); - multiComp.add(green); - multiComp.add(comp); - } + blue = factory.getMarker(BLUE_STR); + red = factory.getMarker(RED_STR); + green = factory.getMarker(GREEN_STR); + comp = factory.getMarker(COMP_STR); + comp.add(blue); - 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)); - } - - public void testPrimitiveByName() { - assertTrue(blue.contains(BLUE_STR)); - } - - public void testComposite() { - assertTrue(comp.contains(comp)); - assertTrue(comp.contains(blue)); - } - - public void testCompositeByName() { - assertTrue(comp.contains(COMP_STR)); - assertTrue(comp.contains(BLUE_STR)); - } - - public void testMultiComposite() { - assertTrue(multiComp.contains(comp)); - assertTrue(multiComp.contains(blue)); - assertTrue(multiComp.contains(green)); - assertFalse(multiComp.contains(red)); - } - - public void testMultiCompositeByName() { - assertTrue(multiComp.contains(COMP_STR)); - assertTrue(multiComp.contains(BLUE_STR)); - assertTrue(multiComp.contains(GREEN_STR)); - assertFalse(multiComp.contains(RED_STR)); - } - - 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); + multiComp = factory.getMarker(MULTI_COMP_STR); + multiComp.add(green); + multiComp.add(comp); } - // 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()); - } + public void testPrimitive() { + assertEquals(BLUE_STR, blue.getName()); + assertTrue(blue.contains(blue)); - 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)); + Marker blue2 = factory.getMarker(BLUE_STR); + assertEquals(BLUE_STR, blue2.getName()); + assertEquals(blue, blue2); + assertTrue(blue.contains(blue2)); + assertTrue(blue2.contains(blue)); + } - parent.add(child); + public void testPrimitiveByName() { + assertTrue(blue.contains(BLUE_STR)); + } - assertTrue(parent.contains(child)); - assertTrue(parent.contains(NEW_PREFIX + CHILD_MARKER_STR)); + public void testComposite() { + assertTrue(comp.contains(comp)); + assertTrue(comp.contains(blue)); + } - assertTrue(parent.remove(child)); + public void testCompositeByName() { + assertTrue(comp.contains(COMP_STR)); + assertTrue(comp.contains(BLUE_STR)); + } - assertFalse(parent.contains(child)); - assertFalse(parent.contains(NEW_PREFIX + CHILD_MARKER_STR)); - assertFalse(parent.remove(child)); - } + public void testMultiComposite() { + assertTrue(multiComp.contains(comp)); + assertTrue(multiComp.contains(blue)); + assertTrue(multiComp.contains(green)); + assertFalse(multiComp.contains(red)); + } - 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)); - } + public void testMultiCompositeByName() { + assertTrue(multiComp.contains(COMP_STR)); + assertTrue(multiComp.contains(BLUE_STR)); + assertTrue(multiComp.contains(GREEN_STR)); + assertFalse(multiComp.contains(RED_STR)); + } - 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; + 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); + } - Marker parent = factory.getMarker(PARENT_NAME); - Marker child = factory.getMarker(CHILD_NAME); - Marker notContained = factory.getMarker(NOT_CONTAINED_NAME); + // 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()); + } - 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)); - } + 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)); + } + + 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)); + } + + 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)); + } + + 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)); + } - 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 3efaddd7..09b9a35a 100644 --- a/slf4j-api/src/test/java/org/slf4j/Differentiator.java +++ b/slf4j-api/src/test/java/org/slf4j/Differentiator.java @@ -29,9 +29,9 @@ 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); - } + 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/NoBindingTest.java b/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java index bdfbe755..7a5ec2d8 100644 --- a/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java +++ b/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java @@ -33,21 +33,21 @@ import junit.framework.TestCase; public class NoBindingTest extends TestCase { - int diff = new Random().nextInt(10000); - - public void testLogger() { - Logger logger = LoggerFactory.getLogger(NoBindingTest.class); - logger.debug("hello"+diff); - assertTrue(logger instanceof NOPLogger); - } + int diff = new Random().nextInt(10000); - public void testMDC() { - MDC.put("k"+diff, "v"); - assertNull(MDC.get("k")); - } + public void testLogger() { + Logger logger = LoggerFactory.getLogger(NoBindingTest.class); + logger.debug("hello" + diff); + assertTrue(logger instanceof NOPLogger); + } - public void testMarker() { - Marker m = MarkerFactory.getMarker("a"+diff); - assertTrue(m instanceof BasicMarker); - } + public void testMDC() { + MDC.put("k" + diff, "v"); + assertNull(MDC.get("k")); + } + + public void testMarker() { + Marker m = MarkerFactory.getMarker("a" + diff); + assertTrue(m instanceof BasicMarker); + } } 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 0921b988..86f7d67d 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/BogoPerf.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/BogoPerf.java @@ -36,124 +36,115 @@ import junit.framework.AssertionFailedError; */ 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; + 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(); + static { + // let the JIT warm up + computeBogoIPS(INITIAL_N); + double bogo_ips = computeBogoIPS(INITIAL_N); + System.out.println("Host runs at " + bogo_ips + " BIPS"); } - 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"); + /** + * 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(); - double bogoIPS = NANOS_IN_ONE_SECOND / avgDPIS; - // System.out.println(bogoIPS + " bogoIPS"); + for (int i = 0; i < N; i++) { + bogoInstruction(); + } + long end = System.nanoTime(); - return bogoIPS; - } + // 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"); - 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(); + double bogoIPS = NANOS_IN_ONE_SECOND / avgDPIS; + // System.out.println(bogoIPS + " bogoIPS"); + + return bogoIPS; } - // 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)"); + 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); } - } - /** - * 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)"); + /** + * Computed the BogoIPS for this host CPU. + * + * @return + */ + public static double currentBIPS() { + return computeBogoIPS(LAST_N); } - } - private static double adjustExpectedPerformance(long referenceDuration, - double referenceBIPS) { - double currentBIPS = currentBIPS(); - return referenceDuration * (currentBIPS / referenceBIPS); - } + static double min(double a, double b) { + return (a <= b) ? a : b; + } - private static double adjustExpectedDuration(long referenceDuration, - double referenceBIPS) { - double currentBIPS = currentBIPS(); - System.out.println("currentBIPS=" + currentBIPS + " BIPS"); - return referenceDuration * (referenceBIPS / currentBIPS); - } + /** + * 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 6c09e244..e8f7bcfc 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSort.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSort.java @@ -32,19 +32,20 @@ package org.slf4j.helpers; */ 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 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; - } + + 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 24f2f306..3592eb02 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSortTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSortTest.java @@ -36,66 +36,65 @@ import junit.framework.TestCase; * */ public class BubbleSortTest extends TestCase { - - 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++]); - } - - public void testEmpty() { - int[] a = new int[] {}; - BubbleSort.sort(a); - } - - 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++]); - } - - 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++]); - } - 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++]); - } - - - 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; + 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++]); + } + + public void testEmpty() { + int[] a = new int[] {}; + BubbleSort.sort(a); + } + + 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++]); + } + + 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++]); + } + + 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++]); + } + + 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)); } - 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 index 1b07a6e1..7b9640bb 100755 --- a/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterPerfTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterPerfTest.java @@ -32,84 +32,80 @@ import org.junit.Ignore; @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; + Integer i1 = new Integer(1); + Integer i2 = new Integer(2); + static long RUN_LENGTH = 100 * 1000; + // + static long REFERENCE_BIPS = 48416; - public MessageFormatterPerfTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - } - - protected void tearDown() throws Exception { - } - - public void XtestJDKFormatterPerf() { - jdkMessageFormatter(RUN_LENGTH); - double duration = jdkMessageFormatter(RUN_LENGTH); - System.out.println("jdk duration = " + duration + " nanos"); - } - - 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); - } - - 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); + public MessageFormatterPerfTest(String name) { + super(name); } - 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(); + + protected void setUp() throws Exception { } - 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); + protected void tearDown() throws Exception { + } + + public void XtestJDKFormatterPerf() { + jdkMessageFormatter(RUN_LENGTH); + double duration = jdkMessageFormatter(RUN_LENGTH); + System.out.println("jdk duration = " + duration + " nanos"); + } + + 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); + } + + 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); } - 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 index 6696dbe5..98ebaa78 100755 --- a/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java @@ -35,327 +35,290 @@ import static org.junit.Assert.*; */ 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) }; + 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; + 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()); + @Test + public void testNull() { + result = MessageFormatter.format(null, i1).getMessage(); + assertEquals(null, result); } - { - 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 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 testArrayThrowable() { - FormattingTuple ft; - Throwable t = new Throwable(); - Object[] ia = new Object[] { i1, i2, i3, t }; - Object[] iaWitness = new Object[] { i1, i2, i3 }; + @Test + public void verifyOneParameterIsHandledCorrectly() { + result = MessageFormatter.format("Value is {}.", i3).getMessage(); + assertEquals("Value is 3.", result); - 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()); + result = MessageFormatter.format("Value is {", i3).getMessage(); + assertEquals("Value is {", result); - ft = MessageFormatter.arrayFormat("{}{}{}", ia); - assertEquals("123", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); + result = MessageFormatter.format("{} is larger than 2.", i3).getMessage(); + assertEquals("3 is larger than 2.", result); - 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()); + result = MessageFormatter.format("No subst", i3).getMessage(); + assertEquals("No subst", result); - 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()); + result = MessageFormatter.format("Incorrect {subst", i3).getMessage(); + assertEquals("Incorrect {subst", result); - ft = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia); - assertEquals("Val=1, {, Val=2", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); + result = MessageFormatter.format("Value is {bla} {}", i3).getMessage(); + assertEquals("Value is {bla} 3", result); - ft = MessageFormatter.arrayFormat("Val={}, \\{, Val={}", ia); - assertEquals("Val=1, \\{, Val=2", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); + result = MessageFormatter.format("Escaped \\{} subst", i3).getMessage(); + assertEquals("Escaped {} subst", result); - ft = MessageFormatter.arrayFormat("Val1={}, Val2={", ia); - assertEquals("Val1=1, Val2={", ft.getMessage()); - assertTrue(Arrays.equals(iaWitness, ft.getArgArray())); - assertEquals(t, ft.getThrowable()); + result = MessageFormatter.format("{Escaped", i3).getMessage(); + assertEquals("{Escaped", result); - ft = MessageFormatter.arrayFormat( - "Value {} is smaller than {} and {} -- {} .", ia); - assertEquals("Value 1 is smaller than 2 and 3 -- " + t.toString() + " .", - ft.getMessage()); - assertTrue(Arrays.equals(ia, ft.getArgArray())); - assertNull(ft.getThrowable()); + result = MessageFormatter.format("\\{}Escaped", i3).getMessage(); + assertEquals("{}Escaped", result); - ft = MessageFormatter.arrayFormat("{}{}{}{}", ia); - assertEquals("123" + t.toString(), ft.getMessage()); - assertTrue(Arrays.equals(ia, ft.getArgArray())); - assertNull(ft.getThrowable()); - } + 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 -- " + t.toString() + " .", ft.getMessage()); + assertTrue(Arrays.equals(ia, ft.getArgArray())); + assertNull(ft.getThrowable()); + + ft = MessageFormatter.arrayFormat("{}{}{}{}", ia); + assertEquals("123" + t.toString(), ft.getMessage()); + assertTrue(Arrays.equals(ia, ft.getArgArray())); + assertNull(ft.getThrowable()); + } } 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 e9d95ec0..c817d673 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/MyRandom.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/MyRandom.java @@ -24,31 +24,28 @@ */ package org.slf4j.helpers; +class MyRandom { -class MyRandom { + private final static long m = 200000000041L; // a prime number + private final static long a = 2000000011L; // a prime number - 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()); - } + long y; + long unused; + int bits = 32; - - 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); - } + 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 3055b7ee..210252f3 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/SubstitutableLoggerTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/SubstitutableLoggerTest.java @@ -41,67 +41,66 @@ import org.slf4j.Logger; * @author Chetan Mehrotra */ public class SubstitutableLoggerTest extends TestCase { - private static final Set EXCLUDED_METHODS = new HashSet(Arrays.asList("getName")); + private static final Set EXCLUDED_METHODS = new HashSet(Arrays.asList("getName")); - public void testDelegate() throws Exception { - SubstituteLogger log = new SubstituteLogger("foo"); - assertTrue(log.delegate() instanceof NOPLogger); + public void testDelegate() throws Exception { + SubstituteLogger log = new SubstituteLogger("foo"); + assertTrue(log.delegate() instanceof NOPLogger); - Set expectedMethodSignatures = determineMethodSignatures(Logger.class); - LoggerInvocationHandler ih = new LoggerInvocationHandler(); - Logger proxyLogger = (Logger) Proxy.newProxyInstance(getClass().getClassLoader(), - new Class[]{Logger.class}, ih); - log.setDelegate(proxyLogger); + 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); + 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; + // Assert that all methods are delegated + expectedMethodSignatures.removeAll(ih.getInvokedMethodSignatures()); + if (!expectedMethodSignatures.isEmpty()) { + fail("Following methods are not delegated " + expectedMethodSignatures.toString()); + } } - public Set getInvokedMethodSignatures() { - return invokedMethodSignatures; + 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 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 class LoggerInvocationHandler implements InvocationHandler { + private final Set invokedMethodSignatures = new HashSet(); - private static String getMethodSignature(Method m) { - List result = new ArrayList(); - result.add(m.getName()); - for (Class clazz : m.getParameterTypes()) { - result.add(clazz.getSimpleName()); + 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(); } - 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 index 8e76610f..370fc14b 100755 --- a/slf4j-api/src/test/java/org/slf4j/helpers/SubstituteLoggerFactoryTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/SubstituteLoggerFactoryTest.java @@ -31,39 +31,39 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; -public class SubstituteLoggerFactoryTest extends TestCase{ - private SubstituteLoggerFactory factory = new SubstituteLoggerFactory(); +public class SubstituteLoggerFactoryTest extends TestCase { + private SubstituteLoggerFactory factory = new SubstituteLoggerFactory(); - public void testFactory() { - Logger log = factory.getLogger("foo"); - assertNotNull(log); + 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); - } - - 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); - } - - 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()); + Logger log2 = factory.getLogger("foo"); + assertTrue("Loggers with same name must be same", log == log2); } - assertEquals(expectedNames, actualNames); - } + 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); + } + + 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/src/main/java/org/slf4j/NDC.java b/slf4j-ext/src/main/java/org/slf4j/NDC.java index 0e5ac531..fbad2741 100644 --- a/slf4j-ext/src/main/java/org/slf4j/NDC.java +++ b/slf4j-ext/src/main/java/org/slf4j/NDC.java @@ -27,36 +27,36 @@ package org.slf4j; import org.slf4j.MDC; public class NDC { - public final static String PREFIX = "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; - } + private static int size() { + int i = 0; + while (true) { + String val = MDC.get(PREFIX + i); + if (val != null) { + i++; + } else { + break; + } + } + return i; } - 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 ""; + 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; } - 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 fa577439..181dfba5 100644 --- a/slf4j-ext/src/main/java/org/slf4j/agent/AgentOptions.java +++ b/slf4j-ext/src/main/java/org/slf4j/agent/AgentOptions.java @@ -37,27 +37,27 @@ package org.slf4j.agent; */ 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"; + /** + * 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 851c97b8..bca08135 100644 --- a/slf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java +++ b/slf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java @@ -38,94 +38,91 @@ import org.slf4j.instrumentation.LogTransformer; */ public class AgentPremain { - /** - * JavaAgent premain entry point as specified in the MANIFEST.MF file. See - * {@link 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) { + /** + * JavaAgent premain entry point as specified in the MANIFEST.MF file. See + * {@link 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. + // 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); + LogTransformer.Builder builder = new LogTransformer.Builder(); + builder = builder.addEntryExit(true); - if (agentArgument != null) { - Properties args = parseArguments(agentArgument, ","); + if (agentArgument != null) { + Properties args = parseArguments(agentArgument, ","); - if (args.containsKey(AgentOptions.VERBOSE)) { - builder = builder.verbose(true); - } + if (args.containsKey(AgentOptions.VERBOSE)) { + builder = builder.verbose(true); + } - if (args.containsKey(AgentOptions.TIME)) { - printStartStopTimes(); - } + 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.IGNORE)) { + String ignore = args.getProperty(AgentOptions.IGNORE); + builder = builder.ignore(ignore.split(":")); + } - if (args.containsKey(AgentOptions.LEVEL)) { - builder = builder.level(args.getProperty(AgentOptions.LEVEL)); - } - } + if (args.containsKey(AgentOptions.LEVEL)) { + builder = builder.level(args.getProperty(AgentOptions.LEVEL)); + } + } - instrumentation.addTransformer(builder.build()); - } + 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; - } + /** + * 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(); + /** + * 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()); + 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); - } + 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); + } } \ No newline at end of file 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 88efdb0f..d4ee8fe5 100644 --- a/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLogger.java +++ b/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLogger.java @@ -41,138 +41,133 @@ import ch.qos.cal10n.MessageParameterObj; */ public class LocLogger extends LoggerWrapper implements Logger { - private static final String FQCN = LocLogger.class.getName(); + 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"); + /** + * 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; + final IMessageConveyor imc; - public LocLogger(Logger logger, IMessageConveyor imc) { - super(logger, LoggerWrapper.class.getName()); - if (imc == null) { - throw new IllegalArgumentException("IMessageConveyor cannot be null"); + public LocLogger(Logger logger, IMessageConveyor imc) { + super(logger, LoggerWrapper.class.getName()); + if (imc == null) { + throw new IllegalArgumentException("IMessageConveyor cannot be null"); + } + this.imc = imc; } - 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); + /** + * 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); + 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); + /** + * 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); + 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); + /** + * 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); + 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); + /** + * 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); + 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); + /** + * 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); + 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 1a9592df..2e54beec 100644 --- a/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLoggerFactory.java +++ b/slf4j-ext/src/main/java/org/slf4j/cal10n/LocLoggerFactory.java @@ -46,30 +46,30 @@ import ch.qos.cal10n.IMessageConveyor; */ public class LocLoggerFactory { - final IMessageConveyor imc; + final IMessageConveyor imc; - public LocLoggerFactory(IMessageConveyor imc) { - this.imc = 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 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()); - } + /** + * 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/ext/EventData.java b/slf4j-ext/src/main/java/org/slf4j/ext/EventData.java index 7430548a..cd661b83 100755 --- a/slf4j-ext/src/main/java/org/slf4j/ext/EventData.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/EventData.java @@ -42,265 +42,264 @@ import java.beans.ExceptionListener; * @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() { - } + private static final long serialVersionUID = 153270778642103985L; - /** - * Constructor to create event data from a Map. - * - * @param map - * The event data. - */ - public EventData(Map map) { - eventData.putAll(map); - } + 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"; - /** - * 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); + /** + * Default Constructor + */ + public EventData() { } - } - /** - * Serialize all the EventData items into an XML representation. - * - * @return an XML String containing all the EventDAta items. - */ - public String toXML() { - return toXML(eventData); - } + /** + * Constructor to create event data from a Map. + * + * @param map + * The event data. + */ + public EventData(Map map) { + eventData.putAll(map); + } - /** - * 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(); + /** + * 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); } - }); - 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"); + /** + * Serialize all the EventData items into an XML representation. + * + * @return an XML String containing all the EventDAta items. + */ + public String toXML() { + return toXML(eventData); } - 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; + /** + * 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; + } } - if (!(o instanceof EventData || o instanceof Map)) { - return false; + + /** + * Retrieve the event identifier. + * + * @return The event identifier + */ + public String getEventId() { + return (String) this.eventData.get(EVENT_ID); } - Map map = (o instanceof EventData) ? ((EventData) o) - .getEventMap() : (Map) o; - return this.eventData.equals(map); - } + /** + * 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); + } - /** - * Compute the hashCode for this EventData instance. - * - * @return The hashcode for this EventData instance. - */ - @Override - public int hashCode() { - return this.eventData.hashCode(); - } + /** + * 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 index 71b52b92..ab220768 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/EventException.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/EventException.java @@ -29,38 +29,38 @@ package org.slf4j.ext; */ public class EventException extends RuntimeException { - private static final long serialVersionUID = -22873966112391992L; + private static final long serialVersionUID = -22873966112391992L; - /** - * Default constructor. - */ - public EventException() { - super(); - } + /** + * Default constructor. + */ + public EventException() { + super(); + } - /** - * Constructor that allows an exception message. - * @param exceptionMessage The exception message. - */ - public EventException(String exceptionMessage) { - super(exceptionMessage); - } + /** + * 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. + * @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 excepton. - */ - public EventException(String exceptionMessage, Throwable originalException) { - super(exceptionMessage, 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 excepton. + */ + 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 index d296312f..a72e656e 100755 --- a/slf4j-ext/src/main/java/org/slf4j/ext/EventLogger.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/EventLogger.java @@ -37,30 +37,28 @@ import org.slf4j.spi.LocationAwareLogger; */ public class EventLogger { - private static final String FQCN = EventLogger.class.getName(); + private static final String FQCN = EventLogger.class.getName(); - static Marker EVENT_MARKER = MarkerFactory.getMarker("EVENT"); + static Marker EVENT_MARKER = MarkerFactory.getMarker("EVENT"); - private static LoggerWrapper eventLogger = - new LoggerWrapper(LoggerFactory.getLogger("EventLogger"), FQCN); + 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); + /** + * 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 29a881d2..392ddaf5 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/LoggerWrapper.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/LoggerWrapper.java @@ -39,905 +39,806 @@ import org.slf4j.spi.LocationAwareLogger; */ 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 + // 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; + 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; + 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 boolean isTraceEnabled() { + return logger.isTraceEnabled(); } - } - /** - * 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 boolean isTraceEnabled(Marker marker) { + return logger.isTraceEnabled(marker); } - } - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(String format, Object arg1, Object arg2) { - if (!logger.isTraceEnabled()) - return; + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String msg) { + 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); + 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... args) { - if (!logger.isTraceEnabled()) - return; + /** + * 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.arrayFormat(format, args) - .getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.TRACE_INT, formattedMessage, args, null); - } else { - logger.trace(format, args); + 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 msg, Throwable t) { - if (!logger.isTraceEnabled()) - return; + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String format, Object arg1, Object arg2) { + if (!logger.isTraceEnabled()) + return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.TRACE_INT, msg, null, t); - } else { - logger.trace(msg, t); + 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(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(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(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(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 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 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... 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 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 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 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 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 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 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 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 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 boolean isDebugEnabled() { + return logger.isDebugEnabled(); } - } - /** - * 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 boolean isDebugEnabled(Marker marker) { + return logger.isDebugEnabled(marker); } - } - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String msg, Throwable t) { - if (!logger.isDebugEnabled()) - return; + /** + * 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, t); - } else { - logger.debug(msg, t); + 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(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(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(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(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(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(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(Marker marker, String format, Object... argArray) { - if (!logger.isDebugEnabled(marker)) - return; - if (instanceofLAL) { + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String msg, Throwable t) { + if (!logger.isDebugEnabled()) + return; - 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); + 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, 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 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 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 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 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 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 info(String format, Object arg1, Object arg2) { - if (!logger.isInfoEnabled()) - return; + /** + * 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) { - 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); + 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 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 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 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 boolean isInfoEnabled() { + return logger.isInfoEnabled(); } - } - /** - * 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 boolean isInfoEnabled(Marker marker) { + return logger.isInfoEnabled(marker); } - } - /** - * 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(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(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(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(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(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(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); + /** + * 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); + } } - } - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(String msg, Throwable t) { + if (!logger.isInfoEnabled()) + return; - /** - * 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); + 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 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 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 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 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 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 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 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 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 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 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); + } } - } - /** - * 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); + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); } - } - /** - * 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 boolean isWarnEnabled(Marker marker) { + return logger.isWarnEnabled(marker); } - } - /** - * 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(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(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 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 boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String format, Object arg1, Object arg2) { + if (!logger.isWarnEnabled()) + return; - /** - * 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); + 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 error(String format, Object arg) { - if (!logger.isErrorEnabled()) - return; + /** + * 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.format(format, arg) - .getMessage(); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.ERROR_INT, formattedMessage, - new Object[] { arg }, null); - } else { - logger.error(format, arg); + 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 error(String format, Object arg1, Object arg2) { - if (!logger.isErrorEnabled()) - return; + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String msg, Throwable t) { + if (!logger.isWarnEnabled()) + 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); + 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 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 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 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 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 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 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 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 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 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 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 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 boolean isErrorEnabled() { + return logger.isErrorEnabled(); } - } - /** - * 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 boolean isErrorEnabled(Marker marker) { + return logger.isErrorEnabled(marker); } - } - /** - * Delegate to the appropriate method of the underlying logger. - */ - public String getName() { - return logger.getName(); - } + /** + * 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 40a93547..5d1e63cf 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/MDCStrLookup.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/MDCStrLookup.java @@ -27,7 +27,6 @@ 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. 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 f0db1ef8..06f01626 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java @@ -40,188 +40,177 @@ import org.slf4j.spi.LocationAwareLogger; */ 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"); + 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 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 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); + 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; + 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 int intValue() { - return this.level; + 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; + } } - 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://bugzilla.slf4j.org/show_bug.cgi?id=114 + super(logger, LoggerWrapper.class.getName()); } - } - /** - * 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://bugzilla.slf4j.org/show_bug.cgi?id=114 - 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 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 + */ + 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()); + /** + * 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; } - 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); + /** + * 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; } - 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); + /** + * 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; } - 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. 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); + /** + * 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(", "); + 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(); } - 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 bd33e153..846a56e8 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/XLoggerFactory.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/XLoggerFactory.java @@ -42,24 +42,24 @@ import org.slf4j.LoggerFactory; */ 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 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()); - } + /** + * 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/instrumentation/JavassistHelper.java b/slf4j-ext/src/main/java/org/slf4j/instrumentation/JavassistHelper.java index 3992e32e..17c52674 100644 --- a/slf4j-ext/src/main/java/org/slf4j/instrumentation/JavassistHelper.java +++ b/slf4j-ext/src/main/java/org/slf4j/instrumentation/JavassistHelper.java @@ -39,152 +39,148 @@ import javassist.bytecode.LocalVariableAttribute; */ public class JavassistHelper { - /** - * Create a javaassist source snippet which either is empty (for anything - * which does not return a value) or a explanatory text around the $_ - * javaassist return value variable. - * - * @param method - * descriptor of method - * @return source snippet - * @throws NotFoundException - */ - public static String returnValue(CtBehavior method) - throws NotFoundException { + /** + * Create a javaassist source snippet which either is empty (for anything + * which does not return a value) or a explanatory text around the $_ + * javaassist 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; - } + 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 { + /** + * 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; - } + if (method instanceof CtMethod == false) { + return false; + } - CtClass returnType = ((CtMethod) method).getReturnType(); - String returnTypeName = returnType.getName(); + CtClass returnType = ((CtMethod) method).getReturnType(); + String returnTypeName = returnType.getName(); - boolean isVoidMethod = "void".equals(returnTypeName); + boolean isVoidMethod = "void".equals(returnTypeName); - boolean methodReturnsValue = isVoidMethod == false; - return methodReturnsValue; - } + boolean methodReturnsValue = isVoidMethod == false; + return methodReturnsValue; + } - /** - * Return javaassist 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 { + /** + * Return javaassist 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(); + CtClass parameterTypes[] = method.getParameterTypes(); - CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute(); + CodeAttribute codeAttribute = method.getMethodInfo().getCodeAttribute(); - LocalVariableAttribute locals = null; + LocalVariableAttribute locals = null; - if (codeAttribute != null) { - AttributeInfo attribute; - attribute = codeAttribute.getAttribute("LocalVariableTable"); - locals = (LocalVariableAttribute) attribute; - } + if (codeAttribute != null) { + AttributeInfo attribute; + attribute = codeAttribute.getAttribute("LocalVariableTable"); + locals = (LocalVariableAttribute) attribute; + } - String methodName = method.getName(); + 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(" + \", \" "); - } + 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(); - } - } + 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("\" + \"="); + 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("+\")"); + 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; - } + 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) { + /** + * 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); - } + if (locals == null) { + return Integer.toString(i + 1); + } - int modifiers = method.getModifiers(); + int modifiers = method.getModifiers(); - int j = i; + 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; - } + 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 c1e39467..09eff678 100644 --- a/slf4j-ext/src/main/java/org/slf4j/instrumentation/LogTransformer.java +++ b/slf4j-ext/src/main/java/org/slf4j/instrumentation/LogTransformer.java @@ -54,271 +54,260 @@ import org.slf4j.helpers.MessageFormatter; */ 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. - * - * {@link 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. + * Builder provides a flexible way of configuring some of many options on the + * parent class instead of providing many constructors. + * + * {@link http + * ://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html} * - * @return */ - public LogTransformer build() { - if (verbose) { - System.err.println("Creating LogTransformer"); - } - return new LogTransformer(this); + 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 returnvalue)? + * + * @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; + } } - boolean addEntryExit; + private String level; + private String levelEnabled; - /** - * Should each method log entry (with parameters) and exit (with parameters - * and returnvalue)? - * - * @param b - * value of flag - * @return - */ - public Builder addEntryExit(boolean b) { - addEntryExit = b; - return this; + 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"; } - boolean addVariableAssignment; + private boolean addEntryExit; + // private boolean addVariableAssignment; + private boolean verbose; + private String[] ignore; - // private Builder addVariableAssignment(boolean b) { - // System.err.println("cannot currently log variable assignments."); - // addVariableAssignment = b; - // return this; - // } + public byte[] transform(ClassLoader loader, String className, Class clazz, ProtectionDomain domain, byte[] bytes) { - boolean verbose; + try { + return transform0(className, clazz, domain, bytes); + } catch (Exception e) { + System.err.println("Could not instrument " + className); + e.printStackTrace(); + return bytes; + } + } /** - * Should LogTransformer be verbose in what it does? This currently list the - * names of the classes being processed. + * 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 */ - public Builder verbose(boolean b) { - verbose = b; - return this; - } + 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) { - String[] ignore = { "org/slf4j/", "ch/qos/logback/", "org/apache/log4j/" }; + loggerName = "_____log"; - public Builder ignore(String[] strings) { - this.ignore = strings; - return this; - } + // We have to declare the log variable. - private String level = "info"; + String pattern1 = "private static org.slf4j.Logger {};"; + String loggerDefinition = format(pattern1, loggerName).getMessage(); + CtField field = CtField.make(loggerDefinition, cl); - 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); + // 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 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); + return b; } - 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"; - } + /** + * 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 { - private boolean addEntryExit; - // private boolean addVariableAssignment; - private boolean verbose; - private String[] ignore; + String signature = JavassistHelper.getSignature(method); + String returnValue = JavassistHelper.returnValue(method); - public byte[] transform(ClassLoader loader, String className, Class clazz, - ProtectionDomain domain, byte[] bytes) { + 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); - 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 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); } - } - 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); - } - } } \ No newline at end of file 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 aab7b441..b20f5851 100644 --- a/slf4j-ext/src/main/java/org/slf4j/instrumentation/ToStringHelper.java +++ b/slf4j-ext/src/main/java/org/slf4j/instrumentation/ToStringHelper.java @@ -29,164 +29,163 @@ import java.util.WeakHashMap; public class ToStringHelper { - /** - * Prefix to use at the start of the representation. Always used. - */ - private static final String ARRAY_PREFIX = "["; + /** + * 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 = ']'; + /** + * 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. - */ + /** + * String separating each element when rendering an array. To be compatible + * with lists comma-space is used. + */ - private static final char[] ELEMENT_SEPARATOR = ", ".toCharArray(); + 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. - */ + /** + * 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>(); + 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 - */ + /** + * 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(); + 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()); + 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()); + 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()); - } + 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); + /** + * 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]); - } + 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; - } + } 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/profiler/DurationUnit.java b/slf4j-ext/src/main/java/org/slf4j/profiler/DurationUnit.java index 48385fbf..9205d3ed 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/DurationUnit.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/DurationUnit.java @@ -31,5 +31,5 @@ package org.slf4j.profiler; * */ public enum DurationUnit { - NANOSECOND, MICROSECOND, MILLISSECOND, SECOND; + NANOSECOND, MICROSECOND, MILLISSECOND, SECOND; } \ No newline at end of file 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 2014b8b2..56357373 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/Profiler.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/Profiler.java @@ -31,7 +31,6 @@ import org.slf4j.Logger; import org.slf4j.Marker; import org.slf4j.MarkerFactory; - // + Profiler [BAS] // |-- elapsed time [doX] 0 milliseconds. // |-- elapsed time [doYYYYY] 56 milliseconds. @@ -42,7 +41,6 @@ import org.slf4j.MarkerFactory; // |-- 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. @@ -51,226 +49,214 @@ import org.slf4j.MarkerFactory; */ public class Profiler implements TimeInstrument { - final static String PROFILER_MARKER_NAME = "PROFILER"; + 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 static int MIN_SW_NAME_LENGTH = 24; + final static int MIN_SW_ELAPSED_TIME_NUMBER_LENGTH = 9; - final String name; - final StopWatch globalStopWatch; + final String name; + final StopWatch globalStopWatch; - List childTimeInstrumentList = new ArrayList(); + List childTimeInstrumentList = new ArrayList(); - // optional field - ProfilerRegistry profilerRegistry; - // optional field - Logger logger; + // 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"); + public Profiler(String name) { + this.name = name; + this.globalStopWatch = new StopWatch(name); } - 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(); - } + public String getName() { + return name; } - if (totalElapsed < childTotal) { - throw new IllegalStateException( - "children have a higher accumulated elapsed time"); + + public ProfilerRegistry getProfilerRegistry() { + return profilerRegistry; } - } - 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."); + public void registerWith(ProfilerRegistry profilerRegistry) { + if (profilerRegistry == null) { + return; + } + this.profilerRegistry = profilerRegistry; + profilerRegistry.put(this); } - 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); + + public Logger getLogger() { + return logger; } - } - - /** - * 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 stopwath 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); - } + public void setLogger(Logger logger) { + this.logger = logger; } - buildStopWatchString(buf, du, label, indentation, globalStopWatch); - return buf.toString(); - } - private static void buildStopWatchString(StringBuilder buf, DurationUnit du, - String prefix, String indentation, StopWatch sw) { + /** + * 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); + } - 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); - } + 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 stopwath 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 b9fed680..61fda75e 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/ProfilerRegistry.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/ProfilerRegistry.java @@ -34,34 +34,32 @@ import java.util.Map; */ public class ProfilerRegistry { - private static final InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal(); + private static final InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal(); - - Map profilerMap = new HashMap(); + 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); + 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(); } - 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 7bf68371..e30486b3 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/SpacePadder.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/SpacePadder.java @@ -25,103 +25,103 @@ 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 + public static final String LINE_SEP = System.getProperty("line.separator"); - @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 String[] SPACES = { " ", " ", " ", " ", // 1,2,4,8 + // spaces + " ", // 16 spaces + " " }; // 32 spaces - 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; + @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); + } } - 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; + 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); + } } - for (int i = 4; i >= 0; i--) { - if ((length & (1 << i)) != 0) { - sbuf.append(SPACES[i]); - } + @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 c5cffed9..9ae7d295 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/StopWatch.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/StopWatch.java @@ -33,85 +33,84 @@ package org.slf4j.profiler; */ public class StopWatch implements TimeInstrument { - private String name; - private long startTime; - private long stopTime; - TimeInstrumentStatus status; + 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"); + public StopWatch(String name) { + start(name); } - return buf.toString(); - } - public final long elapsedTime() { - if (status == TimeInstrumentStatus.STARTED) { - return 0; - } else { - return stopTime - startTime; + StopWatch(StopWatch original) { + this.name = original.name; + this.startTime = original.startTime; + this.stopTime = original.stopTime; + this.status = original.status; } - } - public TimeInstrumentStatus getStatus() { - return 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"); + } - 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 0d0f5d5f..de749df8 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrument.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrument.java @@ -24,7 +24,6 @@ */ package org.slf4j.profiler; - /** * This interface sets the methods that must be implemented by * {@link Profiler} and {@link StopWatch} classes. It settles the @@ -35,45 +34,44 @@ package org.slf4j.profiler; */ public interface TimeInstrument { - /** - * All time instruments are named entities. - * @return the name of this instrument - */ - String getName(); - - - TimeInstrumentStatus getStatus(); - - /** - * Start tis time instrument. - * - * @param name - */ - void start(String name); - - /** - * Stop this time instrument. - * - * @return this - */ - TimeInstrument stop(); + /** + * All time instruments are named entities. + * @return the name of this instrument + */ + String getName(); - /** - * 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(); + TimeInstrumentStatus getStatus(); + + /** + * Start tis 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 5846d0c4..f7eb6f71 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrumentStatus.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/TimeInstrumentStatus.java @@ -23,7 +23,6 @@ * */ - /** * A StopWatch can be in two states: STARTED or STOPPED. */ @@ -37,5 +36,5 @@ package org.slf4j.profiler; * */ enum TimeInstrumentStatus { - STARTED, STOPPED; + STARTED, STOPPED; } \ No newline at end of file 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 0af82c4c..28e645c9 100644 --- a/slf4j-ext/src/main/java/org/slf4j/profiler/Util.java +++ b/slf4j-ext/src/main/java/org/slf4j/profiler/Util.java @@ -35,80 +35,80 @@ import java.text.DecimalFormat; */ 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 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 public double convertToMillis(long nanos) { - return (double) nanos / NANOS_IN_ONE_MILLISECOND; - } + static DurationUnit selectDurationUnitForDisplay(StopWatch sw) { + return selectDurationUnitForDisplay(sw.elapsedTime()); + } - 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; + 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; + } } - 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; + + 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/test/java/org/slf4j/NDCTest.java b/slf4j-ext/src/test/java/org/slf4j/NDCTest.java index 31902cad..33b02bb0 100644 --- a/slf4j-ext/src/test/java/org/slf4j/NDCTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/NDCTest.java @@ -28,31 +28,31 @@ import junit.framework.TestCase; public class NDCTest extends TestCase { - protected void setUp() throws Exception { - super.setUp(); - MDC.clear(); - } + protected void setUp() throws Exception { + super.setUp(); + MDC.clear(); + } - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testEmpty() { - assertEquals("", NDC.pop()); - } - - public void testSmoke() { - NDC.push("a"); - String result = NDC.pop(); - assertEquals("a",result); - } + protected void tearDown() throws Exception { + super.tearDown(); + } - public void testSmoke2() { - NDC.push("a"); - NDC.push("b"); - String result1 = NDC.pop(); - String result0 = NDC.pop(); - assertEquals("b",result1); - assertEquals("a",result0); - } + public void testEmpty() { + assertEquals("", NDC.pop()); + } + + public void testSmoke() { + NDC.push("a"); + String result = NDC.pop(); + assertEquals("a", result); + } + + 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 7d5aa5fe..9254ad70 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 @@ -38,43 +38,43 @@ import ch.qos.cal10n.MessageConveyor; public class LocLoggerTest extends TestCase { - ListAppender listAppender; - org.apache.log4j.Logger log4jRoot; + ListAppender listAppender; + org.apache.log4j.Logger log4jRoot; - IMessageConveyor imc = new MessageConveyor(Locale.UK); - LocLoggerFactory llFactory_uk = new LocLoggerFactory(imc); + IMessageConveyor imc = new MessageConveyor(Locale.UK); + LocLoggerFactory llFactory_uk = new LocLoggerFactory(imc); - final static String EXPECTED_FILE_NAME = "LocLoggerTest.java"; + final static String EXPECTED_FILE_NAME = "LocLoggerTest.java"; - public LocLoggerTest(String name) { - super(name); - } + public LocLoggerTest(String name) { + super(name); + } - public void setUp() throws Exception { - super.setUp(); + public void setUp() throws Exception { + super.setUp(); - // start from a clean slate for each test + // 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); - } + 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()); - } - - public void tearDown() throws Exception { - super.tearDown(); - } + void verify(LoggingEvent le, String expectedMsg) { + assertEquals(expectedMsg, le.getMessage()); + assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName()); + } - public void testSmoke() { - LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass()); - locLogger.info(Months.JAN); - verify((LoggingEvent) listAppender.list.get(0), "January"); - - } + public void tearDown() throws Exception { + super.tearDown(); + } + + 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 daa0aedf..51fb4237 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 @@ -31,5 +31,5 @@ import ch.qos.cal10n.LocaleData; @BaseName("months") @LocaleData(@Locale("en")) public enum Months { - JAN, FEB, MAR, APR, MAY, JUN; + 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 5f602f4a..375bc2d2 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 @@ -34,23 +34,22 @@ 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()); - + // create a message conveyor for a given locale + IMessageConveyor messageConveyor = new MessageConveyor(Locale.JAPAN); - public void applicationStart() { - locLogger.info(Production.APPLICATION_STARTED); - // .. - } - - public void applicationStop() { - locLogger.info(Production.APPLICATION_STOPPED); - // ... - } + // 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 2994cdc2..88413ba9 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 @@ -28,9 +28,9 @@ import junit.framework.*; public class PackageTest extends TestCase { - public static Test suite() { - TestSuite suite = new TestSuite(); - suite.addTestSuite(LocLoggerTest.class); - return suite; - } + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(LocLoggerTest.class); + return suite; + } } 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 957591e5..c0de6f13 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 @@ -29,10 +29,7 @@ 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; +@LocaleData({ @Locale("en_UK"), @Locale("fr") }) +public enum Production { + APPLICATION_STARTED, APPLICATION_STOPPED, DB_CONNECTION, DB_CONNECTION_FAILURE; } \ No newline at end of file diff --git a/slf4j-ext/src/test/java/org/slf4j/dummyExt/EventLoggerTest.java b/slf4j-ext/src/test/java/org/slf4j/dummyExt/EventLoggerTest.java index 43b09a2f..f04aecb6 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/EventLoggerTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/EventLoggerTest.java @@ -38,71 +38,69 @@ import org.slf4j.ext.EventLogger; public class EventLoggerTest extends TestCase { - ListAppender listAppender; - org.apache.log4j.Logger log4; + ListAppender listAppender; + org.apache.log4j.Logger log4; - final static String EXPECTED_FILE_NAME = "EventLoggerTest.java"; + final static String EXPECTED_FILE_NAME = "EventLoggerTest.java"; - public EventLoggerTest(String name) { - super(name); - } - - public void setUp() throws Exception { - super.setUp(); - - // 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()); - - } - - public void tearDown() throws Exception { - super.tearDown(); - MDC.clear(); - } - - void verify(LoggingEvent le, String expectedMsg) { - assertEquals(expectedMsg, le.getMessage()); - assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName()); - } - - - 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"); + public EventLoggerTest(String name) { + super(name); + } + + public void setUp() throws Exception { + super.setUp(); + + // 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()); + + } + + public void tearDown() throws Exception { + super.tearDown(); + MDC.clear(); + } + + void verify(LoggingEvent le, String expectedMsg) { + assertEquals(expectedMsg, le.getMessage()); + assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName()); + } + + 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 5be7b404..bb7f2f2b 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/ListAppender.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/ListAppender.java @@ -32,23 +32,22 @@ 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 List list = new ArrayList(); + + public boolean extractLocationInfo = false; + + protected void append(LoggingEvent event) { + list.add(event); + if (extractLocationInfo) { + event.getLocationInformation(); + } } - } - public void close() { - } + public void close() { + } - public boolean requiresLayout() { - return false; - } + 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 f1edca06..8544e7b3 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/MDCStrLookupTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/MDCStrLookupTest.java @@ -31,7 +31,6 @@ import org.slf4j.ext.MDCStrLookup; public class MDCStrLookupTest extends TestCase { - public MDCStrLookupTest(String name) { super(name); } 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 32994bc7..cee15d38 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/PackageTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/PackageTest.java @@ -28,11 +28,11 @@ import junit.framework.*; public class PackageTest extends TestCase { - public static Test suite() { - TestSuite suite = new TestSuite(); - suite.addTestSuite(MDCStrLookupTest.class); - suite.addTestSuite(XLoggerTest.class); - suite.addTestSuite(EventLoggerTest.class); - return suite; - } + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(MDCStrLookupTest.class); + suite.addTestSuite(XLoggerTest.class); + suite.addTestSuite(EventLoggerTest.class); + return suite; + } } 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 42a017f8..33940cfc 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/XLoggerTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/XLoggerTest.java @@ -33,125 +33,123 @@ import org.slf4j.ext.XLoggerFactory; public class XLoggerTest extends TestCase { - ListAppender listAppender; - org.apache.log4j.Logger log4jRoot; + ListAppender listAppender; + org.apache.log4j.Logger log4jRoot; - final static String EXPECTED_FILE_NAME = "XLoggerTest.java"; + final static String EXPECTED_FILE_NAME = "XLoggerTest.java"; - public XLoggerTest(String name) { - super(name); - } - - public void setUp() throws Exception { - super.setUp(); - - // 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); - } - - public void tearDown() throws Exception { - super.tearDown(); - } - - 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()); - } - - 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)"); - } - - 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)"); - } - - 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); - } - - 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://bugzilla.slf4j.org/show_bug.cgi?id=114 - public void testLocationExtraction_Bug114() { - XLogger logger = XLoggerFactory.getXLogger("UnitTest"); - int line = 137; // next line is line number 134 - 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()); + public XLoggerTest(String name) { + super(name); } - } + public void setUp() throws Exception { + super.setUp(); + + // 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); + } + + public void tearDown() throws Exception { + super.tearDown(); + } + + 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()); + } + + 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)"); + } + + 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)"); + } + + 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); + } + + 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://bugzilla.slf4j.org/show_bug.cgi?id=114 + 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/instrumentation/ToStringHelperTest.java b/slf4j-ext/src/test/java/org/slf4j/instrumentation/ToStringHelperTest.java index 0ada760a..c21b0b83 100644 --- a/slf4j-ext/src/test/java/org/slf4j/instrumentation/ToStringHelperTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/instrumentation/ToStringHelperTest.java @@ -28,51 +28,38 @@ import junit.framework.TestCase; public class ToStringHelperTest extends TestCase { - public void testRenderer() { - assertEquals("", "null", ToStringHelper.render(null)); - assertEquals("", "a", ToStringHelper.render("a")); - assertEquals("", "[]", ToStringHelper.render(new String[0])); + 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]", ToStringHelper.render(new String[] { "a" })); - assertEquals("", "[a, b]", ToStringHelper.render(new String[] { "a", - "b" })); + 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("", "[[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("", "[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]", ToStringHelper.render(new int[] { 1 })); - assertEquals("", "[1, 2, 3]", ToStringHelper - .render(new int[] { 1, 2, 3 })); + 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 long[] { 1, 2, 3 })); - assertEquals("", "[1, 2, 3]", ToStringHelper.render(new short[] { 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, 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 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("", "[[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 })); - } + 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 b4e25434..ad8f07e4 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/BasicProfilerDemo.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/BasicProfilerDemo.java @@ -52,36 +52,36 @@ package org.slf4j.profiler; */ public class BasicProfilerDemo { - public static void main(String[] args) { - // create a profiler called "BASIC" - Profiler profiler = new Profiler("BASIC"); - profiler.start("A"); - doA(); + 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("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) { + 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 84f510e9..a21e573b 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo.java @@ -24,8 +24,6 @@ */ package org.slf4j.profiler; - - /** * * This demo illustrates usage of SLF4J profilers. @@ -55,32 +53,32 @@ package org.slf4j.profiler; * @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(); - } + + 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 91dddb5c..678aa063 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java @@ -27,8 +27,6 @@ package org.slf4j.profiler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - - /** * * This demo illustrates usage of SLF4J profilers. It is almost identical to @@ -40,27 +38,27 @@ import org.slf4j.LoggerFactory; */ 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(); - } + 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 1c86121a..9a634625 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/PackageTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/PackageTest.java @@ -24,15 +24,14 @@ */ package org.slf4j.profiler; - import junit.framework.*; public class PackageTest extends TestCase { - public static Test suite() { - TestSuite suite = new TestSuite(); - suite.addTestSuite(UtilTest.class); - suite.addTestSuite(ProfilerTest.class); - return suite; - } + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(UtilTest.class); + suite.addTestSuite(ProfilerTest.class); + return suite; + } } \ No newline at end of file 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 f2a27210..2ea552be 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/ProfilerTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/ProfilerTest.java @@ -29,108 +29,110 @@ import junit.framework.TestCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class ProfilerTest extends TestCase { +public class ProfilerTest extends TestCase { - Logger logger = LoggerFactory.getLogger(ProfilerTest.class); + Logger logger = LoggerFactory.getLogger(ProfilerTest.class); - public void setUp() throws Exception { - super.setUp(); - } - 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()); - } - - 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. - 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); + public void setUp() throws Exception { + super.setUp(); } - 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 testSmoke() { + Profiler profiler = new Profiler("SMOKE"); + profiler.stop(); + StopWatch gSW = profiler.globalStopWatch; - 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) { + // verify + profiler.sanityCheck(); + assertEquals(TimeInstrumentStatus.STOPPED, gSW.status); + assertEquals(0, profiler.childTimeInstrumentList.size()); + assertNull(profiler.getLastTimeInstrument()); + } + + 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. + 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 9d8b358b..b6607470 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/RandomIntegerArrayGenerator.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/RandomIntegerArrayGenerator.java @@ -27,14 +27,14 @@ 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; + 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; } - 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 1505f9f4..867bb60f 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/SortAndPruneComposites.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/SortAndPruneComposites.java @@ -29,68 +29,68 @@ 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); + static String NESTED_PROFILER_NAME = "SORT_AND_PRUNE"; - // 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; - } + final int[] originalArray; + final int originalArrrayLength; - 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 SortAndPruneComposites(int[] randomArray) { + this.originalArray = randomArray; + this.originalArrrayLength = randomArray.length; - public boolean isPrime(int n) { - if(n < 2) { - return false; } - if(n%2 == 0) { - return false; + + 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; } - for(int i = 3; i*i <=n; i += 2) { - if(n%i ==0) { - return false; - } + + 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; } - 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 713bcb35..601d6fb0 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/UtilTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/UtilTest.java @@ -28,25 +28,25 @@ import junit.framework.TestCase; public class UtilTest extends TestCase { - public UtilTest(String name) { - super(name); - } + public UtilTest(String name) { + super(name); + } - protected void setUp() throws Exception { - super.setUp(); - } + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + 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)); + } - protected void tearDown() throws Exception { - super.tearDown(); - } - - 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-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java b/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java index 8df9d80f..ad075208 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java @@ -40,498 +40,492 @@ import org.slf4j.helpers.MessageFormatter; */ 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; - } + private static final long serialVersionUID = 4141593417490482209L; + final Log log; - /** - * 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()); + // 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#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#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. - * - *

- * 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)} 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, 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#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#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#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#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#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#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#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#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#isDebugEnabled} method of the underlying + * {@link Log} instance. + */ + public boolean isDebugEnabled() { + return log.isDebugEnabled(); } - } - /** - * 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#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#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#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#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#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#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#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#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#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#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#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); } - } - - - /** - * 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 66625ff8..77ea88ec 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerFactory.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerFactory.java @@ -40,45 +40,44 @@ import org.slf4j.helpers.Util; */ public class JCLLoggerFactory implements ILoggerFactory { - private static final String JCL_DELEGATION_LOOP_URL = "http://www.slf4j.org/codes.html#jclDelegationLoop"; + 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 slf4j-jcl.jar on the class path, preempting StackOverflowError. "; - String part2 = "See also " + JCL_DELEGATION_LOOP_URL - + " for more details."; + // check for delegation loops + static { + try { + Class.forName("org.apache.commons.logging.impl.SLF4JLogFactory"); + String part1 = "Detected both jcl-over-slf4j.jar AND 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 + 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; - ConcurrentMap loggerMap; + // key: name (String), value: a JCLLoggerAdapter; + 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; + 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 6705d550..580770db 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -36,48 +36,47 @@ import org.slf4j.spi.LoggerFactoryBinder; */ public class StaticLoggerBinder implements LoggerFactoryBinder { - /** - * The unique instance of this class. - */ - private static final StaticLoggerBinder SINGLETON = new 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; - } - - /** - * Version tag used to check compatibility. The value of this field is - * modified with each release. - */ - - //to avoid constant folding by the compiler, this field must *not* be final - public static String REQUESTED_API_VERSION = "1.6.99"; - - // Binding specific code: - private static final String loggerFactoryClassStr = JCLLoggerFactory.class - .getName(); + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } - /** - * The ILoggerFactory instance returned by the {@link #getLoggerFactory} - * method should always be the same object - */ - private final ILoggerFactory loggerFactory; + /** + * Version tag used to check compatibility. The value of this field is + * modified with each release. + */ + + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; - private StaticLoggerBinder() { // Binding specific code: - loggerFactory = new JCLLoggerFactory(); - } + private static final String loggerFactoryClassStr = JCLLoggerFactory.class.getName(); - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } + /** + * The ILoggerFactory instance returned by the {@link #getLoggerFactory} + * method should always be the same object + */ + private final ILoggerFactory loggerFactory; - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } + 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 4972927d..b35b89b0 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -27,7 +27,6 @@ package org.slf4j.impl; import org.slf4j.helpers.NOPMDCAdapter; import org.slf4j.spi.MDCAdapter; - /** * This implementation is bound to {@link NOPMDCAdapter}. * @@ -35,26 +34,25 @@ import org.slf4j.spi.MDCAdapter; */ public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - private StaticMDCBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link NOPMDCAdapter}. - * - * @return instance of NOPMDCAdapter - */ - public MDCAdapter getMDCA() { - return new NOPMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return NOPMDCAdapter.class.getName(); - } + private StaticMDCBinder() { + } + + /** + * Currently this method always returns an instance of + * {@link NOPMDCAdapter}. + * + * @return instance of NOPMDCAdapter + */ + 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 02817079..1d255230 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -38,31 +38,30 @@ import org.slf4j.spi.MarkerFactoryBinder; */ 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() { - } - - /** - * 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(); - } - - + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * 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/test/java/org/slf4j/InvocationTest.java b/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java index aa55978a..a7035153 100644 --- a/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java @@ -28,7 +28,6 @@ import java.util.logging.Level; import junit.framework.TestCase; - /** * Test whether invoking the SLF4J API causes problems or not. * @@ -37,93 +36,90 @@ import junit.framework.TestCase; */ public class InvocationTest extends TestCase { - Level oldLevel; - java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); - - - public InvocationTest (String arg0) { - super(arg0); - } + Level oldLevel; + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); - protected void setUp() throws Exception { - super.setUp(); - oldLevel = root.getLevel(); - root.setLevel(Level.OFF); - } + public InvocationTest(String arg0) { + super(arg0); + } - protected void tearDown() throws Exception { - super.tearDown(); - root.setLevel(oldLevel); - } - - public void test1() { - Logger logger = LoggerFactory.getLogger("test1"); - logger.debug("Hello world."); - } - - 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); - } - - 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); - } - - 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"); + protected void setUp() throws Exception { + super.setUp(); + oldLevel = root.getLevel(); + root.setLevel(Level.OFF); + } - 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"); - } - - public void testMDC() { - MDC.put("k", "v"); - assertNull(MDC.get("k")); - MDC.remove("k"); - assertNull(MDC.get("k")); - MDC.clear(); - } + protected void tearDown() throws Exception { + super.tearDown(); + root.setLevel(oldLevel); + } + + public void test1() { + Logger logger = LoggerFactory.getLogger("test1"); + logger.debug("Hello world."); + } + + 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); + } + + 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); + } + + 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"); + } + + 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/src/main/java/org/slf4j/impl/JDK14LoggerAdapter.java b/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerAdapter.java index 7b5ee092..2de8e3e5 100755 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerAdapter.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerAdapter.java @@ -43,612 +43,609 @@ import org.slf4j.spi.LocationAwareLogger; * @author Ceki Gülcü * @author Peter Royal */ -public final class JDK14LoggerAdapter extends MarkerIgnoringBase implements - LocationAwareLogger { +public final class JDK14LoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger { - private static final long serialVersionUID = -8053026990503422791L; + private static final long serialVersionUID = -8053026990503422791L; - transient final java.util.logging.Logger logger; + 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); - 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; - } + // 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(); } - 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; - } + /** + * 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); } - 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()); + /** + * 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); + } } - } - public void log(Marker marker, String callerFQCN, int level, String message, - Object[] argArray, Throwable t) { - Level julLevel; - switch (level) { - 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 " + level - + " is not recognized."); + /** + * 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()); + } } - // 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://bugzilla.slf4j.org/show_bug.cgi?id=90 - if (logger.isLoggable(julLevel)) { - log(callerFQCN, julLevel, message, t); + + /** + * 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); + 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; + switch (level) { + 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 " + level + " is not recognized."); + } + // 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://bugzilla.slf4j.org/show_bug.cgi?id=90 + if (logger.isLoggable(julLevel)) { + log(callerFQCN, julLevel, message, t); + } } - } } 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 7dabe742..f251d987 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerFactory.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerFactory.java @@ -38,33 +38,32 @@ import java.util.concurrent.ConcurrentMap; */ public class JDK14LoggerFactory implements ILoggerFactory { - // key: name (String), value: a JDK14LoggerAdapter; - ConcurrentMap loggerMap; + // key: name (String), value: a JDK14LoggerAdapter; + ConcurrentMap loggerMap; - public JDK14LoggerFactory() { - loggerMap =new ConcurrentHashMap(); - } - - /* - * (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 = ""; + public JDK14LoggerFactory() { + loggerMap = new ConcurrentHashMap(); } - 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; + /* + * (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 ecc7b26c..e532be61 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -36,47 +36,45 @@ import org.slf4j.spi.LoggerFactoryBinder; */ 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; - } + /** + * The unique instance of this class. + * + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Declare the version of the SLF4J API this implementation is compiled against. - * The value of this field is usually modified with each release. - */ - // to avoid constant folding by the compiler, this field must *not* be final - public static String REQUESTED_API_VERSION = "1.6.99"; // !final + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } - - private static final String loggerFactoryClassStr = org.slf4j.impl.JDK14LoggerFactory.class.getName(); + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is usually modified with each release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; // !final - /** 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; - } + 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 de3b2a4d..bff523db 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -27,7 +27,6 @@ package org.slf4j.impl; import org.slf4j.helpers.BasicMDCAdapter; import org.slf4j.spi.MDCAdapter; - /** * This implementation is bound to {@link BasicMDCAdapter}. * @@ -35,26 +34,25 @@ import org.slf4j.spi.MDCAdapter; */ public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - private StaticMDCBinder() { - } - - /** - * 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(); - } + private StaticMDCBinder() { + } + + /** + * 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 02817079..1d255230 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -38,31 +38,30 @@ import org.slf4j.spi.MarkerFactoryBinder; */ 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() { - } - - /** - * 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(); - } - - + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * 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/test/java/org/slf4j/InvocationTest.java b/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java index cc348866..da76fab3 100755 --- a/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java @@ -40,7 +40,6 @@ import static junit.framework.Assert.assertNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; - /** * Test whether invoking the SLF4J API causes problems or not. * @@ -48,162 +47,157 @@ import static org.junit.Assert.fail; */ public class InvocationTest { - Level oldLevel; - java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); + Level oldLevel; + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); - ListHandler listHandler = new ListHandler(); + 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); + @Before + public void setUp() throws Exception { + oldLevel = root.getLevel(); + root.setLevel(Level.FINE); + // removeAllHandlers(root); + root.addHandler(listHandler); } - @Override - public void flush() { + @After + public void tearDown() throws Exception { + root.setLevel(oldLevel); + removeListHandlers(root); } - @Override - public void close() throws SecurityException { + @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/impl/JDK14AdapterLoggerNameTest.java b/slf4j-jdk14/src/test/java/org/slf4j/impl/JDK14AdapterLoggerNameTest.java index 840e160c..e3cbbd25 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/impl/JDK14AdapterLoggerNameTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/impl/JDK14AdapterLoggerNameTest.java @@ -31,59 +31,59 @@ import java.util.logging.Logger; import junit.framework.TestCase; public class JDK14AdapterLoggerNameTest extends TestCase { - private MockHandler mockHandler; + private MockHandler mockHandler; - protected void setUp() throws Exception { - super.setUp(); - Logger logger = Logger.getLogger("TEST"); - mockHandler = new MockHandler(); - removeHandlers(logger); - logger.addHandler(mockHandler); - } - - protected void tearDown() throws Exception { - removeHandlers(Logger.getLogger("TEST")); - super.tearDown(); - } - - public void testLoggerNameusingJdkLogging() throws Exception { - Logger.getLogger("TEST").info("test message"); - assertCorrectLoggerName(); - - } - - public void testLoggerNameUsingSlf4j() throws Exception { - JDK14LoggerFactory factory = new JDK14LoggerFactory(); - org.slf4j.Logger logger = factory.getLogger("TEST"); - logger.info("test message"); - assertCorrectLoggerName(); - } - - 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 { + protected void setUp() throws Exception { + super.setUp(); + Logger logger = Logger.getLogger("TEST"); + mockHandler = new MockHandler(); + removeHandlers(logger); + logger.addHandler(mockHandler); } - public void flush() { + protected void tearDown() throws Exception { + removeHandlers(Logger.getLogger("TEST")); + super.tearDown(); } - public void publish(LogRecord record) { - this.record = record; + public void testLoggerNameusingJdkLogging() throws Exception { + Logger.getLogger("TEST").info("test message"); + assertCorrectLoggerName(); + } - } + public void testLoggerNameUsingSlf4j() throws Exception { + JDK14LoggerFactory factory = new JDK14LoggerFactory(); + org.slf4j.Logger logger = factory.getLogger("TEST"); + logger.info("test message"); + assertCorrectLoggerName(); + } + + 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; + } + + } } \ No newline at end of file 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 ba4ffdd4..3b77ab96 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/impl/PerfTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/impl/PerfTest.java @@ -32,45 +32,45 @@ import org.slf4j.helpers.BogoPerf; public class PerfTest extends TestCase { - static long REFERENCE_BIPS = 9000; + static long REFERENCE_BIPS = 9000; - public PerfTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testBug72() { - - 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"); + public PerfTest(String name) { + super(name); } - long end = System.currentTimeMillis(); + protected void setUp() throws Exception { + super.setUp(); + } - long duration = end - start; - return duration; - } + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testBug72() { + + 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 c3dcc776..bb9b8745 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/issue/LoggerSerializationTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/issue/LoggerSerializationTest.java @@ -24,7 +24,6 @@ */ package org.slf4j.issue; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -45,41 +44,40 @@ import org.slf4j.LoggerFactory; */ public class LoggerSerializationTest extends TestCase { - static class LoggerHolder implements Serializable { - private static final long serialVersionUID = 1L; + static class LoggerHolder implements Serializable { + private static final long serialVersionUID = 1L; - private Logger log = LoggerFactory.getLogger(LoggerHolder.class); + private Logger log = LoggerFactory.getLogger(LoggerHolder.class); - public String toString() { - return "log=" + getLog(); - } + public String toString() { + return "log=" + getLog(); + } - public Logger getLog() { - return log; - } - } + public Logger getLog() { + return log; + } + } - public void testCanLoggerBeSerialized() throws IOException, - ClassNotFoundException { + public void testCanLoggerBeSerialized() throws IOException, ClassNotFoundException { - LoggerHolder lh1 = new LoggerHolder(); + LoggerHolder lh1 = new LoggerHolder(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream out = new ObjectOutputStream(baos); - out.writeObject(lh1); - out.close(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(baos); + out.writeObject(lh1); + out.close(); - lh1 = null; + lh1 = null; - byte[] serializedLoggerHolder = baos.toByteArray(); + byte[] serializedLoggerHolder = baos.toByteArray(); - InputStream is = new ByteArrayInputStream(serializedLoggerHolder); - ObjectInputStream in = new ObjectInputStream(is); - LoggerHolder lh2 = (LoggerHolder) in.readObject(); + InputStream is = new ByteArrayInputStream(serializedLoggerHolder); + ObjectInputStream in = new ObjectInputStream(is); + LoggerHolder lh2 = (LoggerHolder) in.readObject(); - Assert.assertNotNull(lh2); - Assert.assertNotNull(lh2.getLog()); - lh2.getLog().info("You must see this message as a log message"); - } + Assert.assertNotNull(lh2); + Assert.assertNotNull(lh2.getLog()); + lh2.getLog().info("You must see this message as a log message"); + } } diff --git a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerAdapter.java b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerAdapter.java index 6a5c97a4..08d3ea0e 100755 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerAdapter.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerAdapter.java @@ -52,553 +52,547 @@ import org.slf4j.spi.LocationAwareLogger; * * @author Ceki Gülcü */ -public final class Log4jLoggerAdapter extends MarkerIgnoringBase implements - LocationAwareLogger, Serializable { +public final class Log4jLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger, Serializable { - private static final long serialVersionUID = 6182834493563598289L; + private static final long serialVersionUID = 6182834493563598289L; - final transient org.apache.log4j.Logger logger; + 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(); + /** + * 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; + // 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; + // 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(); } - } - /** - * 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(); + private boolean isTraceCapable() { + try { + logger.isTraceEnabled(); + return true; + } catch (NoSuchMethodError e) { + return false; + } } - } - /** - * 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()); + /** + * 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 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 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 - * 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 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 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 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 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 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 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 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); } - } - /** - * 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()); + /** + * 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 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 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 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 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 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 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 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 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 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 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); } - } - /** - * 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()); + /** + * 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 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 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 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 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 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; - 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."); + /** + * 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; + 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."); + } + logger.log(callerFQCN, log4jLevel, msg, t); } - logger.log(callerFQCN, log4jLevel, msg, t); - } } 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 1898b95e..e801f9cc 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerFactory.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerFactory.java @@ -39,33 +39,32 @@ import org.slf4j.Logger; */ public class Log4jLoggerFactory implements ILoggerFactory { - // key: name (String), value: a Log4jLoggerAdapter; - ConcurrentMap loggerMap; + // key: name (String), value: a Log4jLoggerAdapter; + ConcurrentMap loggerMap; - - public Log4jLoggerFactory() { - 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.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; + public Log4jLoggerFactory() { + 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.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 47ddf372..95b8ed02 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jMDCAdapter.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jMDCAdapter.java @@ -32,60 +32,60 @@ import org.slf4j.spi.MDCAdapter; public class Log4jMDCAdapter implements MDCAdapter { - public void clear() { - @SuppressWarnings("rawtypes") - Map map = org.apache.log4j.MDC.getContext(); - if (map != null) { - map.clear(); + 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; + public String get(String key) { + return (String) org.apache.log4j.MDC.get(key); } - } - @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); + /** + * 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 3f467a18..081f28a6 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -38,52 +38,51 @@ import org.slf4j.spi.LoggerFactoryBinder; */ public class StaticLoggerBinder implements LoggerFactoryBinder { - /** - * The unique instance of this class. - * - */ - private static final StaticLoggerBinder SINGLETON = new 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 usually modified with each 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"); + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; } - } - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } + /** + * Declare the version of the SLF4J API this implementation is compiled + * against. The value of this field is usually modified with each release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; // !final - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } + 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 74f28da4..77742309 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -26,7 +26,6 @@ package org.slf4j.impl; import org.slf4j.spi.MDCAdapter; - /** * This implementation is bound to {@link Log4jMDCAdapter}. * @@ -34,24 +33,23 @@ import org.slf4j.spi.MDCAdapter; */ public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - private StaticMDCBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link StaticMDCBinder}. - */ - public MDCAdapter getMDCA() { - return new Log4jMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return Log4jMDCAdapter.class.getName(); - } + private StaticMDCBinder() { + } + + /** + * 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 02817079..1d255230 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -38,31 +38,30 @@ import org.slf4j.spi.MarkerFactoryBinder; */ 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() { - } - - /** - * 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(); - } - - + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * 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/test/java/org/slf4j/InvocationTest.java b/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java index ddd4d2bf..b3246f50 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java @@ -39,136 +39,137 @@ import junit.framework.TestCase; */ public class InvocationTest extends TestCase { - ListAppender listAppender = new ListAppender(); - org.apache.log4j.Logger root; - public InvocationTest(String arg0) { - super(arg0); - } + ListAppender listAppender = new ListAppender(); + org.apache.log4j.Logger root; - protected void setUp() throws Exception { - super.setUp(); - root = org.apache.log4j.Logger.getRootLogger(); - root.addAppender(listAppender); - - } - - protected void tearDown() throws Exception { - super.tearDown(); - root.getLoggerRepository().resetConfiguration(); - } - - public void test1() { - Logger logger = LoggerFactory.getLogger("test1"); - logger.debug("Hello world."); - assertEquals(1, listAppender.list.size()); - } - - 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.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 {}", new Integer(3)); - logger.error("Hello world 4.", e); - assertEquals(11, listAppender.list.size()); - } - - 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://bugzilla.slf4j.org/show_bug.cgi?id=78 - public void testNullParameter_BUG78() { - Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78"); - String[] parameters = null; - String msg = "hello {}"; - - logger.debug(msg, parameters); - assertEquals(1, listAppender.list.size()); - LoggingEvent e = (LoggingEvent) listAppender.list.get(0); - assertEquals(msg, e.getMessage()); - } - - 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()); - } - - 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) { + public InvocationTest(String arg0) { + super(arg0); } - } - - 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")); - } - + + protected void setUp() throws Exception { + super.setUp(); + root = org.apache.log4j.Logger.getRootLogger(); + root.addAppender(listAppender); + + } + + protected void tearDown() throws Exception { + super.tearDown(); + root.getLoggerRepository().resetConfiguration(); + } + + public void test1() { + Logger logger = LoggerFactory.getLogger("test1"); + logger.debug("Hello world."); + assertEquals(1, listAppender.list.size()); + } + + 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.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 {}", new Integer(3)); + logger.error("Hello world 4.", e); + assertEquals(11, listAppender.list.size()); + } + + 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://bugzilla.slf4j.org/show_bug.cgi?id=78 + public void testNullParameter_BUG78() { + Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78"); + String[] parameters = null; + String msg = "hello {}"; + + logger.debug(msg, parameters); + assertEquals(1, listAppender.list.size()); + LoggingEvent e = (LoggingEvent) listAppender.list.get(0); + assertEquals(msg, e.getMessage()); + } + + 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()); + } + + 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) { + } + } + + 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 ed1c4dfe..29596899 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/ListAppender.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/ListAppender.java @@ -32,22 +32,22 @@ 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 List list = new ArrayList(); + + public boolean extractLocationInfo = false; + + protected void append(LoggingEvent event) { + list.add(event); + if (extractLocationInfo) { + event.getLocationInformation(); + } } - } - public void close() { - } + public void close() { + } - public boolean requiresLayout() { - return false; - } + public boolean requiresLayout() { + return false; + } } 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 53efe0ef..0dc34b01 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveAppender.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveAppender.java @@ -33,22 +33,22 @@ import org.slf4j.LoggerFactory; public class RecursiveAppender extends AppenderSkeleton { - int diff = new Random().nextInt(); - - public RecursiveAppender() { - System.out.println("in RecursiveAppender constructor"); - Logger logger = LoggerFactory.getLogger("RecursiveAppender"+diff); - System.out.println("logger class="+logger.getClass().getName()); - logger.info("Calling a logger in the constructor"); - } - - protected void append(LoggingEvent arg0) { - } + int diff = new Random().nextInt(); - public void close() { - } + public RecursiveAppender() { + System.out.println("in RecursiveAppender constructor"); + Logger logger = LoggerFactory.getLogger("RecursiveAppender" + diff); + System.out.println("logger class=" + logger.getClass().getName()); + logger.info("Calling a logger in the constructor"); + } - public boolean requiresLayout() { - return false; - } + protected void append(LoggingEvent arg0) { + } + + public void close() { + } + + public boolean requiresLayout() { + return false; + } } diff --git a/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java b/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java index 3ac64de5..23a24437 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java @@ -33,25 +33,25 @@ import org.slf4j.LoggerFactory; public class RecursiveInitializationTest extends TestCase { - // value of LogManager.DEFAULT_CONFIGURATION_KEY; - static String CONFIG_FILE_KEY = "log4j.configuration"; + // value of LogManager.DEFAULT_CONFIGURATION_KEY; + static String CONFIG_FILE_KEY = "log4j.configuration"; - int diff = new Random().nextInt(10000); - - protected void setUp() throws Exception { - System.setProperty(CONFIG_FILE_KEY, "recursiveInit.properties"); - super.setUp(); - } + int diff = new Random().nextInt(10000); - protected void tearDown() throws Exception { - System.clearProperty(CONFIG_FILE_KEY); - super.tearDown(); - } + protected void setUp() throws Exception { + System.setProperty(CONFIG_FILE_KEY, "recursiveInit.properties"); + super.setUp(); + } - public void testLog4j() { - Logger logger = LoggerFactory.getLogger("x"+diff); - System.out.println("logger class="+logger.getClass().getName()); - logger.info("hello"); - } + protected void tearDown() throws Exception { + System.clearProperty(CONFIG_FILE_KEY); + super.tearDown(); + } + + public void testLog4j() { + Logger logger = LoggerFactory.getLogger("x" + diff); + System.out.println("logger class=" + logger.getClass().getName()); + logger.info("hello"); + } } 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 d236fbc7..120fa941 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/Constant.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/Constant.java @@ -26,11 +26,11 @@ 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 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; + public final static int NB_FILES_MAX = 1; } \ No newline at end of file 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 65bdeefd..add4438d 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/ConversionException.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/ConversionException.java @@ -26,38 +26,38 @@ package org.slf4j.migrator; public class ConversionException extends Exception { - /** - * - */ - private static final long serialVersionUID = 498961799888576668L; + /** + * + */ + private static final long serialVersionUID = 498961799888576668L; - private String detail; + 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 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()); + 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 b1627317..71af29bd 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/FileSelector.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/FileSelector.java @@ -32,38 +32,38 @@ import org.slf4j.migrator.internal.ProgressListener; public class FileSelector { - private List javaFileList = new ArrayList(); + private List javaFileList = new ArrayList(); - ProgressListener pl; + 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"); + FileSelector(ProgressListener pl) { + this.pl = pl; } - } - 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]); + 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); + } + } - } - } 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 a0301e36..d4bf3e63 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java @@ -41,71 +41,70 @@ 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; - } + final static int BUFFER_LEN = 8 * 1024; + final LineConverter lineConverter; + final String lineTerminator; + final ProgressListener 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); + InplaceFileConverter(RuleSet ruleSet, ProgressListener pl) { + this.lineConverter = new LineConverter(ruleSet); + lineTerminator = System.getProperty("line.separator"); + this.pl = pl; } - 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 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(); } - } - 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; - } + 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+"]"); + } } - 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()); + 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 ce70262a..5a94a41d 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/Main.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/Main.java @@ -36,15 +36,15 @@ import org.slf4j.migrator.internal.MigratorFrame; */ 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); - } - }); - } - + 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 a0ddead3..99f1a194 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/ProjectConverter.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/ProjectConverter.java @@ -38,90 +38,89 @@ import org.slf4j.migrator.line.RuleSet; public class ProjectConverter { - private RuleSet ruleSet; - private List exception; + private RuleSet ruleSet; + private List exception; - ProgressListener progressListener; + 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 static void main(String[] args) throws IOException { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + MigratorFrame inst = new MigratorFrame(); + inst.setLocationRelativeTo(null); + inst.setVisible(true); + } + }); } - } - 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); + /** + * 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)); + } } - } - /** - * 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 convertProject(File folder) { + FileSelector fs = new FileSelector(progressListener); + List fileList = fs.selectJavaFilesInFolder(folder); + scanFileList(fileList); + progressListener.onDone(); } - } - public void addException(ConversionException exc) { - if (exception == null) { - exception = new ArrayList(); + /** + * 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); + } } - 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; + /** + * 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; + } } - } } \ No newline at end of file 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 da84ea19..a48038a6 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/RuleSetFactory.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/RuleSetFactory.java @@ -39,24 +39,24 @@ import org.slf4j.migrator.line.RuleSet; */ 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; + /** + * 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 c2a07ce0..f2f9b35d 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 @@ -25,66 +25,65 @@ package org.slf4j.migrator.helper; public class Abbreviator { - static final String FILLER = "..."; + static final String FILLER = "..."; - final char folderSeparator; - final int invariantPrefixLength; - final int desiredLength; + 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.substring(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; - } + public Abbreviator(int invariantPrefixLength, int desiredLength, char folderSeparator) { + this.invariantPrefixLength = invariantPrefixLength; + this.desiredLength = desiredLength; + this.folderSeparator = folderSeparator; } - } - 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; + public String abbreviate(String filename) { + if (filename.length() <= desiredLength) { + return filename; } else { - return nextIndex; + + 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.substring(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; + } } - } else { - hitCount++; - nextIndex = tmpIndex; - } } - return nextIndex; - } + + 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 1ba986c4..c438a98a 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 @@ -29,38 +29,33 @@ 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); - } + 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); + } - 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 70b2b48a..a6590ab2 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 @@ -30,28 +30,27 @@ 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; - } + final File folder; + final MigratorFrame frame; + final int conversionType; - public void run() { - ProgressListener pl = new ProgressListenerImpl(folder, frame); - pl.onMigrationBegin(); - ProjectConverter converter = new ProjectConverter(conversionType, pl); - converter.convertProject(folder); - } + ConversionTask(File folder, MigratorFrame frame, int conversionType) { + this.folder = folder; + this.frame = frame; + this.conversionType = conversionType; + } - public void launch() { - Thread t = new Thread(this); - t.setDaemon(true); - t.start(); - } + 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 a03a91f0..377ac6e5 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 @@ -57,339 +57,317 @@ import org.slf4j.migrator.helper.SpringLayoutHelper; * ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class MigratorFrame extends JFrame implements ActionListener { - private static final long serialVersionUID = 1L; + 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"; + 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; + 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 SpringLayout layoutManager = new SpringLayout(); + private SpringLayoutHelper slh = new SpringLayoutHelper(layoutManager, BASIC_PADDING); - private JLabel migrationLabel; + private JLabel migrationLabel; - private JRadioButton radioLog4j; - private JRadioButton radioJCL; - private JRadioButton radioJUL; - private ButtonGroup buttonGroup; + 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 JTextField folderTextField; + private JLabel warningLabel; + JButton migrateButton; + private JButton browseButton; + private JLabel folderLabel; - private JCheckBox awareCheckBox; - private JLabel awareLabel; + private JCheckBox awareCheckBox; + private JLabel awareLabel; - JLabel otherLabel; - JProgressBar progressBar; - private JFileChooser fileChooser; + 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(); + public MigratorFrame() { + super(); + initGUI(); } - } - private void createComponents() { - createMigrationLabel(); - createRadioJCL(); - createRadioLog4j(); - createRadioJUL(); - createButtonGroup(); - createFolderLabel(); - createFolderTextField(); - createBrowseButton(); - createMigrateButton(); - createAwareCheckbox(); - createAwareLabel(); - createWarningLabel(); - createFileChooser(); + private void initGUI() { + try { + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + getContentPane().setLayout(layoutManager); + this.setTitle("SLF4J migrator"); - 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."); + createComponents(); + constrainAll(); + addAllComponentsToContextPane(); + pack(); + this.setSize(700, 400); + } catch (Exception e) { + e.printStackTrace(); } - 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(); + private void createComponents() { + createMigrationLabel(); + createRadioJCL(); + createRadioLog4j(); + createRadioJUL(); + createButtonGroup(); + createFolderLabel(); + createFolderTextField(); + createBrowseButton(); + createMigrateButton(); + createAwareCheckbox(); + createAwareLabel(); + createWarningLabel(); + createFileChooser(); + + otherLabel = new JLabel(); + otherLabel.setText(""); + createProgressBar(); - 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; - } + /** + * + */ + private void constrainAll() { - 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(""); + // contrain migration label + layoutManager.putConstraint(SpringLayout.WEST, migrationLabel, BASIC_PADDING, SpringLayout.EAST, this); - JOptionPane.showMessageDialog(this, buf.toString(), "", - JOptionPane.ERROR_MESSAGE); - } + layoutManager.putConstraint(SpringLayout.NORTH, migrationLabel, BASIC_PADDING, SpringLayout.NORTH, this); - boolean isDirectory(String filename) { - if (filename == null) { - return false; + 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); } - File file = new File(filename); - if (file.exists() && file.isDirectory()) { - return true; - } else { - return false; + + 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 7df6d6d6..a9b8edc5 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 @@ -28,13 +28,18 @@ 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(); + 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 38286985..8187e7e0 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 @@ -31,96 +31,91 @@ 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; + static final int TARGET_FILE_LENGTH = 85; + static final int UPDATE_THRESHOLD = 100; - Abbreviator abbr; - - long lastUpdate = 0; - - + int addFileCount = 0; + int scanFileCount = 0; + int inplaceConversionCount = 0; + final MigratorFrame frame; - public ProgressListenerImpl(File projectFolder, MigratorFrame frame) { - this.frame = frame; - this.abbr = new Abbreviator((int) projectFolder.length(), - TARGET_FILE_LENGTH, File.separatorChar); - } + Abbreviator abbr; - public void onMigrationBegin() { - frame.disableInput(); - } + long lastUpdate = 0; - boolean isTooSoon() { - long now = System.currentTimeMillis(); - if(now-lastUpdate < UPDATE_THRESHOLD) { - return true; - } else { - lastUpdate = now; - return false; + public ProgressListenerImpl(File projectFolder, MigratorFrame frame) { + this.frame = frame; + this.abbr = new Abbreviator((int) projectFolder.length(), TARGET_FILE_LENGTH, File.separatorChar); } - } - - 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 onMigrationBegin() { + frame.disableInput(); } - } - public void onFileScanBegin() { - frame.progressBar.setMaximum(addFileCount); - frame.progressBar.setValue(0); - frame.progressBar.setVisible(true); - } + 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 548692f3..83306596 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 @@ -29,23 +29,23 @@ import java.util.regex.Pattern; public interface ConversionRule { - public Pattern getPattern(); + 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(); + /** + * 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(); } \ No newline at end of file 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 b2e86921..a0393265 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 @@ -30,10 +30,10 @@ import java.util.List; public class EmptyRuleSet implements RuleSet { - List list = new ArrayList(); - - public Iterator iterator() { - return list.iterator(); - } - + 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 4234d9c9..f463e46d 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 @@ -28,7 +28,6 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.regex.Pattern; - /** * This class represents JCL to SLF4J conversion rules * @@ -37,44 +36,34 @@ import java.util.regex.Pattern; */ 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;"); + private ArrayList conversionRuleList; - // 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("); + 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;"); - SingleConversionRule cr5 = new SingleConversionRule(Pattern - .compile("LogFactory.getLog\\("),"LoggerFactory.getLogger("); - + // matching : import org.apache.commons.logging.Log; + SingleConversionRule cr1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.commons.logging.Log;"), "import org.slf4j.Logger;"); - conversionRuleList = new ArrayList(); - conversionRuleList.add(cr0); - conversionRuleList.add(cr1); - conversionRuleList.add(cr2); - conversionRuleList.add(cr3); - conversionRuleList.add(cr4); - conversionRuleList.add(cr5); - } + SingleConversionRule cr2 = new SingleConversionRule(Pattern.compile("(\\sLog\\b)"), " Logger"); + SingleConversionRule cr3 = new SingleConversionRule(Pattern.compile("(^Log\\b)"), "Logger"); - public Iterator iterator() { - return conversionRuleList.iterator(); - } + 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 1144e0cc..b296b70a 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 @@ -36,50 +36,37 @@ import java.util.regex.Pattern; */ 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;"); + private ArrayList conversionRuleList; - SingleConversionRule crImport2 = new SingleConversionRule(Pattern - .compile("import\\s*+java.util.logging.*;"), - "import org.slf4j.Logger;", - "import org.slf4j.LoggerFactory;"); + public JULRuleSet() { + SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.Logger;"), "import org.slf4j.Logger;", + "import org.slf4j.LoggerFactory;"); - SingleConversionRule crFactory0 = new SingleConversionRule(Pattern - .compile("Logger.getLogger\\("), "LoggerFactory.getLogger("); + SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;"); - SingleConversionRule crFactory1 = new SingleConversionRule(Pattern - .compile("LogManager.getLogger\\("), "LoggerFactory.getLogger("); + SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+java.util.logging.*;"), "import org.slf4j.Logger;", + "import org.slf4j.LoggerFactory;"); - 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); - } + SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger("); - public Iterator iterator() { - return conversionRuleList.iterator(); - } + 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 48d15804..850349f2 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 @@ -29,63 +29,63 @@ 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; - } + final RuleSet ruleSet; + boolean atLeastOneMatchOccured = false; - /** - * 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(); + 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]; + 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; } - } - 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 index 39d4469f..c760496c 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 @@ -28,69 +28,51 @@ 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;"); + private ArrayList conversionRuleList; - SingleConversionRule catImport = new SingleConversionRule(Pattern - .compile("import\\s*+org.apache.log4j.Category;"), - "import org.slf4j.Logger;", - "import org.slf4j.LoggerFactory;"); + public Log4jRuleSet() { - SingleConversionRule crImport1 = new SingleConversionRule(Pattern - .compile("import\\s*+org.apache.log4j.LogManager;"), - "import org.slf4j.LoggerFactory;"); + SingleConversionRule crImport0 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.Logger;"), "import org.slf4j.Logger;", + "import org.slf4j.LoggerFactory;"); - SingleConversionRule crImport2 = new SingleConversionRule(Pattern - .compile("import\\s*+org.apache.log4j.*;"), - "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 crImportMDC = new SingleConversionRule(Pattern - .compile("import\\s*+org.apache.log4j.MDC;"), - "import org.slf4j.MDC;"); - + SingleConversionRule crImport1 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.LogManager;"), "import org.slf4j.LoggerFactory;"); - SingleConversionRule crFactory0 = new SingleConversionRule(Pattern - .compile("Logger.getLogger\\("), "LoggerFactory.getLogger("); + SingleConversionRule crImport2 = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.*;"), "import org.slf4j.Logger;", + "import org.slf4j.LoggerFactory;"); - SingleConversionRule crFactory1 = new SingleConversionRule(Pattern - .compile("\\sCategory.getInstance\\("), " LoggerFactory.getLogger("); + SingleConversionRule crImportMDC = new SingleConversionRule(Pattern.compile("import\\s*+org.apache.log4j.MDC;"), "import org.slf4j.MDC;"); - SingleConversionRule crFactory2 = new SingleConversionRule(Pattern - .compile("LogManager.getLogger\\("), "LoggerFactory.getLogger("); + SingleConversionRule crFactory0 = new SingleConversionRule(Pattern.compile("Logger.getLogger\\("), "LoggerFactory.getLogger("); - SingleConversionRule variable0 = new SingleConversionRule(Pattern - .compile("(\\sCategory\\b)")," Logger"); + SingleConversionRule crFactory1 = new SingleConversionRule(Pattern.compile("\\sCategory.getInstance\\("), " LoggerFactory.getLogger("); - SingleConversionRule variable1 = new SingleConversionRule(Pattern - .compile("(^Category\\b)"),"Logger"); + SingleConversionRule crFactory2 = new SingleConversionRule(Pattern.compile("LogManager.getLogger\\("), "LoggerFactory.getLogger("); - 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); + SingleConversionRule variable0 = new SingleConversionRule(Pattern.compile("(\\sCategory\\b)"), " Logger"); - conversionRuleList.add(variable0); - conversionRuleList.add(variable1); - } + SingleConversionRule variable1 = new SingleConversionRule(Pattern.compile("(^Category\\b)"), "Logger"); - public Iterator iterator() { - return conversionRuleList.iterator(); - } + 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 631a0b47..ce1ee520 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 @@ -27,7 +27,6 @@ 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 @@ -36,60 +35,66 @@ import java.util.regex.Pattern; * */ 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]; + // It is extremely unlikely to encounter more than 10 groups in one of + // our conversion reg-expressions + final private static int MAX_GROUPS = 10; - public MultiGroupConversionRule(Pattern pattern) { - this.pattern = pattern; - } + private Pattern pattern; + private String[] replacementTable = new String[MAX_GROUPS]; - /* (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"); + public MultiGroupConversionRule(Pattern pattern) { + this.pattern = pattern; } - 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)); - } + /* + * (non-Javadoc) + * + * @see org.slf4j.converter.ConversionRule#getPattern() + */ + public Pattern getPattern() { + return pattern; } - return replacementBuffer.toString(); - } - public String getAdditionalLine() { - return null; - } + 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 8ee59985..6c5bf37a 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 @@ -26,9 +26,8 @@ package org.slf4j.migrator.line; import java.util.Iterator; - public interface RuleSet { - Iterator iterator(); - + 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 ccfa6fd3..d6b0a5d2 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 @@ -27,7 +27,6 @@ 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 @@ -37,38 +36,40 @@ import java.util.regex.Pattern; */ 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); - } + final private Pattern pattern; + final private String replacementText; + final private String additionalLine; - 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; - } + 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; - } + /* + * (non-Javadoc) + * + * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher) + */ + public String replace(Matcher matcher) { + return replacementText; + } - public String getAdditionalLine() { - return additionalLine; - } + 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 index 16fec608..9473b652 100755 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/AllTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/AllTest.java @@ -29,10 +29,7 @@ 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}) - +@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 40965803..d4b090a2 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/AternativeApproach.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/AternativeApproach.java @@ -33,123 +33,122 @@ 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"); + /** + * 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); + 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); + assertTrue(m.matches()); + String r = cr2.replace(m); + assertEquals("abcd LOGGER", r); - System.out.println(r); - } + System.out.println(r); + } - /** - * In this test we replace, using the simple Pattern (Log), the full Log - * declaration and instanciation. 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); + /** + * In this test we replace, using the simple Pattern (Log), the full Log + * declaration and instanciation. 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 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 s2 = "Logabc "; + m = pat.matcher(s2); + assertTrue(m.find()); - String s3 = "abcLog"; - m = pat.matcher(s3); - 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 instanciation - * 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); + /** + * In this test we use a simple Pattern to replace the log instanciation + * 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()); - } + String nonMatching = "Log log = xxx;"; + pat.matcher(nonMatching); + assertFalse(m.find()); + } - /** - * In this test we try to replace keyword Log without influence on String - * containg Log We see that we have to use two differents 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); + /** + * In this test we try to replace keyword Log without influence on String + * containg Log We see that we have to use two differents 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 s2 = "Logabcd "; + m = pat.matcher(s2); + assertFalse(m.find()); - String s3 = "abcdLogabcd "; - m = pat.matcher(s3); - assertFalse(m.find()); + String s3 = "abcdLogabcd "; + m = pat.matcher(s3); + assertFalse(m.find()); - String s4 = "abcdLog"; - m = pat.matcher(s4); - assertFalse(m.find()); + String s4 = "abcdLog"; + m = pat.matcher(s4); + assertFalse(m.find()); - String s5 = "Log myLog"; - m = pat.matcher(s5); - 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); - } + 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); + /** + * 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); - } + 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 0eb5e614..9f3eb461 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/FileConverterTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/FileConverterTest.java @@ -35,24 +35,23 @@ import org.slf4j.migrator.line.EmptyRuleSet; public class FileConverterTest extends TestCase { - public FileConverterTest(String arg0) { - super(arg0); - } + public FileConverterTest(String arg0) { + super(arg0); + } - protected void setUp() throws Exception { - super.setUp(); - } + protected void setUp() throws Exception { + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); - } + protected void tearDown() throws Exception { + super.tearDown(); + } - public void test() { - } + public void test() { + } - - public void XtestNOP() throws IOException { - InplaceFileConverter fc = new InplaceFileConverter(new EmptyRuleSet(), new NopProgressListener()); - fc.convert(new File("c:/varargs.txt")); - } + 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 index 80c1b08e..dfb6af82 100755 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/PackageTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/PackageTest.java @@ -24,12 +24,11 @@ */ 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}) +@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 46921fc1..a8cee0bf 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/ProjectConverterTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/ProjectConverterTest.java @@ -34,13 +34,12 @@ import junit.framework.TestCase; public class ProjectConverterTest extends TestCase { - public void test() { - } + public void test() { + } - 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); - } + 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 5d2ec75c..ab8c8cbb 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 @@ -30,136 +30,129 @@ import junit.framework.TestCase; public class AbbreviatorTest extends TestCase { - static final char FS = '/'; - static final String INPUT_0 = "/abc/123456/ABC"; - static final String INPUT_1 = "/abc/123456/xxxxx/ABC"; + 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); + RandomHelper rh = new RandomHelper(FS); - public AbbreviatorTest(String arg0) { - super(arg0); - } - - protected void setUp() throws Exception { - super.setUp(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void testSmoke() { - { - Abbreviator abb = new Abbreviator(2, 100, FS); - String r = abb.abbreviate(INPUT_0); - assertEquals(INPUT_0, r); + public AbbreviatorTest(String arg0) { + super(arg0); } - { - Abbreviator abb = new Abbreviator(3, 8, FS); - String r = abb.abbreviate(INPUT_0); - assertEquals("/abc/.../ABC", r); + protected void setUp() throws Exception { + super.setUp(); } - { - Abbreviator abb = new Abbreviator(3, 8, FS); - String r = abb.abbreviate(INPUT_0); - assertEquals("/abc/.../ABC", r); + + protected void tearDown() throws Exception { + super.tearDown(); } - } - public void testImpossibleToAbbreviate() { - Abbreviator abb = new Abbreviator(2, 20, FS); - String in = "iczldqwivpgm/mgrmvbjdxrwmqgprdjusth"; - String r = abb.abbreviate(in); - assertEquals(in, r); - } + public void testSmoke() { + { + Abbreviator abb = new Abbreviator(2, 100, FS); + String r = abb.abbreviate(INPUT_0); + assertEquals(INPUT_0, r); + } - public void testNoFS() { - Abbreviator abb = new Abbreviator(2, 100, FS); - String r = abb.abbreviate("hello"); - assertEquals("hello", r); - - } - - public void testZeroPrefix() { - { - Abbreviator abb = new Abbreviator(0, 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); + } } - } - 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); + public void testImpossibleToAbbreviate() { + Abbreviator abb = new Abbreviator(2, 20, FS); + String in = "iczldqwivpgm/mgrmvbjdxrwmqgprdjusth"; + String r = abb.abbreviate(in); + assertEquals(in, r); } - } - // 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()); - } + public void testNoFS() { + Abbreviator abb = new Abbreviator(2, 100, FS); + String r = abb.abbreviate("hello"); + assertEquals("hello", r); - // 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; + public void testZeroPrefix() { + { + Abbreviator abb = new Abbreviator(0, 100, FS); + String r = abb.abbreviate(INPUT_0); + assertEquals(INPUT_0, r); + } + } + + 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); } - 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 index 6d6e596f..e72304f9 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 @@ -29,7 +29,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({AbbreviatorTest.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 e28a880d..1928daaa 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 @@ -28,43 +28,43 @@ 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(); - } + private Random random = new Random(100); + final char folderSeparator; - 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)); - } + 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(); } - 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 e13bdd1f..08686edf 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 @@ -30,25 +30,25 @@ import org.slf4j.migrator.internal.ProgressListener; public class NopProgressListener implements ProgressListener { - public void onDirectory(File file) { - } + public void onDirectory(File file) { + } - public void onDone() { - } + public void onDone() { + } - public void onFileAddition(File file) { - } + public void onFileAddition(File file) { + } - public void onFileScan(File file) { - } + public void onFileScan(File file) { + } - public void onInplaceConversion(File file) { - } + public void onInplaceConversion(File file) { + } - public void onFileScanBegin() { - } + public void onFileScanBegin() { + } - public void onMigrationBegin() { - } + 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 ce11c976..442b0cf6 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 @@ -31,129 +31,91 @@ import junit.framework.TestCase; public class JCLRuleSetTest extends TestCase { - LineConverter jclConverter = new LineConverter(new JCLRuleSet()); - - 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;")); - } + LineConverter jclConverter = new LineConverter(new JCLRuleSet()); - 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")); - } + 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;")); + } - 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")); - } + 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")); + } - 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;")); + public void testLogFactoryGetFactoryReplacement() { - // 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;")); - } + // 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")); + } - public void testMultiLineReplacement() { - // Logger declaration on a line - assertEquals("protected Logger log =", jclConverter - .getOneLineReplacement("protected Log log =")); + public void testLogDeclarationReplacement() { - // 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);")); - } + // 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;")); + } + + 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 index c34a2e2f..77e11b78 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 @@ -35,144 +35,102 @@ import static org.junit.Assert.assertTrue; public class Log4jRuleSetTest { - LineConverter log4jConverter = new LineConverter(new Log4jRuleSet()); + 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 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 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 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;")); + @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;")); - } + // 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 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 =")); + @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);")); - } + 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 78535f75..7160193b 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 @@ -32,56 +32,44 @@ import junit.framework.TestCase; public class NoConversionTest extends TestCase { - /** - * This test shows that performing JCL to SLF4J conversion has no impact on - * Log4j implementation - */ - 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 JCL to SLF4J conversion has no impact on + * Log4j implementation + */ + 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 - */ - 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);")); + /** + * This test shows that performing Log4j to SLF4J conversion has no impact on + * JCL implementation + */ + 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 index 86268a05..e05977f9 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 @@ -29,9 +29,6 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({TrivialMatcherTest.class, - JCLRuleSetTest.class, - Log4jRuleSetTest.class, - NoConversionTest.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 2fb32382..d392769b 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 @@ -34,32 +34,30 @@ 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(); - } - - + 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(); + } + } \ No newline at end of file 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 1f2c773e..b5b3c6d4 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 @@ -30,18 +30,15 @@ import junit.framework.TestCase; public class TrivialMatcherTest extends TestCase { - public void testSimpleReplacement() { - LineConverter trivialLC = new LineConverter(new TrivialMatcher()); + 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")); - // "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")); - assertEquals("1st group second group 4th group", trivialLC - .getOneLineReplacement("first group second group third group 4th group")); - - } + } } 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 61f0599b..10a947a6 100644 --- a/slf4j-nop/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-nop/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -35,47 +35,46 @@ import org.slf4j.spi.LoggerFactoryBinder; * * @author Ceki Gülcü */ -public class StaticLoggerBinder implements LoggerFactoryBinder { +public class StaticLoggerBinder implements LoggerFactoryBinder { - /** - * The unique instance of this class. - * - */ - private static final StaticLoggerBinder SINGLETON = new 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; - } + /** + * 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 usually modified with each 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(); + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is usually modified with each release. + */ + // to avoid constant folding by the compiler, this field must *not* be final + public static String REQUESTED_API_VERSION = "1.6.99"; // !final - /** 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; - } + 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 ebdbeba8..086b0169 100644 --- a/slf4j-nop/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-nop/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -27,7 +27,6 @@ package org.slf4j.impl; import org.slf4j.helpers.NOPMDCAdapter; import org.slf4j.spi.MDCAdapter; - /** * This implementation is bound to {@link NOPMDCAdapter}. * @@ -35,24 +34,23 @@ import org.slf4j.spi.MDCAdapter; */ public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - private StaticMDCBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link StaticMDCBinder}. - */ - public MDCAdapter getMDCA() { - return new NOPMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return NOPMDCAdapter.class.getName(); - } + private StaticMDCBinder() { + } + + /** + * 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 02817079..1d255230 100644 --- a/slf4j-nop/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-nop/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -38,31 +38,30 @@ import org.slf4j.spi.MarkerFactoryBinder; */ 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() { - } - - /** - * 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(); - } - - + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * 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/test/java/org/slf4j/InvocationTest.java b/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java index 2828124f..ea57d374 100644 --- a/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java @@ -28,7 +28,6 @@ import java.io.Closeable; import java.io.IOException; import junit.framework.TestCase; - /** * Test whether invoking the SLF4J API causes problems or not. * @@ -37,94 +36,92 @@ import junit.framework.TestCase; */ public class InvocationTest extends TestCase { - public InvocationTest (String arg0) { - super(arg0); - } + public InvocationTest(String arg0) { + super(arg0); + } - protected void setUp() throws Exception { - super.setUp(); - } + protected void setUp() throws Exception { + super.setUp(); + } - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void test1() { - Logger logger = LoggerFactory.getLogger("test1"); - logger.debug("Hello world."); - } - - 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); - } - - 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); - } - - 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"); + protected void tearDown() throws Exception { + super.tearDown(); + } - 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"); - } - - public void testMDC() { - MDC.put("k", "v"); - assertNull(MDC.get("k")); - MDC.remove("k"); - assertNull(MDC.get("k")); - MDC.clear(); - } + public void test1() { + Logger logger = LoggerFactory.getLogger("test1"); + logger.debug("Hello world."); + } - public void testMDCCloseable() { - MDC.MDCCloseable closeable = MDC.putCloseable("k", "v"); - assertNull(MDC.get("k")); - closeable.close(); - assertNull(MDC.get("k")); - MDC.clear(); - } + 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); + } + + 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); + } + + 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"); + } + + public void testMDC() { + MDC.put("k", "v"); + assertNull(MDC.get("k")); + MDC.remove("k"); + assertNull(MDC.get("k")); + MDC.clear(); + } + + 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-simple/src/main/java/org/slf4j/impl/SimpleLogger.java b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLogger.java index 44313886..7b0abf95 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLogger.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLogger.java @@ -117,537 +117,532 @@ import org.slf4j.spi.LocationAwareLogger; */ public class SimpleLogger extends MarkerIgnoringBase { - private static final long serialVersionUID = -632788891211436180L; - private static final String CONFIGURATION_FILE = "simplelogger.properties"; + private static final long serialVersionUID = -632788891211436180L; + private static final String CONFIGURATION_FILE = "simplelogger.properties"; - private static long START_TIME = System.currentTimeMillis(); - private static final Properties SIMPLE_LOGGER_PROPS = new Properties(); + private static long START_TIME = System.currentTimeMillis(); + private static final Properties SIMPLE_LOGGER_PROPS = new Properties(); - private static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT; - private static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT; - private static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT; - private static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT; - private static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT; + private static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT; + private static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT; + private static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT; + private static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT; + private static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT; - private static boolean INITIALIZED = false; + private static boolean INITIALIZED = false; - private static int DEFAULT_LOG_LEVEL = LOG_LEVEL_INFO; - private static boolean SHOW_DATE_TIME = false; - private static String DATE_TIME_FORMAT_STR = null; - private static DateFormat DATE_FORMATTER = null; - private static boolean SHOW_THREAD_NAME = true; - private static boolean SHOW_LOG_NAME = true; - private static boolean SHOW_SHORT_LOG_NAME = false; - private static String LOG_FILE = "System.err"; - private static PrintStream TARGET_STREAM = null; - private static boolean LEVEL_IN_BRACKETS = false; - private static String WARN_LEVEL_STRING = "WARN"; + private static int DEFAULT_LOG_LEVEL = LOG_LEVEL_INFO; + private static boolean SHOW_DATE_TIME = false; + private static String DATE_TIME_FORMAT_STR = null; + private static DateFormat DATE_FORMATTER = null; + private static boolean SHOW_THREAD_NAME = true; + private static boolean SHOW_LOG_NAME = true; + private static boolean SHOW_SHORT_LOG_NAME = false; + private static String LOG_FILE = "System.err"; + private static PrintStream TARGET_STREAM = null; + private static boolean LEVEL_IN_BRACKETS = false; + private static String WARN_LEVEL_STRING = "WARN"; + /** All system properties used by SimpleLogger start with this prefix */ + public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger."; - /** All system properties used by SimpleLogger start with this prefix */ - public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger."; + public static final String DEFAULT_LOG_LEVEL_KEY = SYSTEM_PREFIX + "defaultLogLevel"; + public static final String SHOW_DATE_TIME_KEY = SYSTEM_PREFIX + "showDateTime"; + public static final String DATE_TIME_FORMAT_KEY = SYSTEM_PREFIX + "dateTimeFormat"; + public static final String SHOW_THREAD_NAME_KEY = SYSTEM_PREFIX + "showThreadName"; + public static final String SHOW_LOG_NAME_KEY = SYSTEM_PREFIX + "showLogName"; + public static final String SHOW_SHORT_LOG_NAME_KEY = SYSTEM_PREFIX + "showShortLogName"; + public static final String LOG_FILE_KEY = SYSTEM_PREFIX + "logFile"; + public static final String LEVEL_IN_BRACKETS_KEY = SYSTEM_PREFIX + "levelInBrackets"; + public static final String WARN_LEVEL_STRING_KEY = SYSTEM_PREFIX + "warnLevelString"; - public static final String DEFAULT_LOG_LEVEL_KEY = SYSTEM_PREFIX + "defaultLogLevel"; - public static final String SHOW_DATE_TIME_KEY = SYSTEM_PREFIX + "showDateTime"; - public static final String DATE_TIME_FORMAT_KEY = SYSTEM_PREFIX + "dateTimeFormat"; - public static final String SHOW_THREAD_NAME_KEY = SYSTEM_PREFIX + "showThreadName"; - public static final String SHOW_LOG_NAME_KEY = SYSTEM_PREFIX + "showLogName"; - public static final String SHOW_SHORT_LOG_NAME_KEY = SYSTEM_PREFIX + "showShortLogName"; - public static final String LOG_FILE_KEY = SYSTEM_PREFIX + "logFile"; - public static final String LEVEL_IN_BRACKETS_KEY = SYSTEM_PREFIX + "levelInBrackets"; - public static final String WARN_LEVEL_STRING_KEY = SYSTEM_PREFIX + "warnLevelString"; + public static final String LOG_KEY_PREFIX = SYSTEM_PREFIX + "log."; - - public static final String LOG_KEY_PREFIX = SYSTEM_PREFIX + "log."; - - - private static String getStringProperty(String name) { - String prop = null; - try { - prop = System.getProperty(name); - } catch (SecurityException e) { - ; // Ignore + private static String getStringProperty(String name) { + String prop = null; + try { + prop = System.getProperty(name); + } catch (SecurityException e) { + ; // Ignore + } + return (prop == null) ? SIMPLE_LOGGER_PROPS.getProperty(name) : prop; } - return (prop == null) ? SIMPLE_LOGGER_PROPS.getProperty(name) : prop; - } - private static String getStringProperty(String name, String defaultValue) { - String prop = getStringProperty(name); - return (prop == null) ? defaultValue : prop; - } - - private static boolean getBooleanProperty(String name, boolean defaultValue) { - String prop = getStringProperty(name); - return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop); - } - - - // Initialize class attributes. - // Load properties file, if found. - // Override with system properties. - static void init() { - INITIALIZED = true; - loadProperties(); - - String defaultLogLevelString = getStringProperty(DEFAULT_LOG_LEVEL_KEY, null); - if (defaultLogLevelString != null) - DEFAULT_LOG_LEVEL = stringToLevel(defaultLogLevelString); - - SHOW_LOG_NAME = getBooleanProperty(SHOW_LOG_NAME_KEY, SHOW_LOG_NAME); - SHOW_SHORT_LOG_NAME = getBooleanProperty(SHOW_SHORT_LOG_NAME_KEY, SHOW_SHORT_LOG_NAME); - SHOW_DATE_TIME = getBooleanProperty(SHOW_DATE_TIME_KEY, SHOW_DATE_TIME); - SHOW_THREAD_NAME = getBooleanProperty(SHOW_THREAD_NAME_KEY, SHOW_THREAD_NAME); - DATE_TIME_FORMAT_STR = getStringProperty(DATE_TIME_FORMAT_KEY, DATE_TIME_FORMAT_STR); - LEVEL_IN_BRACKETS = getBooleanProperty(LEVEL_IN_BRACKETS_KEY, LEVEL_IN_BRACKETS); - WARN_LEVEL_STRING = getStringProperty(WARN_LEVEL_STRING_KEY, WARN_LEVEL_STRING); - - LOG_FILE = getStringProperty(LOG_FILE_KEY, LOG_FILE); - TARGET_STREAM = computeTargetStream(LOG_FILE); - - if (DATE_TIME_FORMAT_STR != null) { - try { - DATE_FORMATTER = new SimpleDateFormat(DATE_TIME_FORMAT_STR); - } catch (IllegalArgumentException e) { - Util.report("Bad date format in " + CONFIGURATION_FILE + "; will output relative time", e); - } + private static String getStringProperty(String name, String defaultValue) { + String prop = getStringProperty(name); + return (prop == null) ? defaultValue : prop; } - } - - private static PrintStream computeTargetStream(String logFile) { - if ("System.err".equalsIgnoreCase(logFile)) - return System.err; - else if ("System.out".equalsIgnoreCase(logFile)) { - return System.out; - } else { - try { - FileOutputStream fos = new FileOutputStream(logFile); - PrintStream printStream = new PrintStream(fos); - return printStream; - } catch (FileNotFoundException e) { - Util.report("Could not open [" + logFile + "]. Defaulting to System.err", e); - return System.err; - } + private static boolean getBooleanProperty(String name, boolean defaultValue) { + String prop = getStringProperty(name); + return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop); } - } - private static void loadProperties() { - // Add props from the resource simplelogger.properties - InputStream in = AccessController.doPrivileged( - new PrivilegedAction() { - public InputStream run() { + // Initialize class attributes. + // Load properties file, if found. + // Override with system properties. + static void init() { + INITIALIZED = true; + loadProperties(); + + String defaultLogLevelString = getStringProperty(DEFAULT_LOG_LEVEL_KEY, null); + if (defaultLogLevelString != null) + DEFAULT_LOG_LEVEL = stringToLevel(defaultLogLevelString); + + SHOW_LOG_NAME = getBooleanProperty(SHOW_LOG_NAME_KEY, SHOW_LOG_NAME); + SHOW_SHORT_LOG_NAME = getBooleanProperty(SHOW_SHORT_LOG_NAME_KEY, SHOW_SHORT_LOG_NAME); + SHOW_DATE_TIME = getBooleanProperty(SHOW_DATE_TIME_KEY, SHOW_DATE_TIME); + SHOW_THREAD_NAME = getBooleanProperty(SHOW_THREAD_NAME_KEY, SHOW_THREAD_NAME); + DATE_TIME_FORMAT_STR = getStringProperty(DATE_TIME_FORMAT_KEY, DATE_TIME_FORMAT_STR); + LEVEL_IN_BRACKETS = getBooleanProperty(LEVEL_IN_BRACKETS_KEY, LEVEL_IN_BRACKETS); + WARN_LEVEL_STRING = getStringProperty(WARN_LEVEL_STRING_KEY, WARN_LEVEL_STRING); + + LOG_FILE = getStringProperty(LOG_FILE_KEY, LOG_FILE); + TARGET_STREAM = computeTargetStream(LOG_FILE); + + if (DATE_TIME_FORMAT_STR != null) { + try { + DATE_FORMATTER = new SimpleDateFormat(DATE_TIME_FORMAT_STR); + } catch (IllegalArgumentException e) { + Util.report("Bad date format in " + CONFIGURATION_FILE + "; will output relative time", e); + } + } + } + + private static PrintStream computeTargetStream(String logFile) { + if ("System.err".equalsIgnoreCase(logFile)) + return System.err; + else if ("System.out".equalsIgnoreCase(logFile)) { + return System.out; + } else { + try { + FileOutputStream fos = new FileOutputStream(logFile); + PrintStream printStream = new PrintStream(fos); + return printStream; + } catch (FileNotFoundException e) { + Util.report("Could not open [" + logFile + "]. Defaulting to System.err", e); + return System.err; + } + } + } + + private static 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); + return threadCL.getResourceAsStream(CONFIGURATION_FILE); } else { - return ClassLoader.getSystemResourceAsStream(CONFIGURATION_FILE); + return ClassLoader.getSystemResourceAsStream(CONFIGURATION_FILE); } - } - }); - if (null != in) { - try { - SIMPLE_LOGGER_PROPS.load(in); - in.close(); - } catch (java.io.IOException e) { - // ignored - } - } - } - - /** The current log level */ - protected int currentLogLevel = LOG_LEVEL_INFO; - /** The short name of this simple log instance */ - private transient String shortLogName = null; - - /** - * Package access allows only {@link SimpleLoggerFactory} to instantiate - * SimpleLogger instances. - */ - SimpleLogger(String name) { - if (!INITIALIZED) { - init(); - } - this.name = name; - - String levelString = recursivelyComputeLevelString(); - if (levelString != null) { - this.currentLogLevel = stringToLevel(levelString); - } else { - this.currentLogLevel = DEFAULT_LOG_LEVEL; - } - } - - String recursivelyComputeLevelString() { - String tempName = name; - String levelString = null; - int indexOfLastDot = tempName.length(); - while ((levelString == null) && (indexOfLastDot > -1)) { - tempName = tempName.substring(0, indexOfLastDot); - levelString = getStringProperty(LOG_KEY_PREFIX + tempName, null); - indexOfLastDot = String.valueOf(tempName).lastIndexOf("."); - } - return levelString; - } - - private static int stringToLevel(String levelStr) { - if ("trace".equalsIgnoreCase(levelStr)) { - return LOG_LEVEL_TRACE; - } else if ("debug".equalsIgnoreCase(levelStr)) { - return LOG_LEVEL_DEBUG; - } else if ("info".equalsIgnoreCase(levelStr)) { - return LOG_LEVEL_INFO; - } else if ("warn".equalsIgnoreCase(levelStr)) { - return LOG_LEVEL_WARN; - } else if ("error".equalsIgnoreCase(levelStr)) { - return LOG_LEVEL_ERROR; - } - // assume INFO by default - return LOG_LEVEL_INFO; - } - - - /** - * 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; + } + }); + if (null != in) { + try { + SIMPLE_LOGGER_PROPS.load(in); + in.close(); + } catch (java.io.IOException e) { + // ignored + } + } } - StringBuilder buf = new StringBuilder(32); + /** The current log level */ + protected int currentLogLevel = LOG_LEVEL_INFO; + /** The short name of this simple log instance */ + private transient String shortLogName = null; - // Append date-time if so configured - if (SHOW_DATE_TIME) { - if (DATE_FORMATTER != null) { - buf.append(getFormattedDate()); + /** + * Package access allows only {@link SimpleLoggerFactory} to instantiate + * SimpleLogger instances. + */ + SimpleLogger(String name) { + if (!INITIALIZED) { + init(); + } + this.name = name; + + String levelString = recursivelyComputeLevelString(); + if (levelString != null) { + this.currentLogLevel = stringToLevel(levelString); + } else { + this.currentLogLevel = DEFAULT_LOG_LEVEL; + } + } + + String recursivelyComputeLevelString() { + String tempName = name; + String levelString = null; + int indexOfLastDot = tempName.length(); + while ((levelString == null) && (indexOfLastDot > -1)) { + tempName = tempName.substring(0, indexOfLastDot); + levelString = getStringProperty(LOG_KEY_PREFIX + tempName, null); + indexOfLastDot = String.valueOf(tempName).lastIndexOf("."); + } + return levelString; + } + + private static int stringToLevel(String levelStr) { + if ("trace".equalsIgnoreCase(levelStr)) { + return LOG_LEVEL_TRACE; + } else if ("debug".equalsIgnoreCase(levelStr)) { + return LOG_LEVEL_DEBUG; + } else if ("info".equalsIgnoreCase(levelStr)) { + return LOG_LEVEL_INFO; + } else if ("warn".equalsIgnoreCase(levelStr)) { + return LOG_LEVEL_WARN; + } else if ("error".equalsIgnoreCase(levelStr)) { + return LOG_LEVEL_ERROR; + } + // assume INFO by default + return LOG_LEVEL_INFO; + } + + /** + * 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 (SHOW_DATE_TIME) { + if (DATE_FORMATTER != null) { + buf.append(getFormattedDate()); + buf.append(' '); + } else { + buf.append(System.currentTimeMillis() - START_TIME); + buf.append(' '); + } + } + + // Append current thread name if so configured + if (SHOW_THREAD_NAME) { + buf.append('['); + buf.append(Thread.currentThread().getName()); + buf.append("] "); + } + + if (LEVEL_IN_BRACKETS) + buf.append('['); + + // Append a readable representation of the log level + switch (level) { + case LOG_LEVEL_TRACE: + buf.append("TRACE"); + break; + case LOG_LEVEL_DEBUG: + buf.append("DEBUG"); + break; + case LOG_LEVEL_INFO: + buf.append("INFO"); + break; + case LOG_LEVEL_WARN: + buf.append(WARN_LEVEL_STRING); + break; + case LOG_LEVEL_ERROR: + buf.append("ERROR"); + break; + } + if (LEVEL_IN_BRACKETS) + buf.append(']'); buf.append(' '); - } else { - buf.append(System.currentTimeMillis() - START_TIME); - buf.append(' '); - } + + // Append the name of the log instance if so configured + if (SHOW_SHORT_LOG_NAME) { + if (shortLogName == null) + shortLogName = computeShortName(); + buf.append(String.valueOf(shortLogName)).append(" - "); + } else if (SHOW_LOG_NAME) { + buf.append(String.valueOf(name)).append(" - "); + } + + // Append the message + buf.append(message); + + write(buf, t); + } - // Append current thread name if so configured - if (SHOW_THREAD_NAME) { - buf.append('['); - buf.append(Thread.currentThread().getName()); - buf.append("] "); + void write(StringBuilder buf, Throwable t) { + TARGET_STREAM.println(buf.toString()); + if (t != null) { + t.printStackTrace(TARGET_STREAM); + } + TARGET_STREAM.flush(); } - if (LEVEL_IN_BRACKETS) buf.append('['); - - // Append a readable representation of the log level - switch (level) { - case LOG_LEVEL_TRACE: - buf.append("TRACE"); - break; - case LOG_LEVEL_DEBUG: - buf.append("DEBUG"); - break; - case LOG_LEVEL_INFO: - buf.append("INFO"); - break; - case LOG_LEVEL_WARN: - buf.append(WARN_LEVEL_STRING); - break; - case LOG_LEVEL_ERROR: - buf.append("ERROR"); - break; - } - if (LEVEL_IN_BRACKETS) buf.append(']'); - buf.append(' '); - - // Append the name of the log instance if so configured - if (SHOW_SHORT_LOG_NAME) { - if (shortLogName == null) shortLogName = computeShortName(); - buf.append(String.valueOf(shortLogName)).append(" - "); - } else if (SHOW_LOG_NAME) { - buf.append(String.valueOf(name)).append(" - "); + private String getFormattedDate() { + Date now = new Date(); + String dateText; + synchronized (DATE_FORMATTER) { + dateText = DATE_FORMATTER.format(now); + } + return dateText; } - // Append the message - buf.append(message); - - write(buf, t); - - } - - void write(StringBuilder buf, Throwable t) { - TARGET_STREAM.println(buf.toString()); - if (t != null) { - t.printStackTrace(TARGET_STREAM); + private String computeShortName() { + return name.substring(name.lastIndexOf(".") + 1); } - TARGET_STREAM.flush(); - } - private String getFormattedDate() { - Date now = new Date(); - String dateText; - synchronized (DATE_FORMATTER) { - dateText = DATE_FORMATTER.format(now); + /** + * 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()); } - 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; + /** + * 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()); } - 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; + /** + * 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); } - 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); + } - /** 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); + } - /** - * 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 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 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); + } - /** - * 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); + } - /** 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); + } - /** 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); + } - /** - * 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 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 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); + } - /** - * 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); + } - /** 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); + } - /** 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); + } - /** - * 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 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 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); + } - /** - * 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); + } - /** 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); + } - /** 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); + } - /** - * 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 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 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); + } - /** - * 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); + } - /** 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); + } - /** 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); + } - /** - * 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 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 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); + } - /** - * 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); - } + /** Log a message of level ERROR, including an exception. */ + public void error(String msg, Throwable t) { + log(LOG_LEVEL_ERROR, msg, t); + } } 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 1c9edfa7..4c59f2dc 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerFactory.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerFactory.java @@ -38,36 +38,36 @@ import org.slf4j.ILoggerFactory; */ public class SimpleLoggerFactory implements ILoggerFactory { - ConcurrentMap loggerMap; + ConcurrentMap loggerMap; - public SimpleLoggerFactory() { - loggerMap = new ConcurrentHashMap(); - } - - /** - * 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; + public SimpleLoggerFactory() { + loggerMap = new ConcurrentHashMap(); } - } - /** - * 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(); - } + /** + * 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 92a995ee..a08ff675 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -37,46 +37,45 @@ import org.slf4j.spi.LoggerFactoryBinder; */ 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; - } + /** + * The unique instance of this class. + * + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Declare the version of the SLF4J API this implementation is compiled - * against. The value of this field is usually modified with each 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(); + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } - /** - * 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; - } + /** + * Declare the version of the SLF4J API this implementation is compiled + * against. The value of this field is usually modified with each 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 ebdbeba8..086b0169 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -27,7 +27,6 @@ package org.slf4j.impl; import org.slf4j.helpers.NOPMDCAdapter; import org.slf4j.spi.MDCAdapter; - /** * This implementation is bound to {@link NOPMDCAdapter}. * @@ -35,24 +34,23 @@ import org.slf4j.spi.MDCAdapter; */ public class StaticMDCBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - private StaticMDCBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link StaticMDCBinder}. - */ - public MDCAdapter getMDCA() { - return new NOPMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return NOPMDCAdapter.class.getName(); - } + private StaticMDCBinder() { + } + + /** + * 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 dc6cfce1..435a924b 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -39,31 +39,30 @@ import org.slf4j.spi.MarkerFactoryBinder; */ 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() { - } - - /** - * 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(); - } - - + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * 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/test/java/org/slf4j/DetectLoggerNameMismatchTest.java b/slf4j-simple/src/test/java/org/slf4j/DetectLoggerNameMismatchTest.java index e51eb293..c6c6f205 100755 --- a/slf4j-simple/src/test/java/org/slf4j/DetectLoggerNameMismatchTest.java +++ b/slf4j-simple/src/test/java/org/slf4j/DetectLoggerNameMismatchTest.java @@ -46,95 +46,89 @@ import org.junit.Test; */ public class DetectLoggerNameMismatchTest { - private static final String MISMATCH_STRING = "Detected logger name mismatch"; + private static final String MISMATCH_STRING = "Detected logger name mismatch"; - private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - private final PrintStream oldErr = System.err; + private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + private final PrintStream oldErr = System.err; - @Before - public void setUp() { - System.setErr(new PrintStream(byteArrayOutputStream)); - } + @Before + public void setUp() { + System.setErr(new PrintStream(byteArrayOutputStream)); + } - @After - public void tearDown() { - setTrialEnabled(false); - System.setErr(oldErr); - } + @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 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); - assertMismatchDetected(true); - } + /* + * 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); + 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); - assertTrue( - "Actual value of byteArrayOutputStream: " + String.valueOf(byteArrayOutputStream), - String.valueOf(byteArrayOutputStream).contains( - "Detected logger name mismatch. Given name: \"java.lang.String\"; " + - "computed name: \"org.slf4j.DetectLoggerNameMismatchTest\".")); - } + /* + * Checks the whole error message to ensure all the names show up correctly. + */ + @Test + public void testTriggerWholeMessage() { + setTrialEnabled(true); + LoggerFactory.getLogger(String.class); + assertTrue("Actual value of byteArrayOutputStream: " + String.valueOf(byteArrayOutputStream), String.valueOf(byteArrayOutputStream).contains( + "Detected logger name mismatch. Given name: \"java.lang.String\"; " + "computed name: \"org.slf4j.DetectLoggerNameMismatchTest\".")); + } - /* - * 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); - } + /* + * 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)); - } + 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); - } + @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; - } + 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()); + public Logger logger = LoggerFactory.getLogger(getClass()); } -class Square extends ShapeBase {} +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 3712abb3..6842d07c 100644 --- a/slf4j-simple/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-simple/src/test/java/org/slf4j/InvocationTest.java @@ -28,7 +28,6 @@ import java.io.PrintStream; import junit.framework.TestCase; - /** * Test whether invoking the SLF4J API causes problems or not. * @@ -37,98 +36,96 @@ import junit.framework.TestCase; */ public class InvocationTest extends TestCase { - PrintStream old = System.err; - - public InvocationTest (String arg0) { - super(arg0); - } + PrintStream old = System.err; - protected void setUp() throws Exception { - super.setUp(); - System.setErr(new SilentPrintStream(old)); - } + public InvocationTest(String arg0) { + super(arg0); + } - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } - - public void test1() { - Logger logger = LoggerFactory.getLogger("test1"); - logger.debug("Hello world."); - } - - 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://bugzilla.slf4j.org/show_bug.cgi?id=78 - public void testNullParameter_BUG78() { - Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78"); - String[] parameters = null; - String msg = "hello {}"; - logger.info(msg, parameters); - } - - 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); - } - - 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"); + protected void setUp() throws Exception { + super.setUp(); + System.setErr(new SilentPrintStream(old)); + } - 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"); - } - - public void testMDC() { - MDC.put("k", "v"); - assertNull(MDC.get("k")); - MDC.remove("k"); - assertNull(MDC.get("k")); - MDC.clear(); - } + protected void tearDown() throws Exception { + super.tearDown(); + System.setErr(old); + } + + public void test1() { + Logger logger = LoggerFactory.getLogger("test1"); + logger.debug("Hello world."); + } + + 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://bugzilla.slf4j.org/show_bug.cgi?id=78 + public void testNullParameter_BUG78() { + Logger logger = LoggerFactory.getLogger("testNullParameter_BUG78"); + String[] parameters = null; + String msg = "hello {}"; + logger.info(msg, parameters); + } + + 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); + } + + 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"); + } + + 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/SilentPrintStream.java b/slf4j-simple/src/test/java/org/slf4j/SilentPrintStream.java index abb0cbaa..1d710d98 100644 --- a/slf4j-simple/src/test/java/org/slf4j/SilentPrintStream.java +++ b/slf4j-simple/src/test/java/org/slf4j/SilentPrintStream.java @@ -28,19 +28,19 @@ import java.io.PrintStream; public class SilentPrintStream extends PrintStream { - PrintStream other; + PrintStream other; - public SilentPrintStream(PrintStream ps) { - super(ps); - other = ps; - } + public SilentPrintStream(PrintStream ps) { + super(ps); + other = ps; + } - public void print(String s) { - } + public void print(String s) { + } - public void println(String s) { - } - - public void println(Object x) { - } + public void println(String s) { + } + + public void println(Object x) { + } } 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 ea349256..4c84762d 100644 --- a/slf4j-simple/src/test/java/org/slf4j/impl/SimpleLoggerTest.java +++ b/slf4j-simple/src/test/java/org/slf4j/impl/SimpleLoggerTest.java @@ -33,45 +33,46 @@ import static junit.framework.Assert.assertNull; public class SimpleLoggerTest { - String A_KEY = SimpleLogger.LOG_KEY_PREFIX+"a"; + String A_KEY = SimpleLogger.LOG_KEY_PREFIX + "a"; - @Before public void before() { - System.setProperty(A_KEY, "info"); - } + @Before + public void before() { + System.setProperty(A_KEY, "info"); + } - @After public void after() { - System.clearProperty(A_KEY); - } + @After + public void after() { + System.clearProperty(A_KEY); + } - @Test - public void emptyLoggerName() { - SimpleLogger simpleLogger = new SimpleLogger("a"); - assertEquals("info", simpleLogger.recursivelyComputeLevelString()); - } + @Test + public void emptyLoggerName() { + SimpleLogger simpleLogger = new SimpleLogger("a"); + assertEquals("info", simpleLogger.recursivelyComputeLevelString()); + } - @Test - public void loggerNameWithNoDots_WithLevel() { - SimpleLogger simpleLogger = new SimpleLogger("a"); - assertEquals("info", simpleLogger.recursivelyComputeLevelString()); - } + @Test + public void loggerNameWithNoDots_WithLevel() { + 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 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 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 loggerNameWithOneDot_NoSetLevel() { + SimpleLogger simpleLogger = new SimpleLogger("x.y"); + assertNull(simpleLogger.recursivelyComputeLevelString()); + } }