From 88c4c456766193e012eb890e2208473d99b91f83 Mon Sep 17 00:00:00 2001 From: Ceki Gulcu Date: Thu, 3 Dec 2009 19:16:42 +0100 Subject: [PATCH] setting autocrlf = true on windows - no logical changes --- .gitignore | 12 +- LICENSE.txt | 48 +- binderVersion.pl | 84 +- codeStyle.xml | 502 +-- integration/build.xml | 188 +- integration/osgi-build.xml | 182 +- integration/pom.xml | 240 +- integration/src/IBUNDLE-META-INF/MANIFEST.MF | 28 +- .../src/test/java/integrator/Activator.java | 112 +- .../test/java/org/slf4j/MultiBindingTest.java | 124 +- .../java/org/slf4j/Pre155VersionTest.java | 118 +- .../java/org/slf4j/StringPrintStream.java | 68 +- .../test/java/org/slf4j/VersionMatchTest.java | 78 +- .../java/org/slf4j/VersionMismatchTest.java | 86 +- .../java/org/slf4j/test_osgi/BundleTest.java | 70 +- .../test_osgi/CheckingBundleListener.java | 86 +- .../java/org/slf4j/test_osgi/FelixHost.java | 250 +- .../test_osgi/FrameworkErrorListener.java | 120 +- jcl-over-slf4j/LICENSE.txt | 350 +-- jcl-over-slf4j/pom.xml | 164 +- .../logging/impl/SLF4JLocationAwareLog.java | 530 ++-- .../apache/commons/logging/impl/SLF4JLog.java | 466 +-- .../apache/commons/logging/impl/package.html | 10 +- .../org/apache/commons/logging/package.html | 338 +-- .../src/main/resources/META-INF/MANIFEST.MF | 18 +- .../org.apache.commons.logging.LogFactory | 10 +- .../apache/commons/logging/InvokeJCLTest.java | 188 +- .../logging/impl/SerializationTest.java | 132 +- jcl104-over-slf4j/pom.xml | 60 +- jul-to-slf4j/pom.xml | 104 +- .../org/slf4j/bridge/SLF4JBridgeHandler.java | 546 ++-- .../main/java/org/slf4j/bridge/package.html | 30 +- .../java/org/slf4j/bridge/ListAppender.java | 106 +- .../bridge/SLF4JBridgeHandlerPerfTest.java | 230 +- .../slf4j/bridge/SLF4JBridgeHandlerTest.java | 350 +-- .../slf4j/bridge/testLogStrings.properties | 6 +- log4j-over-slf4j/compatibility/build.xml | 274 +- log4j-over-slf4j/compatibility/readme.txt | 32 +- .../src/main/java/test/DummyObject.java | 16 +- .../src/main/java/test/Log4j12Calls.java | 78 +- .../src/main/java/test/Log4j13Calls.java | 92 +- .../src/main/java/test/LoggerTest.java | 338 +-- log4j-over-slf4j/pom.xml | 134 +- .../main/java/org/apache/log4j/Category.java | 670 ++-- .../src/main/java/org/apache/log4j/Level.java | 434 +-- .../org/apache/log4j/Log4jLoggerFactory.java | 92 +- .../java/org/apache/log4j/LogManager.java | 90 +- .../main/java/org/apache/log4j/Logger.java | 158 +- .../src/main/java/org/apache/log4j/MDC.java | 56 +- .../main/java/org/apache/log4j/Priority.java | 386 +-- .../main/java/org/apache/log4j/package.html | 36 +- .../src/main/resources/META-INF/MANIFEST.MF | 12 +- .../test/java/org/apache/log4j/Trivial.java | 102 +- .../src/test/java/org/dummy/Bug131.java | 136 +- .../src/test/java/org/dummy/Bug139.java | 114 +- .../src/test/java/org/dummy/ListHandler.java | 50 +- slf4j-api/LICENSE.txt | 48 +- slf4j-api/pom.xml | 200 +- .../main/java/org/slf4j/ILoggerFactory.java | 114 +- .../main/java/org/slf4j/IMarkerFactory.java | 162 +- slf4j-api/src/main/java/org/slf4j/Logger.java | 1442 ++++----- .../main/java/org/slf4j/LoggerFactory.java | 580 ++-- slf4j-api/src/main/java/org/slf4j/MDC.java | 412 +-- slf4j-api/src/main/java/org/slf4j/Marker.java | 286 +- .../main/java/org/slf4j/MarkerFactory.java | 182 +- .../org/slf4j/helpers/BasicMDCAdapter.java | 294 +- .../java/org/slf4j/helpers/BasicMarker.java | 392 +-- .../org/slf4j/helpers/BasicMarkerFactory.java | 198 +- .../org/slf4j/helpers/MarkerIgnoringBase.java | 336 +-- .../org/slf4j/helpers/MessageFormatter.java | 788 ++--- .../java/org/slf4j/helpers/NOPLogger.java | 476 +-- .../org/slf4j/helpers/NOPMakerAdapter.java | 78 +- .../org/slf4j/helpers/NamedLoggerBase.java | 92 +- .../helpers/SubstituteLoggerFactory.java | 134 +- .../src/main/java/org/slf4j/helpers/Util.java | 90 +- .../main/java/org/slf4j/helpers/package.html | 32 +- .../org/slf4j/impl/StaticLoggerBinder.java | 154 +- .../java/org/slf4j/impl/StaticMDCBinder.java | 70 +- .../org/slf4j/impl/StaticMarkerBinder.java | 142 +- .../src/main/java/org/slf4j/impl/package.html | 34 +- .../src/main/java/org/slf4j/package.html | 32 +- .../org/slf4j/spi/LocationAwareLogger.java | 120 +- .../org/slf4j/spi/LoggerFactoryBinder.java | 132 +- .../main/java/org/slf4j/spi/MDCAdapter.java | 182 +- .../org/slf4j/spi/MarkerFactoryBinder.java | 134 +- .../src/main/java/org/slf4j/spi/package.html | 14 +- .../src/main/resources/META-INF/MANIFEST.MF | 16 +- .../test/java/org/slf4j/BasicMarkerTest.java | 392 +-- .../test/java/org/slf4j/Differentiator.java | 74 +- .../test/java/org/slf4j/NoBindingTest.java | 50 +- .../test/java/org/slf4j/helpers/BogoPerf.java | 318 +- .../java/org/slf4j/helpers/BubbleSort.java | 100 +- .../org/slf4j/helpers/BubbleSortTest.java | 202 +- .../helpers/MessageFormatterPerfTest.java | 116 +- .../slf4j/helpers/MessageFormatterTest.java | 572 ++-- .../test/java/org/slf4j/helpers/MyRandom.java | 112 +- slf4j-ext/pom.xml | 208 +- slf4j-ext/src/main/java/org/slf4j/NDC.java | 122 +- .../main/java/org/slf4j/agent/package.html | 66 +- .../main/java/org/slf4j/cal10n/LocLogger.java | 350 +-- .../org/slf4j/cal10n/LocLoggerFactory.java | 146 +- .../java/org/slf4j/ext/LoggerWrapper.java | 1736 +++++------ .../src/main/java/org/slf4j/ext/XLogger.java | 394 +-- .../java/org/slf4j/ext/XLoggerFactory.java | 84 +- .../src/main/java/org/slf4j/ext/package.html | 24 +- .../org/slf4j/instrumentation/package.html | 36 +- .../java/org/slf4j/profiler/DurationUnit.java | 68 +- .../java/org/slf4j/profiler/Profiler.java | 552 ++-- .../org/slf4j/profiler/ProfilerRegistry.java | 134 +- .../java/org/slf4j/profiler/SpacePadder.java | 152 +- .../java/org/slf4j/profiler/StopWatch.java | 234 +- .../org/slf4j/profiler/TimeInstrument.java | 110 +- .../slf4j/profiler/TimeInstrumentStatus.java | 80 +- .../main/java/org/slf4j/profiler/Util.java | 228 +- .../main/java/org/slf4j/profiler/package.html | 26 +- .../src/main/resources/META-INF/MANIFEST.MF | 16 +- .../src/test/java/org/slf4j/NDCTest.java | 114 +- .../org/slf4j/cal10n_dummy/LocLoggerTest.java | 158 +- .../java/org/slf4j/cal10n_dummy/Months.java | 20 +- .../org/slf4j/cal10n_dummy/MyApplication.java | 64 +- .../org/slf4j/cal10n_dummy/Production.java | 26 +- .../org/slf4j/dummyExt/EventLoggerTest.java | 214 +- .../java/org/slf4j/dummyExt/ListAppender.java | 60 +- .../java/org/slf4j/dummyExt/XLoggerTest.java | 314 +- .../test/java/org/slf4j/dummyExt/package.html | 6 +- .../org/slf4j/profiler/BasicProfilerDemo.java | 126 +- .../slf4j/profiler/NestedProfilerDemo.java | 124 +- .../slf4j/profiler/NestedProfilerDemo2.java | 84 +- .../java/org/slf4j/profiler/PackageTest.java | 74 +- .../java/org/slf4j/profiler/ProfilerTest.java | 272 +- .../profiler/RandomIntegerArrayGenerator.java | 32 +- .../profiler/SortAndPruneComposites.java | 144 +- .../java/org/slf4j/profiler/UtilTest.java | 104 +- slf4j-ext/src/test/resources/log4j.properties | 12 +- .../src/test/resources/months_en.properties | 12 +- slf4j-jcl/LICENSE.txt | 48 +- .../java/org/slf4j/impl/JCLLoggerAdapter.java | 1070 +++---- .../java/org/slf4j/impl/JCLLoggerFactory.java | 152 +- .../org/slf4j/impl/StaticLoggerBinder.java | 184 +- .../java/org/slf4j/impl/StaticMDCBinder.java | 68 +- .../org/slf4j/impl/StaticMarkerBinder.java | 154 +- .../src/main/resources/META-INF/MANIFEST.MF | 18 +- .../test/java/org/slf4j/InvocationTest.java | 276 +- slf4j-jdk14/LICENSE.txt | 48 +- slf4j-jdk14/pom.xml | 136 +- .../org/slf4j/impl/JDK14LoggerAdapter.java | 1324 ++++---- .../org/slf4j/impl/JDK14LoggerFactory.java | 160 +- .../org/slf4j/impl/StaticLoggerBinder.java | 182 +- .../java/org/slf4j/impl/StaticMDCBinder.java | 72 +- .../org/slf4j/impl/StaticMarkerBinder.java | 154 +- .../src/main/resources/META-INF/MANIFEST.MF | 16 +- .../test/java/org/slf4j/InvocationTest.java | 298 +- .../impl/JDK14AdapterLoggerNameTest.java | 194 +- .../test/java/org/slf4j/impl/PerfTest.java | 104 +- slf4j-log4j12/LICENSE.txt | 48 +- slf4j-log4j12/pom.xml | 110 +- .../org/slf4j/impl/Log4jLoggerAdapter.java | 1200 ++++---- .../org/slf4j/impl/Log4jLoggerFactory.java | 162 +- .../java/org/slf4j/impl/Log4jMDCAdapter.java | 128 +- .../org/slf4j/impl/StaticLoggerBinder.java | 194 +- .../java/org/slf4j/impl/StaticMDCBinder.java | 66 +- .../org/slf4j/impl/StaticMarkerBinder.java | 154 +- .../src/main/resources/META-INF/MANIFEST.MF | 16 +- .../test/java/org/slf4j/InvocationTest.java | 366 +-- .../src/test/java/org/slf4j/ListAppender.java | 58 +- .../org/slf4j/impl/RecursiveAppender.java | 60 +- .../impl/RecursiveInitializationTest.java | 66 +- .../test/resources/recursiveInit.properties | 14 +- slf4j-migrator/LIMITATIONS.txt | 68 +- slf4j-migrator/pom.xml | 90 +- .../java/org/slf4j/migrator/FileSelector.java | 90 +- .../slf4j/migrator/InplaceFileConverter.java | 174 +- .../main/java/org/slf4j/migrator/Main.java | 100 +- .../slf4j/migrator/helper/Abbreviator.java | 132 +- .../migrator/helper/SpringLayoutHelper.java | 84 +- .../migrator/internal/ConversionTask.java | 114 +- .../migrator/internal/ProgressListener.java | 80 +- .../internal/ProgressListenerImpl.java | 252 +- .../slf4j/migrator/line/ConversionRule.java | 100 +- .../org/slf4j/migrator/line/EmptyRuleSet.java | 30 +- .../line/MultiGroupConversionRule.java | 190 +- .../java/org/slf4j/migrator/line/RuleSet.java | 20 +- .../migrator/line/SingleConversionRule.java | 148 +- .../test/java/org/slf4j/migrator/AllTest.java | 82 +- .../slf4j/migrator/AternativeApproach.java | 262 +- .../org/slf4j/migrator/FileConverterTest.java | 68 +- .../slf4j/migrator/ProjectConverterTest.java | 44 +- .../migrator/helper/AbbreviatorTest.java | 282 +- .../slf4j/migrator/helper/RandomHelper.java | 92 +- .../internal/NopProgressListener.java | 60 +- .../slf4j/migrator/line/TriviialMatcher.java | 128 +- slf4j-nop/LICENSE.txt | 48 +- slf4j-nop/pom.xml | 102 +- .../java/org/slf4j/impl/NOPLoggerFactory.java | 116 +- .../org/slf4j/impl/StaticLoggerBinder.java | 178 +- .../java/org/slf4j/impl/StaticMDCBinder.java | 68 +- .../org/slf4j/impl/StaticMarkerBinder.java | 154 +- .../src/main/resources/META-INF/MANIFEST.MF | 16 +- .../test/java/org/slf4j/InvocationTest.java | 258 +- slf4j-osgi-integration-test/pom.xml | 2 +- .../integration/jdk/test/JdkBundleTest.java | 352 +-- .../log4j/test/Log4JBundleTest.java | 362 +-- .../logservice/test/LogServiceBundleTest.java | 376 +-- .../integration/nop/test/NopBundleTest.java | 348 +-- .../simple/test/SimpleBundleTest.java | 354 +-- .../osgi/integration/jdk/test/MANIFEST.MF | 28 +- .../osgi/integration/log4j/test/MANIFEST.MF | 28 +- .../integration/logservice/test/MANIFEST.MF | 30 +- .../osgi/integration/nop/test/MANIFEST.MF | 28 +- .../osgi/integration/simple/test/MANIFEST.MF | 28 +- slf4j-simple/LICENSE.txt | 48 +- slf4j-simple/pom.xml | 94 +- .../java/org/slf4j/impl/SimpleLogger.java | 754 ++--- .../org/slf4j/impl/SimpleLoggerFactory.java | 146 +- .../org/slf4j/impl/StaticLoggerBinder.java | 164 +- .../java/org/slf4j/impl/StaticMDCBinder.java | 116 +- .../org/slf4j/impl/StaticMarkerBinder.java | 138 +- .../src/main/resources/META-INF/MANIFEST.MF | 18 +- .../test/java/org/slf4j/InvocationTest.java | 284 +- .../java/org/slf4j/SilentPrintStream.java | 44 +- slf4j-site/LICENSE.txt | 48 +- slf4j-site/pom.xml | 118 +- slf4j-site/src/site/pages/bug-reporting.html | 194 +- .../src/site/pages/changes/changes-1.3.txt | 88 +- slf4j-site/src/site/pages/codes.html | 560 ++-- slf4j-site/src/site/pages/compatibility.html | 536 ++-- slf4j-site/src/site/pages/css/prettify.css | 54 +- slf4j-site/src/site/pages/css/site.css | 594 ++-- slf4j-site/src/site/pages/docs.html | 272 +- slf4j-site/src/site/pages/faq.html | 2682 ++++++++--------- slf4j-site/src/site/pages/inde_base.html | 56 +- slf4j-site/src/site/pages/index.html | 106 +- slf4j-site/src/site/pages/legacy.html | 478 +-- slf4j-site/src/site/pages/license.html | 136 +- slf4j-site/src/site/pages/localization.html | 316 +- slf4j-site/src/site/pages/mailing-lists.html | 254 +- slf4j-site/src/site/pages/manual.html | 682 ++--- slf4j-site/src/site/pages/migrator.html | 450 +-- slf4j-site/src/site/pages/repos.html | 208 +- slf4j-site/src/site/pages/support.html | 86 +- slf4j-site/src/site/pages/templates/footer.js | 36 +- slf4j-site/src/site/pages/templates/header.js | 12 +- slf4j-site/src/site/pages/templates/left.js | 70 +- slf4j-site/src/site/pages/templates/right.js | 2 +- src/main/assembly/source.xml | 610 ++-- version.pl | 88 +- 246 files changed, 24385 insertions(+), 24385 deletions(-) diff --git a/.gitignore b/.gitignore index ebc44e14..f69eeb62 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ -.settings -target -.classpath -.project -*~ -integration/bundle/ +.settings +target +.classpath +.project +*~ +integration/bundle/ integration/felix-cache/ \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt index f1c9e370..48b18e39 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,24 +1,24 @@ -Copyright (c) 2004-2008 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - +Copyright (c) 2004-2008 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/binderVersion.pl b/binderVersion.pl index 688d4ae4..b5b32334 100644 --- a/binderVersion.pl +++ b/binderVersion.pl @@ -1,42 +1,42 @@ - -if ($#ARGV < 1) { - print "Usage: binderVersion.pl VER FILE {FILE, FILE}\n"; - exit; -} - -$V= $ARGV[0]; -# Trim -SNAPSHOT -$V =~ s/-SNAPSHOT//; - -print "VER:${V}\r\n"; -shift(@ARGV); - -sub replace () { - my $filename = $_[0]; - - if(-s $filename) { - print "Processing [" . $filename . "]\r\n"; - - my $original = "$filename.original"; - - rename($filename, $original); - open(OUT, ">$filename"); - open(IN, "$original"); - - while() { - if(/VERSION\s+=\s+".*";/) { - s/VERSION\s+=\s+".*";/VERSION = "${V}";/; - } - print OUT; - } - close(IN); - close(OUT); - unlink($original); - } else { - print "File [" . $filename . "] does not exist\r\n" - } -} - -foreach $ARG (@ARGV) { - do replace($ARG); -} + +if ($#ARGV < 1) { + print "Usage: binderVersion.pl VER FILE {FILE, FILE}\n"; + exit; +} + +$V= $ARGV[0]; +# Trim -SNAPSHOT +$V =~ s/-SNAPSHOT//; + +print "VER:${V}\r\n"; +shift(@ARGV); + +sub replace () { + my $filename = $_[0]; + + if(-s $filename) { + print "Processing [" . $filename . "]\r\n"; + + my $original = "$filename.original"; + + rename($filename, $original); + open(OUT, ">$filename"); + open(IN, "$original"); + + while() { + if(/VERSION\s+=\s+".*";/) { + s/VERSION\s+=\s+".*";/VERSION = "${V}";/; + } + print OUT; + } + close(IN); + close(OUT); + unlink($original); + } else { + print "File [" . $filename . "] does not exist\r\n" + } +} + +foreach $ARG (@ARGV) { + do replace($ARG); +} diff --git a/codeStyle.xml b/codeStyle.xml index 21b42b61..b204f1a1 100644 --- a/codeStyle.xml +++ b/codeStyle.xml @@ -1,251 +1,251 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/integration/build.xml b/integration/build.xml index cc549493..41b55d47 100644 --- a/integration/build.xml +++ b/integration/build.xml @@ -1,95 +1,95 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/integration/osgi-build.xml b/integration/osgi-build.xml index 00f59f7f..231c2faa 100644 --- a/integration/osgi-build.xml +++ b/integration/osgi-build.xml @@ -1,92 +1,92 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - value of t = @{t} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + value of t = @{t} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/integration/pom.xml b/integration/pom.xml index bb407830..b5e2ef7f 100644 --- a/integration/pom.xml +++ b/integration/pom.xml @@ -1,121 +1,121 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - integration - jar - SLF4J Integration tests - - http://www.slf4j.org - SLF4J integration tests - - - - org.slf4j - slf4j-api - - - - - junit - junit - 3.8.1 - - - - ant - ant-junit - 1.6.5 - - - - - - org.apache.felix - org.apache.felix.main - 2.0.2 - - - - - - - maven-antrun-plugin - 1.2 - - - junit - junit - 3.8.1 - - - ant - ant-junit - 1.6.5 - - - - - ant-test - package - - - - - - - - - - - - run - - - - ant-osgi-test - package - - - - - - - - - - run - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - once - plain - false - - **/*Test.java - - - - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + integration + jar + SLF4J Integration tests + + http://www.slf4j.org + SLF4J integration tests + + + + org.slf4j + slf4j-api + + + + + junit + junit + 3.8.1 + + + + ant + ant-junit + 1.6.5 + + + + + + org.apache.felix + org.apache.felix.main + 2.0.2 + + + + + + + maven-antrun-plugin + 1.2 + + + junit + junit + 3.8.1 + + + ant + ant-junit + 1.6.5 + + + + + ant-test + package + + + + + + + + + + + + run + + + + ant-osgi-test + package + + + + + + + + + + run + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + once + plain + false + + **/*Test.java + + + + + + + + \ No newline at end of file diff --git a/integration/src/IBUNDLE-META-INF/MANIFEST.MF b/integration/src/IBUNDLE-META-INF/MANIFEST.MF index c06e4609..10d04448 100644 --- a/integration/src/IBUNDLE-META-INF/MANIFEST.MF +++ b/integration/src/IBUNDLE-META-INF/MANIFEST.MF @@ -1,15 +1,15 @@ -Manifest-Version: 1.0 -Archiver-Version: Plexus Archiver -Created-By: Apache Maven -Built-By: ceki -Build-Jdk: 1.6.0_16 -Bundle-Description: iBundle -Bundle-Version: 0.1 -Bundle-Activator: integrator.Activator -Implementation-Title: iBundle -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: iBundle -Bundle-Name: abundle -Bundle-RequiredExecutionEnvironment: J2SE-1.3 -Export-Package: apack +Manifest-Version: 1.0 +Archiver-Version: Plexus Archiver +Created-By: Apache Maven +Built-By: ceki +Build-Jdk: 1.6.0_16 +Bundle-Description: iBundle +Bundle-Version: 0.1 +Bundle-Activator: integrator.Activator +Implementation-Title: iBundle +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: iBundle +Bundle-Name: abundle +Bundle-RequiredExecutionEnvironment: J2SE-1.3 +Export-Package: apack Import-Package: org.osgi.framework, org.slf4j;version=1.5 \ No newline at end of file diff --git a/integration/src/test/java/integrator/Activator.java b/integration/src/test/java/integrator/Activator.java index c2f6617e..e61a28a5 100644 --- a/integration/src/test/java/integrator/Activator.java +++ b/integration/src/test/java/integrator/Activator.java @@ -1,57 +1,57 @@ -/* - * Copyright (c) 2004-2009 QOS.ch All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package integrator; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A BundleActivator which invokes slf4j loggers - * @author Ceki Gülcü - * - */ -public class Activator implements BundleActivator { - - private BundleContext m_context = null; - - public void start(BundleContext context) { - Logger logger = LoggerFactory.getLogger(this.getClass()); - logger.info("Activator.start()"); - m_context = context; - } - - public void stop(BundleContext context) { - m_context = null; - Logger logger = LoggerFactory.getLogger(this.getClass()); - logger.info("Activator.stop"); - } - - public Bundle[] getBundles() { - if (m_context != null) { - return m_context.getBundles(); - } - return null; - } +/* + * Copyright (c) 2004-2009 QOS.ch All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package integrator; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A BundleActivator which invokes slf4j loggers + * @author Ceki Gülcü + * + */ +public class Activator implements BundleActivator { + + private BundleContext m_context = null; + + public void start(BundleContext context) { + Logger logger = LoggerFactory.getLogger(this.getClass()); + logger.info("Activator.start()"); + m_context = context; + } + + public void stop(BundleContext context) { + m_context = null; + Logger logger = LoggerFactory.getLogger(this.getClass()); + logger.info("Activator.stop"); + } + + public Bundle[] getBundles() { + if (m_context != null) { + return m_context.getBundles(); + } + return null; + } } \ No newline at end of file diff --git a/integration/src/test/java/org/slf4j/MultiBindingTest.java b/integration/src/test/java/org/slf4j/MultiBindingTest.java index 7e1b1838..3f33c3ec 100644 --- a/integration/src/test/java/org/slf4j/MultiBindingTest.java +++ b/integration/src/test/java/org/slf4j/MultiBindingTest.java @@ -1,62 +1,62 @@ -/* - * Copyright (c) 2004-2009 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j; - -import java.io.PrintStream; -import java.util.Random; - -import junit.framework.TestCase; - -public class MultiBindingTest extends TestCase { - - StringPrintStream sps = new StringPrintStream(System.err); - PrintStream old = System.err; - int diff = 1024 + new Random().nextInt(10000); - - public MultiBindingTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } - - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } - - public void test() throws Exception { - Logger logger = LoggerFactory.getLogger(this.getClass()); - String msg = "hello world " + diff; - logger.info(msg); - assertTrue("number of lines should be greater than 4", sps.stringList - .size() > 4); - String s0 = (String) sps.stringList.get(0); - assertTrue(s0 - .contains("SLF4J: Class path contains multiple SLF4J bindings.")); - } -} +/* + * Copyright (c) 2004-2009 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j; + +import java.io.PrintStream; +import java.util.Random; + +import junit.framework.TestCase; + +public class MultiBindingTest extends TestCase { + + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); + + public MultiBindingTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } + + protected void tearDown() throws Exception { + super.tearDown(); + System.setErr(old); + } + + public void test() throws Exception { + Logger logger = LoggerFactory.getLogger(this.getClass()); + String msg = "hello world " + diff; + logger.info(msg); + assertTrue("number of lines should be greater than 4", sps.stringList + .size() > 4); + String s0 = (String) sps.stringList.get(0); + assertTrue(s0 + .contains("SLF4J: Class path contains multiple SLF4J bindings.")); + } +} diff --git a/integration/src/test/java/org/slf4j/Pre155VersionTest.java b/integration/src/test/java/org/slf4j/Pre155VersionTest.java index f9fd3c38..02dc11eb 100644 --- a/integration/src/test/java/org/slf4j/Pre155VersionTest.java +++ b/integration/src/test/java/org/slf4j/Pre155VersionTest.java @@ -1,59 +1,59 @@ -/* - * Copyright (c) 2004-2009 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j; - -import java.io.PrintStream; -import java.util.Random; - -import junit.framework.TestCase; - -public class Pre155VersionTest extends TestCase { - - StringPrintStream sps = new StringPrintStream(System.err); - PrintStream old = System.err; - int diff = 1024 + new Random().nextInt(10000); - - public Pre155VersionTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } - - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } - - public void test() throws Exception { - Logger logger = LoggerFactory.getLogger(this.getClass()); - String msg = "hello world " + diff; - logger.info(msg); - String s0 = (String) sps.stringList.get(0); - assertTrue(s0.contains(msg)); - } -} +/* + * Copyright (c) 2004-2009 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j; + +import java.io.PrintStream; +import java.util.Random; + +import junit.framework.TestCase; + +public class Pre155VersionTest extends TestCase { + + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); + + public Pre155VersionTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } + + protected void tearDown() throws Exception { + super.tearDown(); + System.setErr(old); + } + + public void test() throws Exception { + Logger logger = LoggerFactory.getLogger(this.getClass()); + String msg = "hello world " + diff; + logger.info(msg); + String s0 = (String) sps.stringList.get(0); + assertTrue(s0.contains(msg)); + } +} diff --git a/integration/src/test/java/org/slf4j/StringPrintStream.java b/integration/src/test/java/org/slf4j/StringPrintStream.java index 22d16dac..35d08613 100644 --- a/integration/src/test/java/org/slf4j/StringPrintStream.java +++ b/integration/src/test/java/org/slf4j/StringPrintStream.java @@ -1,34 +1,34 @@ -package org.slf4j; - -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.List; - -public class StringPrintStream extends PrintStream { - - public static final String LINE_SEP = System.getProperty("line.separator"); - PrintStream other; - List stringList = new ArrayList(); - - public StringPrintStream(PrintStream ps) { - super(ps); - other = ps; - } - - public void print(String s) { - other.print(s); - stringList.add(s); - } - - public void println(String s) { - other.println(s); - stringList.add(s); - - } - - public void println(Object o) { - other.println(o); - stringList.add(o); - } -} - +package org.slf4j; + +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; + +public class StringPrintStream extends PrintStream { + + public static final String LINE_SEP = System.getProperty("line.separator"); + PrintStream other; + List stringList = new ArrayList(); + + public StringPrintStream(PrintStream ps) { + super(ps); + other = ps; + } + + public void print(String s) { + other.print(s); + stringList.add(s); + } + + public void println(String s) { + other.println(s); + stringList.add(s); + + } + + public void println(Object o) { + other.println(o); + stringList.add(o); + } +} + diff --git a/integration/src/test/java/org/slf4j/VersionMatchTest.java b/integration/src/test/java/org/slf4j/VersionMatchTest.java index d86884c6..4b7a0755 100644 --- a/integration/src/test/java/org/slf4j/VersionMatchTest.java +++ b/integration/src/test/java/org/slf4j/VersionMatchTest.java @@ -1,39 +1,39 @@ - -package org.slf4j; - -import java.io.PrintStream; -import java.util.Random; - -import junit.framework.TestCase; - -public class VersionMatchTest extends TestCase { - - - StringPrintStream sps = new StringPrintStream(System.err); - PrintStream old = System.err; - int diff = 1024 + new Random().nextInt(10000); - - public VersionMatchTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } - - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } - - - public void test() throws Exception { - Logger logger = LoggerFactory.getLogger(this.getClass()); - String msg = "hello world "+diff; - logger.info(msg); - assertEquals(1, sps.stringList.size()); - String s0 = (String) sps.stringList.get(0); - assertTrue(s0.contains(msg)); - } -} + +package org.slf4j; + +import java.io.PrintStream; +import java.util.Random; + +import junit.framework.TestCase; + +public class VersionMatchTest extends TestCase { + + + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); + + public VersionMatchTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } + + protected void tearDown() throws Exception { + super.tearDown(); + System.setErr(old); + } + + + public void test() throws Exception { + Logger logger = LoggerFactory.getLogger(this.getClass()); + String msg = "hello world "+diff; + logger.info(msg); + assertEquals(1, sps.stringList.size()); + String s0 = (String) sps.stringList.get(0); + assertTrue(s0.contains(msg)); + } +} diff --git a/integration/src/test/java/org/slf4j/VersionMismatchTest.java b/integration/src/test/java/org/slf4j/VersionMismatchTest.java index d0f6b370..d325866d 100644 --- a/integration/src/test/java/org/slf4j/VersionMismatchTest.java +++ b/integration/src/test/java/org/slf4j/VersionMismatchTest.java @@ -1,43 +1,43 @@ -package org.slf4j; - -import java.io.PrintStream; -import java.util.Random; - -import junit.framework.TestCase; - -public class VersionMismatchTest extends TestCase { - - StringPrintStream sps = new StringPrintStream(System.err); - PrintStream old = System.err; - int diff = 1024 + new Random().nextInt(10000); - - public VersionMismatchTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - System.setErr(sps); - } - - protected void tearDown() throws Exception { - super.tearDown(); - System.setErr(old); - } - - public void test() throws Exception { - Logger logger = LoggerFactory.getLogger(this.getClass()); - String msg = "hello world " + diff; - logger.info(msg); - - String s0 = (String) sps.stringList.get(0); - assertTrue(s0.matches("SLF4J: The requested version .* by your slf4j binding is not compatible with.*")); - - String s1 = (String) sps.stringList.get(1); - assertTrue(s1.contains(LoggerFactory.VERSION_MISMATCH)); - - String s2 = (String) sps.stringList.get(2); - assertTrue(s2.contains(msg)); - - } -} +package org.slf4j; + +import java.io.PrintStream; +import java.util.Random; + +import junit.framework.TestCase; + +public class VersionMismatchTest extends TestCase { + + StringPrintStream sps = new StringPrintStream(System.err); + PrintStream old = System.err; + int diff = 1024 + new Random().nextInt(10000); + + public VersionMismatchTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + System.setErr(sps); + } + + protected void tearDown() throws Exception { + super.tearDown(); + System.setErr(old); + } + + public void test() throws Exception { + Logger logger = LoggerFactory.getLogger(this.getClass()); + String msg = "hello world " + diff; + logger.info(msg); + + String s0 = (String) sps.stringList.get(0); + assertTrue(s0.matches("SLF4J: The requested version .* by your slf4j binding is not compatible with.*")); + + String s1 = (String) sps.stringList.get(1); + assertTrue(s1.contains(LoggerFactory.VERSION_MISMATCH)); + + String s2 = (String) sps.stringList.get(2); + assertTrue(s2.contains(msg)); + + } +} diff --git a/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java b/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java index 6488a9a9..c4f209fe 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java +++ b/integration/src/test/java/org/slf4j/test_osgi/BundleTest.java @@ -1,35 +1,35 @@ -package org.slf4j.test_osgi; - -import java.io.File; - -import junit.framework.TestCase; - -public class BundleTest extends TestCase { - - FrameworkErrorListener fel = new FrameworkErrorListener(); - CheckingBundleListener mbl = new CheckingBundleListener(); - - FelixHost felixHost = new FelixHost(fel, mbl); - - protected void setUp() throws Exception { - super.setUp(); - felixHost.doLaunch(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - felixHost.stop(); - } - - public void testSmoke() { - System.out.println("==========="+new File(".").getAbsolutePath()); - mbl.dumpAll(); - // check that the bundle was installed - assertTrue(mbl.exists("iBundle")); - if(fel.errorList.size() != 0) { - fel.dumpAll(); - } - // check that no errors occured - assertEquals(0, fel.errorList.size()); - } -} +package org.slf4j.test_osgi; + +import java.io.File; + +import junit.framework.TestCase; + +public class BundleTest extends TestCase { + + FrameworkErrorListener fel = new FrameworkErrorListener(); + CheckingBundleListener mbl = new CheckingBundleListener(); + + FelixHost felixHost = new FelixHost(fel, mbl); + + protected void setUp() throws Exception { + super.setUp(); + felixHost.doLaunch(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + felixHost.stop(); + } + + public void testSmoke() { + System.out.println("==========="+new File(".").getAbsolutePath()); + mbl.dumpAll(); + // check that the bundle was installed + assertTrue(mbl.exists("iBundle")); + if(fel.errorList.size() != 0) { + fel.dumpAll(); + } + // check that no errors occured + assertEquals(0, fel.errorList.size()); + } +} diff --git a/integration/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java b/integration/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java index bfaeed06..3641a2a6 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java +++ b/integration/src/test/java/org/slf4j/test_osgi/CheckingBundleListener.java @@ -1,43 +1,43 @@ -package org.slf4j.test_osgi; - -import java.util.ArrayList; -import java.util.List; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleEvent; -import org.osgi.framework.BundleListener; - -public class CheckingBundleListener implements BundleListener { - - List eventList = new ArrayList(); - - public void bundleChanged(BundleEvent be) { - eventList.add(be); - } - - private void dump(BundleEvent be) { - System.out.println("BE:" + ", source " + be.getSource() + ", bundle=" - + be.getBundle() + ", type=" + be.getType()); - - } - - public void dumpAll() { - for (int i = 0; i < eventList.size(); i++) { - BundleEvent fe = (BundleEvent) eventList.get(i); - dump(fe); - } - } - - boolean exists(String bundleName) { - for (int i = 0; i < eventList.size(); i++) { - BundleEvent fe = (BundleEvent) eventList.get(i); - Bundle b = fe.getBundle(); - System.out.println("===["+b+"]"); - if (bundleName.equals(b.getSymbolicName())) { - return true; - } - } - return false; - } - -} +package org.slf4j.test_osgi; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleEvent; +import org.osgi.framework.BundleListener; + +public class CheckingBundleListener implements BundleListener { + + List eventList = new ArrayList(); + + public void bundleChanged(BundleEvent be) { + eventList.add(be); + } + + private void dump(BundleEvent be) { + System.out.println("BE:" + ", source " + be.getSource() + ", bundle=" + + be.getBundle() + ", type=" + be.getType()); + + } + + public void dumpAll() { + for (int i = 0; i < eventList.size(); i++) { + BundleEvent fe = (BundleEvent) eventList.get(i); + dump(fe); + } + } + + boolean exists(String bundleName) { + for (int i = 0; i < eventList.size(); i++) { + BundleEvent fe = (BundleEvent) eventList.get(i); + Bundle b = fe.getBundle(); + System.out.println("===["+b+"]"); + if (bundleName.equals(b.getSymbolicName())) { + return true; + } + } + return false; + } + +} diff --git a/integration/src/test/java/org/slf4j/test_osgi/FelixHost.java b/integration/src/test/java/org/slf4j/test_osgi/FelixHost.java index 4fd572d2..62058f5b 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/FelixHost.java +++ b/integration/src/test/java/org/slf4j/test_osgi/FelixHost.java @@ -1,126 +1,126 @@ -/* - * Copyright (c) 2004-2009 QOS.ch All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package org.slf4j.test_osgi; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.apache.felix.framework.Felix; -import org.apache.felix.framework.util.FelixConstants; -import org.apache.felix.framework.util.StringMap; -import org.apache.felix.main.AutoProcessor; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.Constants; - -/** - * Runs a hosted version of Felix for testing purposes. Any bundle errors are - * reported via the FrameworkListener passed to the constructor. - * - * @author Ceki Gücü - */ -public class FelixHost { - - private Felix felix = null; - - Properties otherProps = new Properties(); - - final FrameworkErrorListener frameworkErrorListener; - final CheckingBundleListener myBundleListener; - - public FelixHost(FrameworkErrorListener frameworkErrorListener, - CheckingBundleListener myBundleListener) { - this.frameworkErrorListener = frameworkErrorListener; - this.myBundleListener = myBundleListener; - } - - public void doLaunch() { - // Create a case-insensitive configuration property map. - Map 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 void stop() throws BundleException { - felix.stop(); - } - - public Bundle[] getInstalledBundles() { - // Use the system bundle activator to gain external - // access to the set of installed bundles. - return null;// m_activator.getBundles(); - } +/* + * Copyright (c) 2004-2009 QOS.ch All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.slf4j.test_osgi; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.apache.felix.framework.Felix; +import org.apache.felix.framework.util.FelixConstants; +import org.apache.felix.framework.util.StringMap; +import org.apache.felix.main.AutoProcessor; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.Constants; + +/** + * Runs a hosted version of Felix for testing purposes. Any bundle errors are + * reported via the FrameworkListener passed to the constructor. + * + * @author Ceki Gücü + */ +public class FelixHost { + + private Felix felix = null; + + Properties otherProps = new Properties(); + + final FrameworkErrorListener frameworkErrorListener; + final CheckingBundleListener myBundleListener; + + public FelixHost(FrameworkErrorListener frameworkErrorListener, + CheckingBundleListener myBundleListener) { + this.frameworkErrorListener = frameworkErrorListener; + this.myBundleListener = myBundleListener; + } + + public void doLaunch() { + // Create a case-insensitive configuration property map. + Map 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 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 3e9ee36a..118ac8dd 100644 --- a/integration/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java +++ b/integration/src/test/java/org/slf4j/test_osgi/FrameworkErrorListener.java @@ -1,60 +1,60 @@ -/* - * Copyright (c) 2004-2009 QOS.ch All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package org.slf4j.test_osgi; - -import java.util.ArrayList; -import java.util.List; - -import org.osgi.framework.FrameworkEvent; -import org.osgi.framework.FrameworkListener; - -public class FrameworkErrorListener implements FrameworkListener { - - public List errorList = new ArrayList(); - - public void frameworkEvent(FrameworkEvent fe) { - if (fe.getType() == FrameworkEvent.ERROR) { - errorList.add(fe); - - } - } - - private void dump(FrameworkEvent fe) { - Throwable t = fe.getThrowable(); - String tString = null; - if (t != null) { - tString = t.toString(); - } - System.out.println("Framework ERROR:" + ", source " + fe.getSource() - + ", bundle=" + fe.getBundle() + ", ex=" + tString); - if(t != null) { - t.printStackTrace(); - } - } - - public void dumpAll() { - for(int i = 0; i < errorList.size(); i++) { - FrameworkEvent fe = (FrameworkEvent) errorList.get(i); - dump(fe); - } - } -} +/* + * Copyright (c) 2004-2009 QOS.ch All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package org.slf4j.test_osgi; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.framework.FrameworkEvent; +import org.osgi.framework.FrameworkListener; + +public class FrameworkErrorListener implements FrameworkListener { + + public List errorList = new ArrayList(); + + public void frameworkEvent(FrameworkEvent fe) { + if (fe.getType() == FrameworkEvent.ERROR) { + errorList.add(fe); + + } + } + + private void dump(FrameworkEvent fe) { + Throwable t = fe.getThrowable(); + String tString = null; + if (t != null) { + tString = t.toString(); + } + System.out.println("Framework ERROR:" + ", source " + fe.getSource() + + ", bundle=" + fe.getBundle() + ", ex=" + tString); + if(t != null) { + t.printStackTrace(); + } + } + + public void dumpAll() { + for(int i = 0; i < errorList.size(); i++) { + FrameworkEvent fe = (FrameworkEvent) errorList.get(i); + dump(fe); + } + } +} diff --git a/jcl-over-slf4j/LICENSE.txt b/jcl-over-slf4j/LICENSE.txt index 21254fc7..2bb9ad24 100644 --- a/jcl-over-slf4j/LICENSE.txt +++ b/jcl-over-slf4j/LICENSE.txt @@ -1,176 +1,176 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/jcl-over-slf4j/pom.xml b/jcl-over-slf4j/pom.xml index 96b61b06..cac58f71 100644 --- a/jcl-over-slf4j/pom.xml +++ b/jcl-over-slf4j/pom.xml @@ -1,83 +1,83 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - jcl-over-slf4j - jar - JCL 1.1.1 implemented over SLF4J - - http://www.slf4j.org - - JCL 1.1.1 implementation over SLF4J - - - - - - - org.slf4j - slf4j-api - - - - org.slf4j - slf4j-jdk14 - test - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - ${parsedVersion.osgiVersion} - ${project.description} - ${project.version} - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + jcl-over-slf4j + jar + JCL 1.1.1 implemented over SLF4J + + http://www.slf4j.org + + JCL 1.1.1 implementation over SLF4J + + + + + + + org.slf4j + slf4j-api + + + + org.slf4j + slf4j-jdk14 + test + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + ${parsedVersion.osgiVersion} + ${project.description} + ${project.version} + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + + + + \ No newline at end of file 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 04ce57d4..7171784b 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLocationAwareLog.java +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SLF4JLocationAwareLog.java @@ -1,266 +1,266 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.logging.impl; - -import java.io.ObjectStreamException; -import java.io.Serializable; - -import org.apache.commons.logging.Log; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LocationAwareLogger; - -/** - * Implementation of {@link Log org.apache.commons.logging.Log} interface which - * delegates all processing to a wrapped {@link Logger org.slf4j.Logger} - * instance. - * - *

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

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

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

JCL's FATAL and TRACE levels are mapped to ERROR and DEBUG respectively. All + * other levels map one to one. + * + * @author Ceki Gülcü + */ +public class SLF4JLog implements Log, Serializable { + + private static final long serialVersionUID = 680728617011167209L; + + //used to store this logger's name to recreate it after serialization + protected String name; + + // in both Log4jLogger and Jdk14Logger classes in the original JCL, the + // logger instance is transient + private transient Logger logger; + + SLF4JLog(Logger logger) { + this.logger = logger; + this.name = logger.getName(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + /** + * Delegates to the isErrorEnabled method of the wrapped + * org.slf4j.Logger instance. + */ + public boolean isFatalEnabled() { + return logger.isErrorEnabled(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + /** + * Delegates to the isDebugEnabled method of the wrapped + * org.slf4j.Logger instance. + */ + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + /** + * Directly delegates to the wrapped org.slf4j.Logger instance. + */ + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + /** + * Converts the input parameter to String and then delegates to + * the debug method of the wrapped org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + */ + public void trace(Object message) { + logger.trace(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to + * the debug method of the wrapped org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + * @param t the exception to log + */ + public void trace(Object message, Throwable t) { + logger.trace(String.valueOf(message), t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + */ + public void debug(Object message) { + logger.debug(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to + * the wrapped org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + * @param t the exception to log + */ + public void debug(Object message, Throwable t) { + logger.debug(String.valueOf(message), t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + */ + public void info(Object message) { + logger.info(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to + * the wrapped org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + * @param t the exception to log + */ + public void info(Object message, Throwable t) { + logger.info(String.valueOf(message), t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + */ + public void warn(Object message) { + logger.warn(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to + * the wrapped org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + * @param t the exception to log + */ + public void warn(Object message, Throwable t) { + logger.warn(String.valueOf(message), t); + } + + /** + * Converts the input parameter to String and then delegates to the wrapped + * org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + */ + public void error(Object message) { + logger.error(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to + * the wrapped org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + * @param t the exception to log + */ + public void error(Object message, Throwable t) { + logger.error(String.valueOf(message), t); + } + + + + /** + * Converts the input parameter to String and then delegates to + * the error method of the wrapped org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + */ + public void fatal(Object message) { + logger.error(String.valueOf(message)); + } + + /** + * Converts the first input parameter to String and then delegates to + * the error method of the wrapped org.slf4j.Logger instance. + * + * @param message the message to log. Converted to {@link String} + * @param t the exception to log + */ + public void fatal(Object message, Throwable t) { + logger.error(String.valueOf(message), t); + } + + /** + * Replace this instance with a homonymous (same name) logger returned by + * LoggerFactory. Note that this method is only called during deserialization. + * + * @return logger with same name as returned by LoggerFactory + * @throws ObjectStreamException + */ + protected Object readResolve() throws ObjectStreamException { + Logger logger = LoggerFactory.getLogger(this.name); + return new SLF4JLog(logger); + } } \ No newline at end of file diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/package.html b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/package.html index 128d15f8..ec177dd3 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/package.html +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/package.html @@ -1,5 +1,5 @@ - - -

SLF4J based implementation of commons-logging wrapper APIs.

- - + + +

SLF4J based implementation of commons-logging wrapper APIs.

+ + diff --git a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/package.html b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/package.html index 8e76ba47..04ca2d78 100644 --- a/jcl-over-slf4j/src/main/java/org/apache/commons/logging/package.html +++ b/jcl-over-slf4j/src/main/java/org/apache/commons/logging/package.html @@ -1,169 +1,169 @@ - - - -

Jakarta Commons Logging implemented over SLF4J.

- - -

Overview

- -

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

- -

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

- -

Quick Start Guide

- -

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

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

Configuring the Commons Logging Package

- -

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

- -

Choosing a LogFactory Implementation

- -

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

- - - -

Configuring the Underlying Logging System

- -

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

- -

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

- -

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

- - -

Using the Logging Package APIs

- -

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

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

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

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

into a single method call:

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

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

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

Jakarta Commons Logging implemented over SLF4J.

+ + +

Overview

+ +

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

+ +

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

+ +

Quick Start Guide

+ +

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

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

Configuring the Commons Logging Package

+ +

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

+ +

Choosing a LogFactory Implementation

+ +

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

+ + + +

Configuring the Underlying Logging System

+ +

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

+ +

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

+ +

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

+ + +

Using the Logging Package APIs

+ +

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

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

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

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

into a single method call:

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

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

+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class MyComponent {
+
+  protected static Log log =
+    LogFactory.getLog(MyComponent.class);
+
+  // Called once at startup time
+  public void start() {
+    ...
+    log.info("MyComponent started");
+    ...
+  }
+
+  // Called once at shutdown time
+  public void stop() {
+    ...
+    log.info("MyComponent stopped");
+    ...
+  }
+
+  // Called repeatedly to process a particular argument value
+  // which you want logged if debugging is enabled
+  public void process(String value) {
+    ...
+    // Do the string concatenation only if logging is enabled
+    if (log.isDebugEnabled())
+      log.debug("MyComponent processing " + value);
+    ...
+  }
+
+}
+
+ + diff --git a/jcl-over-slf4j/src/main/resources/META-INF/MANIFEST.MF b/jcl-over-slf4j/src/main/resources/META-INF/MANIFEST.MF index 390f3c12..a78719a4 100644 --- a/jcl-over-slf4j/src/main/resources/META-INF/MANIFEST.MF +++ b/jcl-over-slf4j/src/main/resources/META-INF/MANIFEST.MF @@ -1,9 +1,9 @@ -Implementation-Title: jcl-over-slf4j -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: jcl.over.slf4j -Bundle-Name: jcl-over-slf4j -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.3 -Export-Package: org.apache.commons.logging;version=1.1.1, - org.apache.commons.logging.impl;version=1.1.1 -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion} +Implementation-Title: jcl-over-slf4j +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: jcl.over.slf4j +Bundle-Name: jcl-over-slf4j +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.3 +Export-Package: org.apache.commons.logging;version=1.1.1, + org.apache.commons.logging.impl;version=1.1.1 +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion} diff --git a/jcl-over-slf4j/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory b/jcl-over-slf4j/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory index 50a7c3bc..8cece6f0 100644 --- a/jcl-over-slf4j/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory +++ b/jcl-over-slf4j/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory @@ -1,5 +1,5 @@ -org.apache.commons.logging.impl.SLF4JLogFactory - -# Axis gets at JCL through its own mechanism as defined by Commons Discovery, which -# in turn follows the instructions found at: -# http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service Provider +org.apache.commons.logging.impl.SLF4JLogFactory + +# Axis gets at JCL through its own mechanism as defined by Commons Discovery, which +# in turn follows the instructions found at: +# http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html#Service Provider diff --git a/jcl-over-slf4j/src/test/java/org/apache/commons/logging/InvokeJCLTest.java b/jcl-over-slf4j/src/test/java/org/apache/commons/logging/InvokeJCLTest.java index e8536e48..28222d90 100644 --- a/jcl-over-slf4j/src/test/java/org/apache/commons/logging/InvokeJCLTest.java +++ b/jcl-over-slf4j/src/test/java/org/apache/commons/logging/InvokeJCLTest.java @@ -1,94 +1,94 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - - -package org.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"); - - log.error(null); - log.error("error message"); - - log.fatal(null); - log.fatal("fatal message"); - - - log.trace(null, e); - log.trace("trace message", e); - - log.debug(null, e); - log.debug("debug message", e); - - log.info(null, e); - log.info("info message", e); - - log.warn(null, e); - log.warn("warn message", e); - - log.error(null, e); - log.error("error message", e); - - log.fatal(null, e); - log.fatal("fatal message", e); - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + + +package org.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"); + + 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 be1f3957..d97cef1b 100644 --- a/jcl-over-slf4j/src/test/java/org/apache/commons/logging/impl/SerializationTest.java +++ b/jcl-over-slf4j/src/test/java/org/apache/commons/logging/impl/SerializationTest.java @@ -1,66 +1,66 @@ -package org.apache.commons.logging.impl; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -import junit.framework.TestCase; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.slf4j.impl.JDK14LoggerFactory; -import org.slf4j.spi.LocationAwareLogger; - -public class SerializationTest extends TestCase { - - ObjectInputStream ois; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos; - - public SerializationTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - oos = new ObjectOutputStream(baos); - super.setUp(); - } - - 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); - - 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 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(); - } -} +package org.apache.commons.logging.impl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import junit.framework.TestCase; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.slf4j.impl.JDK14LoggerFactory; +import org.slf4j.spi.LocationAwareLogger; + +public class SerializationTest extends TestCase { + + ObjectInputStream ois; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos; + + public SerializationTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + oos = new ObjectOutputStream(baos); + super.setUp(); + } + + 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); + + 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 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(); + } +} diff --git a/jcl104-over-slf4j/pom.xml b/jcl104-over-slf4j/pom.xml index c2049d9a..5ce0a748 100644 --- a/jcl104-over-slf4j/pom.xml +++ b/jcl104-over-slf4j/pom.xml @@ -1,31 +1,31 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - jcl104-over-slf4j - pom - DEPRECATED - JCL 1.0.4 implemented over SLF4J - - http://www.slf4j.org - - DEPRECATED - JCL implemented over SLF4J - - - - - org.slf4j - jcl-over-slf4j - - As it now supports JCL versions 1.0.4, 1.1 and 1.1.1, the jcl104-over-slf4j module has been renamed as jcl-over-slf4j. - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + jcl104-over-slf4j + pom + DEPRECATED - JCL 1.0.4 implemented over SLF4J + + http://www.slf4j.org + + DEPRECATED - JCL implemented over SLF4J + + + + + org.slf4j + jcl-over-slf4j + + As it now supports JCL versions 1.0.4, 1.1 and 1.1.1, the jcl104-over-slf4j module has been renamed as jcl-over-slf4j. + + + + \ No newline at end of file diff --git a/jul-to-slf4j/pom.xml b/jul-to-slf4j/pom.xml index 713df4a2..2bf3d278 100644 --- a/jul-to-slf4j/pom.xml +++ b/jul-to-slf4j/pom.xml @@ -1,53 +1,53 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - jul-to-slf4j - - jar - JUL to SLF4J bridge - - http://www.slf4j.org - - JUL to SLF4J bridge - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - ${project.version} - test - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.4 - 1.4 - - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + jul-to-slf4j + + jar + JUL to SLF4J bridge + + http://www.slf4j.org + + JUL to SLF4J bridge + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + ${project.version} + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.4 + 1.4 + + + + + + \ No newline at end of file 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 b0651850..1a3a111e 100644 --- a/jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java +++ b/jul-to-slf4j/src/main/java/org/slf4j/bridge/SLF4JBridgeHandler.java @@ -1,273 +1,273 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - */ - -package org.slf4j.bridge; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.LogRecord; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LocationAwareLogger; - -// Based on http://bugzilla.slf4j.org/show_bug.cgi?id=38 - -/** - * Bridge/route all JUL log records to the SLF4J API. - * - *

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

- * FINEST  -> TRACE
- * FINER   -> DEBUG
- * FINE    -> DEBUG
- * INFO    -> INFO
- * WARNING -> WARN
- * SEVER   -> ERROR
- * 
- * - * Usage: - * - *
- * // call only once during initialization time of your application
- * SLF4JBridgeHandler.install();
- * 
- * // usual pattern: get a Logger and then log a message
- * java.util.logging.Logger julLogger = java.util.logging.Logger
- *     .getLogger("org.wombat");
- * julLogger.fine("hello world"); // this will get redirected to SLF4J
- * 
- * - *

- * Please note that translating a java.util.logging event into SLF4J incurs the - * cost of constructing {@link LogRecord} instance regardless of whether the - * SLF4J logger is disabled for the given level. Consequently, j.u.l. to - * SLF4J translation can seriously impact on the cost of disabled logging - * statements (60 fold increase) and a measurable impact on enabled log - * statements (20% overall increase). - *

- * - *

- * If application performance is a concern, then use of SLF4JBridgeHandler is - * appropriate only if few j.u.l. logging statements are in play. - * - * @author Christian Stein - * @author Joern Huxhorn - * @author Ceki Gülcü - * @author Darryl Smith - * - * @since 1.5.1 - */ -public class SLF4JBridgeHandler extends Handler { - - // The caller is java.util.logging.Logger - private static final String FQCN = java.util.logging.Logger.class.getName(); - private static final String UNKNOWN_LOGGER_NAME = "unknown.jul.logger"; - - private static final int TRACE_LEVEL_THRESHOLD = Level.FINEST.intValue(); - private static final int DEBUG_LEVEL_THRESHOLD = Level.FINE.intValue(); - private static final int INFO_LEVEL_THRESHOLD = Level.INFO.intValue(); - private static final int WARN_LEVEL_THRESHOLD = Level.WARNING.intValue(); - - /** - * Adds a SLF4JBridgeHandler instance to jul's root logger. - * - *

- * This handler will redirect jul 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 disabled that statement, by definition, will not - * reach any SLF4JBridgeHandler instance and cannot be redirected. - */ - public static void install() { - LogManager.getLogManager().getLogger("").addHandler( - new SLF4JBridgeHandler()); - } - - /** - * 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 = LogManager.getLogManager().getLogger( - ""); - Handler[] handlers = rootLogger.getHandlers(); - for (int i = 0; i < handlers.length; i++) { - if (handlers[i] instanceof SLF4JBridgeHandler) { - 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, 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(); - if (params != null) { - 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); - } - } - -} +/* + * Copyright (c) 2004-2008 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + */ + +package org.slf4j.bridge; + +import java.text.MessageFormat; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogManager; +import java.util.logging.LogRecord; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LocationAwareLogger; + +// Based on http://bugzilla.slf4j.org/show_bug.cgi?id=38 + +/** + * Bridge/route all JUL log records to the SLF4J API. + * + *

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

+ * FINEST  -> TRACE
+ * FINER   -> DEBUG
+ * FINE    -> DEBUG
+ * INFO    -> INFO
+ * WARNING -> WARN
+ * SEVER   -> ERROR
+ * 
+ * + * Usage: + * + *
+ * // call only once during initialization time of your application
+ * SLF4JBridgeHandler.install();
+ * 
+ * // usual pattern: get a Logger and then log a message
+ * java.util.logging.Logger julLogger = java.util.logging.Logger
+ *     .getLogger("org.wombat");
+ * julLogger.fine("hello world"); // this will get redirected to SLF4J
+ * 
+ * + *

+ * Please note that translating a java.util.logging event into SLF4J incurs the + * cost of constructing {@link LogRecord} instance regardless of whether the + * SLF4J logger is disabled for the given level. Consequently, j.u.l. to + * SLF4J translation can seriously impact on the cost of disabled logging + * statements (60 fold increase) and a measurable impact on enabled log + * statements (20% overall increase). + *

+ * + *

+ * If application performance is a concern, then use of SLF4JBridgeHandler is + * appropriate only if few j.u.l. logging statements are in play. + * + * @author Christian Stein + * @author Joern Huxhorn + * @author Ceki Gülcü + * @author Darryl Smith + * + * @since 1.5.1 + */ +public class SLF4JBridgeHandler extends Handler { + + // The caller is java.util.logging.Logger + private static final String FQCN = java.util.logging.Logger.class.getName(); + private static final String UNKNOWN_LOGGER_NAME = "unknown.jul.logger"; + + private static final int TRACE_LEVEL_THRESHOLD = Level.FINEST.intValue(); + private static final int DEBUG_LEVEL_THRESHOLD = Level.FINE.intValue(); + private static final int INFO_LEVEL_THRESHOLD = Level.INFO.intValue(); + private static final int WARN_LEVEL_THRESHOLD = Level.WARNING.intValue(); + + /** + * Adds a SLF4JBridgeHandler instance to jul's root logger. + * + *

+ * This handler will redirect jul 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 disabled that statement, by definition, will not + * reach any SLF4JBridgeHandler instance and cannot be redirected. + */ + public static void install() { + LogManager.getLogManager().getLogger("").addHandler( + new SLF4JBridgeHandler()); + } + + /** + * 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 = LogManager.getLogManager().getLogger( + ""); + Handler[] handlers = rootLogger.getHandlers(); + for (int i = 0; i < handlers.length; i++) { + if (handlers[i] instanceof SLF4JBridgeHandler) { + 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, 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(); + if (params != null) { + 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/main/java/org/slf4j/bridge/package.html b/jul-to-slf4j/src/main/java/org/slf4j/bridge/package.html index 37927ffc..2b643c31 100644 --- a/jul-to-slf4j/src/main/java/org/slf4j/bridge/package.html +++ b/jul-to-slf4j/src/main/java/org/slf4j/bridge/package.html @@ -1,15 +1,15 @@ - - - - - - - - - - -

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

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

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

+ +
+ + diff --git a/jul-to-slf4j/src/test/java/org/slf4j/bridge/ListAppender.java b/jul-to-slf4j/src/test/java/org/slf4j/bridge/ListAppender.java index 38fc6f1a..044b0cb0 100644 --- a/jul-to-slf4j/src/test/java/org/slf4j/bridge/ListAppender.java +++ b/jul-to-slf4j/src/test/java/org/slf4j/bridge/ListAppender.java @@ -1,53 +1,53 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.bridge; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.spi.LoggingEvent; - -public class ListAppender extends AppenderSkeleton { - - public List list = new ArrayList(); - - public boolean extractLocationInfo = false; - - protected void append(LoggingEvent event) { - list.add(event); - if(extractLocationInfo) { - event.getLocationInformation(); - } - } - - public void close() { - } - - public boolean requiresLayout() { - return false; - } - -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.bridge; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class ListAppender extends AppenderSkeleton { + + public List list = new ArrayList(); + + public boolean extractLocationInfo = false; + + protected void append(LoggingEvent event) { + list.add(event); + if(extractLocationInfo) { + event.getLocationInformation(); + } + } + + public void close() { + } + + public boolean requiresLayout() { + return false; + } + +} diff --git a/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerPerfTest.java b/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerPerfTest.java index ae7d25cd..71588c29 100644 --- a/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerPerfTest.java +++ b/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerPerfTest.java @@ -1,115 +1,115 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.bridge; - -import java.util.logging.Handler; -import java.util.logging.LogManager; - -import junit.framework.TestCase; - -import org.apache.log4j.FileAppender; -import org.apache.log4j.PatternLayout; -import org.slf4j.LoggerFactory; - -public class SLF4JBridgeHandlerPerfTest extends TestCase { - - static String LOGGER_NAME = "yay"; - static int RUN_LENGTH = 100*1000; - - - // set to false to test enabled logging performance - boolean disabledLogger = true; - - FileAppender fileAppender; - org.apache.log4j.Logger log4jRoot; - java.util.logging.Logger julRootLogger = LogManager.getLogManager() - .getLogger(""); - - java.util.logging.Logger julLogger = java.util.logging.Logger - .getLogger(LOGGER_NAME); - org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(LOGGER_NAME); - - Handler[] existingHandlers; - - public SLF4JBridgeHandlerPerfTest(String arg0) { - super(arg0); - } - - 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]); - } - 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]); - } - } - - 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)); - } -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.bridge; + +import java.util.logging.Handler; +import java.util.logging.LogManager; + +import junit.framework.TestCase; + +import org.apache.log4j.FileAppender; +import org.apache.log4j.PatternLayout; +import org.slf4j.LoggerFactory; + +public class SLF4JBridgeHandlerPerfTest extends TestCase { + + static String LOGGER_NAME = "yay"; + static int RUN_LENGTH = 100*1000; + + + // set to false to test enabled logging performance + boolean disabledLogger = true; + + FileAppender fileAppender; + org.apache.log4j.Logger log4jRoot; + java.util.logging.Logger julRootLogger = LogManager.getLogManager() + .getLogger(""); + + java.util.logging.Logger julLogger = java.util.logging.Logger + .getLogger(LOGGER_NAME); + org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(LOGGER_NAME); + + Handler[] existingHandlers; + + public SLF4JBridgeHandlerPerfTest(String arg0) { + super(arg0); + } + + 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]); + } + 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]); + } + } + + 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)); + } +} 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 5f5e1366..18cbaf2c 100644 --- a/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerTest.java +++ b/jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerTest.java @@ -1,175 +1,175 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.bridge; - -import java.text.MessageFormat; -import java.util.ResourceBundle; -import java.util.logging.Level; - -import junit.framework.TestCase; - -import org.apache.log4j.spi.LocationInfo; -import org.apache.log4j.spi.LoggingEvent; - -public class SLF4JBridgeHandlerTest extends TestCase { - - 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"); - - 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 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()); - - // 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); - - 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); - } - - public void testLogWithResourceBundle() { - SLF4JBridgeHandler.install(); - - String resourceBundleName = "org.slf4j.bridge.testLogStrings"; - ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); - String resourceKey = "resource_key"; - String expectedMsg = bundle.getString(resourceKey); - String msg = resourceKey; - - java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger - .getLogger("yay", resourceBundleName); - - julResourceBundleLogger.info(msg); - assertEquals(1, listAppender.list.size()); - LoggingEvent le = (LoggingEvent) listAppender.list.get(0); - assertEquals(LOGGER_NAME, le.getLoggerName()); - assertEquals(expectedMsg, le.getMessage()); - } - - public void testLogWithResourceBundleWithParameters() { - SLF4JBridgeHandler.install(); - - String resourceBundleName = "org.slf4j.bridge.testLogStrings"; - ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); - - java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger - .getLogger("foo", resourceBundleName); - - String resourceKey1 = "resource_key_1"; - String expectedMsg1 = bundle.getString(resourceKey1); - julResourceBundleLogger.info(resourceKey1); // 1st log - - String resourceKey2 = "resource_key_2"; - Object[] params2 = new Object[] { "foo", "bar" }; - String expectedMsg2 = MessageFormat.format(bundle.getString(resourceKey2), - params2); - julResourceBundleLogger.log(Level.INFO, resourceKey2, params2); // 2nd log - - - String resourceKey3 = "invalidKey {0}"; - Object[] params3 = new Object[] { "John" }; - String expectedMsg3 = MessageFormat.format(resourceKey3, params3); - julResourceBundleLogger.log(Level.INFO, resourceKey3, params3); // 3rd log - - julLogger.log(Level.INFO, resourceKey3, params3); // 4th log - - assertEquals(4, listAppender.list.size()); - - LoggingEvent le = null; - - le = (LoggingEvent) listAppender.list.get(0); - assertEquals("foo", le.getLoggerName()); - assertEquals(expectedMsg1, le.getMessage()); - - le = (LoggingEvent) listAppender.list.get(1); - assertEquals("foo", le.getLoggerName()); - assertEquals(expectedMsg2, le.getMessage()); - - le = (LoggingEvent) listAppender.list.get(2); - assertEquals("foo", le.getLoggerName()); - assertEquals(expectedMsg3, le.getMessage()); - - le = (LoggingEvent) listAppender.list.get(3); - assertEquals("yay", le.getLoggerName()); - assertEquals(expectedMsg3, le.getMessage()); - } - - void assertLevel(int index, org.apache.log4j.Level expectedLevel) { - LoggingEvent le = (LoggingEvent) listAppender.list.get(index); - assertEquals(expectedLevel, le.getLevel()); - } -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.bridge; + +import java.text.MessageFormat; +import java.util.ResourceBundle; +import java.util.logging.Level; + +import junit.framework.TestCase; + +import org.apache.log4j.spi.LocationInfo; +import org.apache.log4j.spi.LoggingEvent; + +public class SLF4JBridgeHandlerTest extends TestCase { + + 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"); + + 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 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()); + + // 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); + + 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); + } + + public void testLogWithResourceBundle() { + SLF4JBridgeHandler.install(); + + String resourceBundleName = "org.slf4j.bridge.testLogStrings"; + ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); + String resourceKey = "resource_key"; + String expectedMsg = bundle.getString(resourceKey); + String msg = resourceKey; + + java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger + .getLogger("yay", resourceBundleName); + + julResourceBundleLogger.info(msg); + assertEquals(1, listAppender.list.size()); + LoggingEvent le = (LoggingEvent) listAppender.list.get(0); + assertEquals(LOGGER_NAME, le.getLoggerName()); + assertEquals(expectedMsg, le.getMessage()); + } + + public void testLogWithResourceBundleWithParameters() { + SLF4JBridgeHandler.install(); + + String resourceBundleName = "org.slf4j.bridge.testLogStrings"; + ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); + + java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger + .getLogger("foo", resourceBundleName); + + String resourceKey1 = "resource_key_1"; + String expectedMsg1 = bundle.getString(resourceKey1); + julResourceBundleLogger.info(resourceKey1); // 1st log + + String resourceKey2 = "resource_key_2"; + Object[] params2 = new Object[] { "foo", "bar" }; + String expectedMsg2 = MessageFormat.format(bundle.getString(resourceKey2), + params2); + julResourceBundleLogger.log(Level.INFO, resourceKey2, params2); // 2nd log + + + String resourceKey3 = "invalidKey {0}"; + Object[] params3 = new Object[] { "John" }; + String expectedMsg3 = MessageFormat.format(resourceKey3, params3); + julResourceBundleLogger.log(Level.INFO, resourceKey3, params3); // 3rd log + + julLogger.log(Level.INFO, resourceKey3, params3); // 4th log + + assertEquals(4, listAppender.list.size()); + + LoggingEvent le = null; + + le = (LoggingEvent) listAppender.list.get(0); + assertEquals("foo", le.getLoggerName()); + assertEquals(expectedMsg1, le.getMessage()); + + le = (LoggingEvent) listAppender.list.get(1); + assertEquals("foo", le.getLoggerName()); + assertEquals(expectedMsg2, le.getMessage()); + + le = (LoggingEvent) listAppender.list.get(2); + assertEquals("foo", le.getLoggerName()); + assertEquals(expectedMsg3, le.getMessage()); + + le = (LoggingEvent) listAppender.list.get(3); + assertEquals("yay", le.getLoggerName()); + assertEquals(expectedMsg3, le.getMessage()); + } + + void assertLevel(int index, org.apache.log4j.Level expectedLevel) { + LoggingEvent le = (LoggingEvent) listAppender.list.get(index); + assertEquals(expectedLevel, le.getLevel()); + } +} diff --git a/jul-to-slf4j/src/test/resources/org/slf4j/bridge/testLogStrings.properties b/jul-to-slf4j/src/test/resources/org/slf4j/bridge/testLogStrings.properties index 2b0d1437..e0deb62f 100644 --- a/jul-to-slf4j/src/test/resources/org/slf4j/bridge/testLogStrings.properties +++ b/jul-to-slf4j/src/test/resources/org/slf4j/bridge/testLogStrings.properties @@ -1,3 +1,3 @@ -resource_key=msg -resource_key_1=msg -resource_key_2=msg {0} {1} +resource_key=msg +resource_key_1=msg +resource_key_2=msg {0} {1} diff --git a/log4j-over-slf4j/compatibility/build.xml b/log4j-over-slf4j/compatibility/build.xml index b60875a0..5115a42a 100644 --- a/log4j-over-slf4j/compatibility/build.xml +++ b/log4j-over-slf4j/compatibility/build.xml @@ -1,137 +1,137 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - These are some of the targets supported by this ANT build scpript: - - all - run all available tests - refresh - copy required jar files to the lib directory - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + These are some of the targets supported by this ANT build scpript: + + all - run all available tests + refresh - copy required jar files to the lib directory + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/log4j-over-slf4j/compatibility/readme.txt b/log4j-over-slf4j/compatibility/readme.txt index 575b3581..6554cc63 100644 --- a/log4j-over-slf4j/compatibility/readme.txt +++ b/log4j-over-slf4j/compatibility/readme.txt @@ -1,17 +1,17 @@ - -This directory is used to test the module against various log4j calls. -Two test cases simulate the typical calls that one can find in an application -that uses either log4j 1.2.x, or log4j 1.3.x. - -In the same directory is a build.xml file that uses ant to -compile the test cases with the corresponding log4j version, -and to runs these tests without log4j in the classpath but with -logback jars instead. - -To run the tests, one must have ant installed. Issuing the following command, -once in the compatibility directory will launch the tests: - -ant all - -To obtain more information about the use of the log4j-over-slf4j module, + +This directory is used to test the module against various log4j calls. +Two test cases simulate the typical calls that one can find in an application +that uses either log4j 1.2.x, or log4j 1.3.x. + +In the same directory is a build.xml file that uses ant to +compile the test cases with the corresponding log4j version, +and to runs these tests without log4j in the classpath but with +logback jars instead. + +To run the tests, one must have ant installed. Issuing the following command, +once in the compatibility directory will launch the tests: + +ant all + +To obtain more information about the use of the log4j-over-slf4j module, please visit http://www..slf4j.org/log4j-over-slf4j.html \ No newline at end of file diff --git a/log4j-over-slf4j/compatibility/src/main/java/test/DummyObject.java b/log4j-over-slf4j/compatibility/src/main/java/test/DummyObject.java index 73473eec..3a117909 100644 --- a/log4j-over-slf4j/compatibility/src/main/java/test/DummyObject.java +++ b/log4j-over-slf4j/compatibility/src/main/java/test/DummyObject.java @@ -1,8 +1,8 @@ -package test; - -public class DummyObject { - - public String toString() { - return "dummy"; - } -} +package test; + +public class DummyObject { + + public String toString() { + return "dummy"; + } +} diff --git a/log4j-over-slf4j/compatibility/src/main/java/test/Log4j12Calls.java b/log4j-over-slf4j/compatibility/src/main/java/test/Log4j12Calls.java index 1a1860cb..eeff93b5 100644 --- a/log4j-over-slf4j/compatibility/src/main/java/test/Log4j12Calls.java +++ b/log4j-over-slf4j/compatibility/src/main/java/test/Log4j12Calls.java @@ -1,39 +1,39 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * - * Copyright (C) 1999-2006, QOS.ch - * - * This library is free software, you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation. - */ -package test; - -import junit.framework.TestCase; - -import org.apache.log4j.Logger; -import org.apache.log4j.MDC; - -/** - * - * A test case that issues the typical calls - * that an application using log4j 1.2 would do. - * - * @author Ceki Gülcü - * @author Sébastien Pennec - */ -public class Log4j12Calls extends TestCase { - public static final Logger logger = Logger.getLogger(Log4j12Calls.class); - - public void testLog() { - MDC.put("key", "value1"); - - logger.trace("Trace level can be noisy"); - logger.debug("Entering application"); - logger.info("Violets are blue"); - logger.warn("Here is a warning"); - logger.error("Exiting application", new Exception("just testing")); - - MDC.remove("key"); - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * + * Copyright (C) 1999-2006, QOS.ch + * + * This library is free software, you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation. + */ +package test; + +import junit.framework.TestCase; + +import org.apache.log4j.Logger; +import org.apache.log4j.MDC; + +/** + * + * A test case that issues the typical calls + * that an application using log4j 1.2 would do. + * + * @author Ceki Gülcü + * @author Sébastien Pennec + */ +public class Log4j12Calls extends TestCase { + public static final Logger logger = Logger.getLogger(Log4j12Calls.class); + + public void testLog() { + MDC.put("key", "value1"); + + logger.trace("Trace level can be noisy"); + logger.debug("Entering application"); + logger.info("Violets are blue"); + logger.warn("Here is a warning"); + logger.error("Exiting application", new Exception("just testing")); + + MDC.remove("key"); + } +} diff --git a/log4j-over-slf4j/compatibility/src/main/java/test/Log4j13Calls.java b/log4j-over-slf4j/compatibility/src/main/java/test/Log4j13Calls.java index b44e4ed5..54c6e9f7 100644 --- a/log4j-over-slf4j/compatibility/src/main/java/test/Log4j13Calls.java +++ b/log4j-over-slf4j/compatibility/src/main/java/test/Log4j13Calls.java @@ -1,46 +1,46 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * - * Copyright (C) 1999-2006, QOS.ch - * - * This library is free software, you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation. - */ - -package test; - -import junit.framework.TestCase; - -import org.apache.log4j.Logger; -import org.apache.log4j.MDC; - -/** - * - * A test case that issues the typical calls - * that an application using log4j 1.3 would do. - * - * @author Ceki Gülcü - * @author Sébastien Pennec - */ - -public class Log4j13Calls extends TestCase { - public static final Logger logger = Logger.getLogger(Log4j12Calls.class); - - public void testLog() { - MDC.put("key", "value1"); - - logger.trace("Trace level can be noisy"); - logger.debug("Entering application"); - logger.info("Violets are blue"); - logger.warn("Here is a warning"); - logger.info("The answer is {}.", new Integer(42)); - logger.info("Number: {} and another one: {}.", new Integer(42), new Integer(24)); - - logger.error("Exiting application", new Exception("just testing")); - - MDC.remove("key"); - - MDC.clear(); - } -} +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * + * Copyright (C) 1999-2006, QOS.ch + * + * This library is free software, you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation. + */ + +package test; + +import junit.framework.TestCase; + +import org.apache.log4j.Logger; +import org.apache.log4j.MDC; + +/** + * + * A test case that issues the typical calls + * that an application using log4j 1.3 would do. + * + * @author Ceki Gülcü + * @author Sébastien Pennec + */ + +public class Log4j13Calls extends TestCase { + public static final Logger logger = Logger.getLogger(Log4j12Calls.class); + + public void testLog() { + MDC.put("key", "value1"); + + logger.trace("Trace level can be noisy"); + logger.debug("Entering application"); + logger.info("Violets are blue"); + logger.warn("Here is a warning"); + logger.info("The answer is {}.", new Integer(42)); + logger.info("Number: {} and another one: {}.", new Integer(42), new Integer(24)); + + logger.error("Exiting application", new Exception("just testing")); + + MDC.remove("key"); + + MDC.clear(); + } +} diff --git a/log4j-over-slf4j/compatibility/src/main/java/test/LoggerTest.java b/log4j-over-slf4j/compatibility/src/main/java/test/LoggerTest.java index 61c5a79c..29c8a46b 100644 --- a/log4j-over-slf4j/compatibility/src/main/java/test/LoggerTest.java +++ b/log4j-over-slf4j/compatibility/src/main/java/test/LoggerTest.java @@ -1,169 +1,169 @@ -package test; - -import junit.framework.TestCase; - -import org.slf4j.LoggerFactory; - -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.spi.LoggingEvent; -import ch.qos.logback.core.read.ListAppender; -import org.apache.log4j.Level; - -/** - * A class that tests the invocation of the org.apache.log4j.Logger class that - * belongs to the log4j-bridge package - * - * @author Sébastien Pennec - * @author Ceki Gülcü - */ - -public class LoggerTest extends TestCase { - - LoggerContext context; - ListAppender appender; - ch.qos.logback.classic.Logger logbackLogger; - org.apache.log4j.Logger log4jLogger; - - public void setUp() throws Exception { - context = (LoggerContext) LoggerFactory.getILoggerFactory(); - context.shutdownAndReset(); - appender = new ListAppender(); - appender.setContext(context); - appender.setName("listAppender"); - appender.start(); - ch.qos.logback.classic.Logger lbLogger = context - .getLogger(LoggerContext.ROOT_NAME); - lbLogger.addAppender(appender); - - log4jLogger = org.apache.log4j.Logger.getLogger(LoggerTest.class); - logbackLogger = context.getLogger(LoggerTest.class); - super.setUp(); - } - - public void tearDown() throws Exception { - appender.stop(); - context.stop(); - appender = null; - context = null; - logbackLogger = null; - log4jLogger = null; - super.tearDown(); - } - - public void testLogWithObjectMessages() { - LoggingEvent event; - - log4jLogger.debug("test"); - event = appender.list.get(0); - assertEquals("test", event.getMessage()); - appender.list.clear(); - - log4jLogger.debug(null); - event = appender.list.get(0); - assertEquals(null, event.getMessage()); - appender.list.clear(); - - DummyObject dummy = new DummyObject(); - log4jLogger.debug(dummy); - event = appender.list.get(0); - assertEquals(dummy.toString(), event.getMessage()); - appender.list.clear(); - } - - public void testIsEnabledAPI() { - assertFalse(log4jLogger.isTraceEnabled()); - assertTrue(log4jLogger.isDebugEnabled()); - assertTrue(log4jLogger.isInfoEnabled()); - assertTrue(log4jLogger.isWarnEnabled()); - assertTrue(log4jLogger.isErrorEnabled()); - } - - public void testPrintAPI() { - Exception e = new Exception("just testing"); - - log4jLogger.trace(null); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.debug(null); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.debug("debug message"); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.info(null); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.info("info message"); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.warn(null); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.warn("warn message"); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.error(null); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.error("error message"); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.debug(null, e); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.debug("debug message", e); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.info(null, e); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.info("info message", e); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.warn(null, e); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.warn("warn message", e); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.error(null, e); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - log4jLogger.error("error message", e); - assertEquals(1, appender.list.size()); - appender.list.clear(); - - } - - public void testLogAPI() { - log4jLogger.log("x", Level.TRACE, "x", null); - assertEquals(0, appender.list.size()); - - log4jLogger.log("x", Level.DEBUG, "x", null); - log4jLogger.log("x", Level.INFO, "x", null); - log4jLogger.log("x", Level.WARN, "x", null); - log4jLogger.log("x", Level.ERROR, "x", null); - log4jLogger.log("x", Level.FATAL, "x", null); - - assertEquals(5, appender.list.size()); - appender.list.clear(); - - } - -} +package test; + +import junit.framework.TestCase; + +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import org.apache.log4j.Level; + +/** + * A class that tests the invocation of the org.apache.log4j.Logger class that + * belongs to the log4j-bridge package + * + * @author Sébastien Pennec + * @author Ceki Gülcü + */ + +public class LoggerTest extends TestCase { + + LoggerContext context; + ListAppender appender; + ch.qos.logback.classic.Logger logbackLogger; + org.apache.log4j.Logger log4jLogger; + + public void setUp() throws Exception { + context = (LoggerContext) LoggerFactory.getILoggerFactory(); + context.shutdownAndReset(); + appender = new ListAppender(); + appender.setContext(context); + appender.setName("listAppender"); + appender.start(); + ch.qos.logback.classic.Logger lbLogger = context + .getLogger(LoggerContext.ROOT_NAME); + lbLogger.addAppender(appender); + + log4jLogger = org.apache.log4j.Logger.getLogger(LoggerTest.class); + logbackLogger = context.getLogger(LoggerTest.class); + super.setUp(); + } + + public void tearDown() throws Exception { + appender.stop(); + context.stop(); + appender = null; + context = null; + logbackLogger = null; + log4jLogger = null; + super.tearDown(); + } + + public void testLogWithObjectMessages() { + LoggingEvent event; + + log4jLogger.debug("test"); + event = appender.list.get(0); + assertEquals("test", event.getMessage()); + appender.list.clear(); + + log4jLogger.debug(null); + event = appender.list.get(0); + assertEquals(null, event.getMessage()); + appender.list.clear(); + + DummyObject dummy = new DummyObject(); + log4jLogger.debug(dummy); + event = appender.list.get(0); + assertEquals(dummy.toString(), event.getMessage()); + appender.list.clear(); + } + + public void testIsEnabledAPI() { + assertFalse(log4jLogger.isTraceEnabled()); + assertTrue(log4jLogger.isDebugEnabled()); + assertTrue(log4jLogger.isInfoEnabled()); + assertTrue(log4jLogger.isWarnEnabled()); + assertTrue(log4jLogger.isErrorEnabled()); + } + + public void testPrintAPI() { + Exception e = new Exception("just testing"); + + log4jLogger.trace(null); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.debug(null); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.debug("debug message"); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.info(null); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.info("info message"); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.warn(null); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.warn("warn message"); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.error(null); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.error("error message"); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.debug(null, e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.debug("debug message", e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.info(null, e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.info("info message", e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.warn(null, e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.warn("warn message", e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.error(null, e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + log4jLogger.error("error message", e); + assertEquals(1, appender.list.size()); + appender.list.clear(); + + } + + public void testLogAPI() { + log4jLogger.log("x", Level.TRACE, "x", null); + assertEquals(0, appender.list.size()); + + log4jLogger.log("x", Level.DEBUG, "x", null); + log4jLogger.log("x", Level.INFO, "x", null); + log4jLogger.log("x", Level.WARN, "x", null); + log4jLogger.log("x", Level.ERROR, "x", null); + log4jLogger.log("x", Level.FATAL, "x", null); + + assertEquals(5, appender.list.size()); + appender.list.clear(); + + } + +} diff --git a/log4j-over-slf4j/pom.xml b/log4j-over-slf4j/pom.xml index afe2dc03..9cd2586b 100644 --- a/log4j-over-slf4j/pom.xml +++ b/log4j-over-slf4j/pom.xml @@ -1,68 +1,68 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - log4j-over-slf4j - jar - Log4j Implemented Over SLF4J - - http://www.slf4j.org - - - - Log4j implemented over SLF4J - - - - Apache Software Licenses - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - - org.slf4j - slf4j-api - - - - org.slf4j - slf4j-jdk14 - test - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - ${parsedVersion.osgiVersion} - ${project.description} - ${project.version} - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + log4j-over-slf4j + jar + Log4j Implemented Over SLF4J + + http://www.slf4j.org + + + + Log4j implemented over SLF4J + + + + Apache Software Licenses + http://www.apache.org/licenses/LICENSE-2.0.txt + + + + + + org.slf4j + slf4j-api + + + + org.slf4j + slf4j-jdk14 + test + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + ${parsedVersion.osgiVersion} + ${project.description} + ${project.version} + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + + \ No newline at end of file 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 175aa7d9..c85e7b26 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Category.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Category.java @@ -1,335 +1,335 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.log4j; - -import org.slf4j.LoggerFactory; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; -import org.slf4j.spi.LocationAwareLogger; - -/** - *

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

- * - *

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

- * The result is computed by simulation. - * - * @return - */ - public Level getEffectiveLevel() { - if (slf4jLogger.isTraceEnabled()) { - return Level.TRACE; - } - if (slf4jLogger.isDebugEnabled()) { - return Level.DEBUG; - } - if (slf4jLogger.isInfoEnabled()) { - return Level.INFO; - } - if (slf4jLogger.isWarnEnabled()) { - return Level.WARN; - } - return Level.ERROR; - } - - /** - * Returns the assigned {@link Level}, if any, for this Category. This - * implementation always returns null. - * - * @return Level - the assigned Level, can be null. - */ - final public Level getLevel() { - return null; - } - - /** - * @deprecated Please use {@link #getLevel} instead. - */ - final public Level getPriority() { - return null; - } - - /** - * Delegates to {@link org.slf4j.Logger#isDebugEnabled} method in SLF4J - */ - public boolean isDebugEnabled() { - return slf4jLogger.isDebugEnabled(); - } - - /** - * Delegates to {@link org.slf4j.Logger#isInfoEnabled} method in SLF4J - */ - public boolean isInfoEnabled() { - return slf4jLogger.isInfoEnabled(); - } - - /** - * Delegates 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, 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); - } - - - public void log(String FQCN, Priority p, Object msg, Throwable t) { - int levelInt = priorityToLevelInt(p); - if (locationAwareLogger != null) { - locationAwareLogger.log(null, FQCN, levelInt, convertToString(msg), t); - } else { - throw new UnsupportedOperationException("The logger [" + slf4jLogger - + "] does not seem to be location aware."); - } - } - - 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: - 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(); - } - } - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.log4j; + +import org.slf4j.LoggerFactory; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; +import org.slf4j.spi.LocationAwareLogger; + +/** + *

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

+ * + *

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

+ * The result is computed by simulation. + * + * @return + */ + public Level getEffectiveLevel() { + if (slf4jLogger.isTraceEnabled()) { + return Level.TRACE; + } + if (slf4jLogger.isDebugEnabled()) { + return Level.DEBUG; + } + if (slf4jLogger.isInfoEnabled()) { + return Level.INFO; + } + if (slf4jLogger.isWarnEnabled()) { + return Level.WARN; + } + return Level.ERROR; + } + + /** + * Returns the assigned {@link Level}, if any, for this Category. This + * implementation always returns null. + * + * @return Level - the assigned Level, can be null. + */ + final public Level getLevel() { + return null; + } + + /** + * @deprecated Please use {@link #getLevel} instead. + */ + final public Level getPriority() { + return null; + } + + /** + * Delegates to {@link org.slf4j.Logger#isDebugEnabled} method in SLF4J + */ + public boolean isDebugEnabled() { + return slf4jLogger.isDebugEnabled(); + } + + /** + * Delegates to {@link org.slf4j.Logger#isInfoEnabled} method in SLF4J + */ + public boolean isInfoEnabled() { + return slf4jLogger.isInfoEnabled(); + } + + /** + * Delegates 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, 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); + } + + + public void log(String FQCN, Priority p, Object msg, Throwable t) { + int levelInt = priorityToLevelInt(p); + if (locationAwareLogger != null) { + locationAwareLogger.log(null, FQCN, levelInt, convertToString(msg), t); + } else { + throw new UnsupportedOperationException("The logger [" + slf4jLogger + + "] does not seem to be location aware."); + } + } + + 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: + 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(); + } + } + +} 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 18731b73..36ae5718 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Level.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Level.java @@ -1,218 +1,218 @@ -/* - * Copyright 1999-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Contributors: Kitching Simon -// Nicholas Wolff - -package org.apache.log4j; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamException; -import java.io.Serializable; - -/** - Defines the minimum set of levels recognized by the system, that is - OFF, FATAL, ERROR, - WARN, INFO, DEBUG and - ALL. - -

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

The Level class may be subclassed to define a larger + level set. + + @author Ceki Gülcü + + */ +public class Level extends Priority implements Serializable { + + /** + * TRACE level integer value. + * @since 1.2.12 + */ + public static final int TRACE_INT = 5000; + + /** + The OFF has the highest possible rank and is + intended to turn off logging. */ + final static public Level OFF = new Level(OFF_INT, "OFF", 0); + + /** + The FATAL level designates very severe error + events that will presumably lead the application to abort. + */ + final static public Level FATAL = new Level(FATAL_INT, "FATAL", 0); + + /** + The ERROR level designates error events that + might still allow the application to continue running. */ + final static public Level ERROR = new Level(ERROR_INT, "ERROR", 3); + + /** + The WARN level designates potentially harmful situations. + */ + final static public Level WARN = new Level(WARN_INT, "WARN", 4); + + /** + The INFO level designates informational messages + that highlight the progress of the application at coarse-grained + level. */ + final static public Level INFO = new Level(INFO_INT, "INFO", 6); + + /** + The DEBUG Level designates fine-grained + informational events that are most useful to debug an + application. */ + final static public Level DEBUG = new Level(DEBUG_INT, "DEBUG", 7); + + /** + * The TRACE Level designates finer-grained + * informational events than the DEBUGALL has the lowest possible rank and is intended to + turn on all logging. */ + final static public Level ALL = new Level(ALL_INT, "ALL", 7); + + /** + * Serialization version id. + */ + static final long serialVersionUID = 3491141966387921974L; + + /** + Instantiate a Level object. + */ + protected + Level(int level, String levelStr, int syslogEquivalent) { + super(level, levelStr, syslogEquivalent); + } + + + /** + Convert the string passed as argument to a level. If the + conversion fails, then this method returns {@link #DEBUG}. + */ + public + static + Level toLevel(String sArg) { + return (Level) toLevel(sArg, Level.DEBUG); + } + + /** + Convert an integer passed as argument to a level. If the + conversion fails, then this method returns {@link #DEBUG}. + + */ + public + static + Level toLevel(int val) { + return (Level) toLevel(val, Level.DEBUG); + } + + /** + Convert an integer passed as argument to a level. If the + conversion fails, then this method returns the specified default. + */ + public + static + Level toLevel(int val, Level defaultLevel) { + switch(val) { + case ALL_INT: return ALL; + case DEBUG_INT: return Level.DEBUG; + case INFO_INT: return Level.INFO; + case WARN_INT: return Level.WARN; + case ERROR_INT: return Level.ERROR; + case FATAL_INT: return Level.FATAL; + case OFF_INT: return OFF; + case TRACE_INT: return Level.TRACE; + default: return defaultLevel; + } + } + + /** + Convert the string passed as argument to a level. If the + conversion fails, then this method returns the value of + defaultLevel. + */ + public + static + Level toLevel(String sArg, Level defaultLevel) { + if(sArg == null) + return defaultLevel; + + String s = sArg.toUpperCase(); + + if(s.equals("ALL")) return Level.ALL; + if(s.equals("DEBUG")) return Level.DEBUG; + if(s.equals("INFO")) return Level.INFO; + if(s.equals("WARN")) return Level.WARN; + if(s.equals("ERROR")) return Level.ERROR; + if(s.equals("FATAL")) return Level.FATAL; + if(s.equals("OFF")) return Level.OFF; + if(s.equals("TRACE")) return Level.TRACE; + return defaultLevel; + } + + /** + * Custom deserialization of Level. + * @param s serialization stream. + * @throws IOException if IO exception. + * @throws ClassNotFoundException if class not found. + */ + private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException { + s.defaultReadObject(); + level = s.readInt(); + syslogEquivalent = s.readInt(); + levelStr = s.readUTF(); + if (levelStr == null) { + levelStr = ""; + } + } + + /** + * Serialize level. + * @param s serialization stream. + * @throws IOException if exception during serialization. + */ + private void writeObject(final ObjectOutputStream s) throws IOException { + s.defaultWriteObject(); + s.writeInt(level); + s.writeInt(syslogEquivalent); + s.writeUTF(levelStr); + } + + /** + * Resolved deserialized level to one of the stock instances. + * May be overriden in classes derived from Level. + * @return resolved object. + * @throws ObjectStreamException if exception during resolution. + */ + private Object readResolve() throws ObjectStreamException { + // + // 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 + // + return this; + } } \ No newline at end of file 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 0f925ad0..fb3a70e3 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Log4jLoggerFactory.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Log4jLoggerFactory.java @@ -1,46 +1,46 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -import java.util.Hashtable; - -/** - * This class is a factory that creates and maintains org.apache.log4j.Loggers - * wrapping org.slf4j.Loggers. - * - * It keeps a hashtable of all created org.apache.log4j.Logger instances so that - * all newly created instances are not dulpicates of existing loggers. - * - * @author Sébastien Pennec - */ -class Log4jLoggerFactory { - - // String, Logger - private static Hashtable log4jLoggers = new Hashtable(); - - public static synchronized Logger getLogger(String name) { - if (log4jLoggers.containsKey(name)) { - return (org.apache.log4j.Logger) log4jLoggers.get(name); - } else { - Logger log4jLogger = new Logger(name); - - log4jLoggers.put(name, log4jLogger); - return log4jLogger; - } - } - -} +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.log4j; + +import java.util.Hashtable; + +/** + * This class is a factory that creates and maintains org.apache.log4j.Loggers + * wrapping org.slf4j.Loggers. + * + * It keeps a hashtable of all created org.apache.log4j.Logger instances so that + * all newly created instances are not dulpicates of existing loggers. + * + * @author Sébastien Pennec + */ +class Log4jLoggerFactory { + + // String, Logger + private static Hashtable log4jLoggers = new Hashtable(); + + public static synchronized Logger getLogger(String name) { + if (log4jLoggers.containsKey(name)) { + return (org.apache.log4j.Logger) log4jLoggers.get(name); + } else { + Logger log4jLogger = new Logger(name); + + log4jLoggers.put(name, log4jLogger); + return log4jLogger; + } + } + +} 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 5fed6b29..3c498be3 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/LogManager.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/LogManager.java @@ -1,45 +1,45 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.log4j; - -/** - *

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

- * This implementation does NOT implement the setRepositorySelector(), - * getLoggerRepository(), exists(), getCurrentLoggers(), shutdown() and - * resetConfiguration() methods which do not have SLF4J equivalents. - * - * @author Ceki Gülcü - * */ -public class LogManager { - - public static Logger getRootLogger() { - return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); - } - - public static Logger getLogger(final String name) { - return Log4jLoggerFactory.getLogger(name); - } - - public static Logger getLogger(final Class clazz) { - return Log4jLoggerFactory.getLogger(clazz.getName()); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.log4j; + +/** + *

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

+ * This implementation does NOT implement the setRepositorySelector(), + * getLoggerRepository(), exists(), getCurrentLoggers(), shutdown() and + * resetConfiguration() methods which do not have SLF4J equivalents. + * + * @author Ceki Gülcü + * */ +public class LogManager { + + public static Logger getRootLogger() { + return Log4jLoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + } + + public static Logger getLogger(final String name) { + return Log4jLoggerFactory.getLogger(name); + } + + public static Logger getLogger(final Class clazz) { + return Log4jLoggerFactory.getLogger(clazz.getName()); + } +} 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 47bffc34..483de04f 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Logger.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Logger.java @@ -1,79 +1,79 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.log4j; - -import org.slf4j.spi.LocationAwareLogger; - -/** - *

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

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

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

+ * + * @author Ceki Gülcü + * */ +public class Logger extends Category { + + private static final String LOGGER_FQCN = Logger.class.getName(); + + Logger(String name) { + super(name); + } + + public static Logger getLogger(String name) { + return Log4jLoggerFactory.getLogger(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); + } + + + /** + * 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 e5b4bd5b..c8187930 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/MDC.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/MDC.java @@ -1,28 +1,28 @@ -package org.apache.log4j; - -public class MDC { - - public static void put(String key, String value) { - org.slf4j.MDC.put(key, value); - } - - public static void put(String key, Object value) { - if (value != null) { - put(key, value.toString()); - } else { - put(key, null); - } - } - - public static Object get(String key) { - return org.slf4j.MDC.get(key); - } - - public static void remove(String key) { - org.slf4j.MDC.remove(key); - } - - public static void clear() { - org.slf4j.MDC.clear(); - } -} +package org.apache.log4j; + +public class MDC { + + public static void put(String key, String value) { + org.slf4j.MDC.put(key, value); + } + + public static void put(String key, Object value) { + if (value != null) { + put(key, value.toString()); + } else { + put(key, null); + } + } + + public static Object get(String key) { + return org.slf4j.MDC.get(key); + } + + public static void remove(String key) { + org.slf4j.MDC.remove(key); + } + + public static void clear() { + org.slf4j.MDC.clear(); + } +} 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 4d4e8f1c..eac27338 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/Priority.java +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/Priority.java @@ -1,194 +1,194 @@ -/* - * Copyright 1999-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Contributors: Kitching Simon - -package org.apache.log4j; - -// Contributors: Kitching Simon - -/** - Refrain from using this class directly, use - the {@link Level} class instead. - - @author Ceki Gülcü */ -public class Priority { - - transient int level; - transient String levelStr; - transient int syslogEquivalent; - - public final static int OFF_INT = Integer.MAX_VALUE; - public final static int FATAL_INT = 50000; - public final static int ERROR_INT = 40000; - public final static int WARN_INT = 30000; - public final static int INFO_INT = 20000; - public final static int DEBUG_INT = 10000; - //public final static int FINE_INT = DEBUG_INT; - public final static int ALL_INT = Integer.MIN_VALUE; - - /** - * @deprecated Use {@link Level#FATAL} instead. - */ - final static public Priority FATAL = new Level(FATAL_INT, "FATAL", 0); - - /** - * @deprecated Use {@link Level#ERROR} instead. - */ - final static public Priority ERROR = new Level(ERROR_INT, "ERROR", 3); - - /** - * @deprecated Use {@link Level#WARN} instead. - */ - final static public Priority WARN = new Level(WARN_INT, "WARN", 4); - - /** - * @deprecated Use {@link Level#INFO} instead. - */ - final static public Priority INFO = new Level(INFO_INT, "INFO", 6); - - /** - * @deprecated Use {@link Level#DEBUG} instead. - */ - final static public Priority DEBUG = new Level(DEBUG_INT, "DEBUG", 7); - - - /** - * Default constructor for deserialization. - */ - protected Priority() { - level = DEBUG_INT; - levelStr = "DEBUG"; - syslogEquivalent = 7; - } - - /** - Instantiate a level object. - */ - protected - Priority(int level, String levelStr, int syslogEquivalent) { - this.level = level; - this.levelStr = levelStr; - this.syslogEquivalent = syslogEquivalent; - } - - /** - Two priorities are equal if their level fields are equal. - @since 1.2 - */ - public - boolean equals(Object o) { - if(o instanceof Priority) { - Priority r = (Priority) o; - return (this.level == r.level); - } else { - return false; - } - } - - /** - Return the syslog equivalent of this priority as an integer. - */ - public - final - int getSyslogEquivalent() { - return syslogEquivalent; - } - - - - /** - Returns true if this level has a higher or equal - level than the level passed as argument, false - otherwise. - -

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

You should think twice before overriding the default + implementation of isGreaterOrEqual method. + + */ + public + boolean isGreaterOrEqual(Priority r) { + return level >= r.level; + } + + /** + Return all possible priorities as an array of Level objects in + descending order. + + @deprecated This method will be removed with no replacement. + */ + public + static + Priority[] getAllPossiblePriorities() { + return new Priority[] {Priority.FATAL, Priority.ERROR, Level.WARN, + Priority.INFO, Priority.DEBUG}; + } + + + /** + Returns the string representation of this priority. + */ + final + public + String toString() { + return levelStr; + } + + /** + Returns the integer representation of this level. + */ + public + final + int toInt() { + return level; + } + + /** + * @deprecated Please use the {@link Level#toLevel(String)} method instead. + */ + public + static + Priority toPriority(String sArg) { + return Level.toLevel(sArg); + } + + /** + * @deprecated Please use the {@link Level#toLevel(int)} method instead. + */ + public + static + Priority toPriority(int val) { + return toPriority(val, Priority.DEBUG); + } + + /** + * @deprecated Please use the {@link Level#toLevel(int, Level)} method instead. + */ + public + static + Priority toPriority(int val, Priority defaultPriority) { + return Level.toLevel(val, (Level) defaultPriority); + } + + /** + * @deprecated Please use the {@link Level#toLevel(String, Level)} method instead. + */ + public + static + Priority toPriority(String sArg, Priority defaultPriority) { + return Level.toLevel(sArg, (Level) defaultPriority); + } } \ No newline at end of file diff --git a/log4j-over-slf4j/src/main/java/org/apache/log4j/package.html b/log4j-over-slf4j/src/main/java/org/apache/log4j/package.html index 357d0e66..c3c83469 100644 --- a/log4j-over-slf4j/src/main/java/org/apache/log4j/package.html +++ b/log4j-over-slf4j/src/main/java/org/apache/log4j/package.html @@ -1,18 +1,18 @@ - - - - - - - - - - - -

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

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

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

+ + + + + diff --git a/log4j-over-slf4j/src/main/resources/META-INF/MANIFEST.MF b/log4j-over-slf4j/src/main/resources/META-INF/MANIFEST.MF index 7d575ff6..bc459b6c 100644 --- a/log4j-over-slf4j/src/main/resources/META-INF/MANIFEST.MF +++ b/log4j-over-slf4j/src/main/resources/META-INF/MANIFEST.MF @@ -1,6 +1,6 @@ -Implementation-Title: log4j-over-slf4j -Bundle-SymbolicName: log4j.over.slf4j -Bundle-Name: log4j-over-slf4j -Bundle-Vendor: SLF4J.ORG -Export-Package: org.apache.log4j -Import-Package: org.slf4j, org.slf4j.spi +Implementation-Title: log4j-over-slf4j +Bundle-SymbolicName: log4j.over.slf4j +Bundle-Name: log4j-over-slf4j +Bundle-Vendor: SLF4J.ORG +Export-Package: org.apache.log4j +Import-Package: org.slf4j, org.slf4j.spi 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 2ed0cda9..f94b57c9 100644 --- a/log4j-over-slf4j/src/test/java/org/apache/log4j/Trivial.java +++ b/log4j-over-slf4j/src/test/java/org/apache/log4j/Trivial.java @@ -1,51 +1,51 @@ -/* - * Copyright (c) 2004-2009 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.apache.log4j; - -import org.apache.log4j.Logger; - -import junit.framework.TestCase; - -public class Trivial extends TestCase { - - public void testSmoke() { - Logger l = Logger.getLogger("a"); - l.trace("t"); - l.debug("d"); - l.info("i"); - l.warn("w"); - l.error("e"); - l.fatal("f"); - - Exception e = new Exception("testing"); - l.trace("t", e); - l.debug("d", e); - l.info("i", e); - l.warn("w", e); - l.error("e", e); - l.fatal("f", e); - } - -} +/* + * Copyright (c) 2004-2009 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.apache.log4j; + +import org.apache.log4j.Logger; + +import junit.framework.TestCase; + +public class Trivial extends TestCase { + + public void testSmoke() { + Logger l = Logger.getLogger("a"); + l.trace("t"); + l.debug("d"); + l.info("i"); + l.warn("w"); + l.error("e"); + l.fatal("f"); + + Exception e = new Exception("testing"); + l.trace("t", e); + l.debug("d", e); + l.info("i", e); + l.warn("w", e); + l.error("e", e); + l.fatal("f", e); + } + +} diff --git a/log4j-over-slf4j/src/test/java/org/dummy/Bug131.java b/log4j-over-slf4j/src/test/java/org/dummy/Bug131.java index 5f192921..13da1b40 100644 --- a/log4j-over-slf4j/src/test/java/org/dummy/Bug131.java +++ b/log4j-over-slf4j/src/test/java/org/dummy/Bug131.java @@ -1,68 +1,68 @@ -/* - * Copyright (c) 2004-2009 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.dummy; - -import java.util.logging.Level; -import java.util.logging.LogRecord; - -import junit.framework.TestCase; - -import org.apache.log4j.Category; -import org.apache.log4j.Logger; - -public class Bug131 extends TestCase { - - public void testBug131() { - - ListHandler listHandler = new ListHandler(); - java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); - root.addHandler(listHandler); - root.setLevel(Level.FINEST); - Logger log4jLogger = Logger.getLogger("a"); - Category log4jCategory = Logger.getLogger("b"); - - int n = 0; - - log4jLogger.trace("msg" +(n++)); - log4jLogger.debug("msg" +(n++)); - log4jLogger.info("msg" +(n++)); - log4jLogger.warn("msg" +(n++)); - log4jLogger.error("msg" +(n++)); - log4jLogger.fatal("msg" +(n++)); - - log4jCategory.debug("msg" +(n++)); - log4jCategory.info("msg" +(n++)); - log4jCategory.warn("msg" +(n++)); - log4jCategory.error("msg" +(n++)); - log4jCategory.fatal("msg" +(n++)); - - assertEquals(n, listHandler.list.size()); - - for(int i = 0; i < n; i++) { - LogRecord logRecord = (LogRecord) listHandler.list.get(i); - assertEquals("testBug131", logRecord.getSourceMethodName()); - } - } -} +/* + * Copyright (c) 2004-2009 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.dummy; + +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import junit.framework.TestCase; + +import org.apache.log4j.Category; +import org.apache.log4j.Logger; + +public class Bug131 extends TestCase { + + public void testBug131() { + + ListHandler listHandler = new ListHandler(); + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); + root.addHandler(listHandler); + root.setLevel(Level.FINEST); + Logger log4jLogger = Logger.getLogger("a"); + Category log4jCategory = Logger.getLogger("b"); + + int n = 0; + + log4jLogger.trace("msg" +(n++)); + log4jLogger.debug("msg" +(n++)); + log4jLogger.info("msg" +(n++)); + log4jLogger.warn("msg" +(n++)); + log4jLogger.error("msg" +(n++)); + log4jLogger.fatal("msg" +(n++)); + + log4jCategory.debug("msg" +(n++)); + log4jCategory.info("msg" +(n++)); + log4jCategory.warn("msg" +(n++)); + log4jCategory.error("msg" +(n++)); + log4jCategory.fatal("msg" +(n++)); + + assertEquals(n, listHandler.list.size()); + + for(int i = 0; i < n; i++) { + LogRecord logRecord = (LogRecord) listHandler.list.get(i); + assertEquals("testBug131", logRecord.getSourceMethodName()); + } + } +} diff --git a/log4j-over-slf4j/src/test/java/org/dummy/Bug139.java b/log4j-over-slf4j/src/test/java/org/dummy/Bug139.java index a15cdb5d..5e02d089 100644 --- a/log4j-over-slf4j/src/test/java/org/dummy/Bug139.java +++ b/log4j-over-slf4j/src/test/java/org/dummy/Bug139.java @@ -1,57 +1,57 @@ -/* - * Copyright (c) 2004-2009 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.dummy; - -import java.util.logging.Level; -import java.util.logging.LogRecord; - -import junit.framework.TestCase; - -import org.apache.log4j.Category; -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"); - - int n = 0; - - log4jLogger.log(org.apache.log4j.Level.DEBUG, "hello"+(++n)); - log4jCategory.log(org.apache.log4j.Level.DEBUG, "world"+(++n)); - - assertEquals(n, listHandler.list.size()); - - for (int i = 0; i < n; i++) { - LogRecord logRecord = (LogRecord) listHandler.list.get(i); - assertEquals("test", logRecord.getSourceMethodName()); - } - } -} +/* + * Copyright (c) 2004-2009 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.dummy; + +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import junit.framework.TestCase; + +import org.apache.log4j.Category; +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"); + + int n = 0; + + log4jLogger.log(org.apache.log4j.Level.DEBUG, "hello"+(++n)); + log4jCategory.log(org.apache.log4j.Level.DEBUG, "world"+(++n)); + + assertEquals(n, listHandler.list.size()); + + for (int i = 0; i < n; i++) { + LogRecord logRecord = (LogRecord) listHandler.list.get(i); + assertEquals("test", logRecord.getSourceMethodName()); + } + } +} diff --git a/log4j-over-slf4j/src/test/java/org/dummy/ListHandler.java b/log4j-over-slf4j/src/test/java/org/dummy/ListHandler.java index 194a3ab0..83df77e0 100644 --- a/log4j-over-slf4j/src/test/java/org/dummy/ListHandler.java +++ b/log4j-over-slf4j/src/test/java/org/dummy/ListHandler.java @@ -1,25 +1,25 @@ -package org.dummy; - -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Handler; -import java.util.logging.LogRecord; - -public class ListHandler extends Handler { - - List list = new ArrayList(); - - public void close() throws SecurityException { - - } - - public void flush() { - - } - - public void publish(LogRecord logRecord) { - logRecord.getSourceClassName(); - list.add(logRecord); - } - -} +package org.dummy; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Handler; +import java.util.logging.LogRecord; + +public class ListHandler extends Handler { + + List list = new ArrayList(); + + public void close() throws SecurityException { + + } + + public void flush() { + + } + + public void publish(LogRecord logRecord) { + logRecord.getSourceClassName(); + list.add(logRecord); + } + +} diff --git a/slf4j-api/LICENSE.txt b/slf4j-api/LICENSE.txt index f6e2f31f..508a2728 100644 --- a/slf4j-api/LICENSE.txt +++ b/slf4j-api/LICENSE.txt @@ -1,24 +1,24 @@ -Copyright (c) 2004-2007 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-api/pom.xml b/slf4j-api/pom.xml index 299a05be..e93733d7 100644 --- a/slf4j-api/pom.xml +++ b/slf4j-api/pom.xml @@ -1,101 +1,101 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - slf4j-api - jar - SLF4J API Module - - http://www.slf4j.org - The slf4j API - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - once - plain - false - - **/AllTest.java - **/PackageTest.java - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - ${parsedVersion.osgiVersion} - ${project.description} - ${project.version} - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - bundle-test-jar - package - - jar - test-jar - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - process-classes - - run - - - - - - Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder - - - - - - - - - - - - - org.codehaus.mojo - clirr-maven-plugin - - 1.5.6 - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + slf4j-api + jar + SLF4J API Module + + http://www.slf4j.org + The slf4j API + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + once + plain + false + + **/AllTest.java + **/PackageTest.java + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + ${parsedVersion.osgiVersion} + ${project.description} + ${project.version} + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + bundle-test-jar + package + + jar + test-jar + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + process-classes + + run + + + + + + Removing slf4j-api's dummy StaticLoggerBinder and StaticMarkerBinder + + + + + + + + + + + + + org.codehaus.mojo + clirr-maven-plugin + + 1.5.6 + + + + + \ No newline at end of file diff --git a/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java b/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java index 26e7a554..851b60ca 100644 --- a/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/ILoggerFactory.java @@ -1,57 +1,57 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j; - - -/** - * ILoggerFactory instances manufacture {@link Logger} - * instances by name. - * - *

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

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

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

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

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

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

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

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

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

Null name values are not allowed. - * - * @param name the name of the marker to be created, null value is - * not allowed. - * - * @return a Marker instance - */ - Marker getMarker(String name); - - /** - * Checks if the marker with the name already exists. If name is null, then false - * is returned. - * - * @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. - * - * @return a dangling marker - * @since 1.5.1 - */ - Marker getDetachedMarker(String name); -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j; + + +/** + * Implementaitons of this interface are used to manufacture {@link Marker} + * instances. + * + *

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

Null name values are not allowed. + * + * @param name the name of the marker to be created, null value is + * not allowed. + * + * @return a Marker instance + */ + Marker getMarker(String name); + + /** + * Checks if the marker with the name already exists. If name is null, then false + * is returned. + * + * @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. + * + * @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 e2e99a51..13efdcd5 100644 --- a/slf4j-api/src/main/java/org/slf4j/Logger.java +++ b/slf4j-api/src/main/java/org/slf4j/Logger.java @@ -1,721 +1,721 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - - -package org.slf4j; - -/** - * The org.slf4j.Logger interface is the main user entry point of SLF4J API. - * It is expected that logging takes place through concrete implementations - * of this interface. - * - *

Typical usage pattern:

- *
- * import org.slf4j.Logger;
- * import org.slf4j.LoggerFactory;
- * 
- * public class Wombat {
- *
- *   final static Logger logger = LoggerFactory.getLogger(Wombat.class);
- *   Integer t;
- *   Integer oldT;
- *
- *   public void setTemperature(Integer temperature) {
- *     oldT = t;        
- *     t = temperature;
- *     logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);
- *     if(temperature.intValue() > 50) {
- *       logger.info("Temperature has risen above 50 degrees.");
- *     }
- *   }
- * }
- 
- - - - * @author Ceki Gülcü - */ -public interface Logger { - - - /** - * Case insensitive String constant used to retrieve the name of the root logger. - * @since 1.3 - */ - final public String ROOT_LOGGER_NAME = "ROOT"; - - /** - * Return the name of this Logger instance. - */ - 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 object creation when the logger - * is disabled for the TRACE level.

- * - * @param format the format string - * @param argArray an array of arguments - * - * @since 1.4 - */ - public void trace(String format, Object[] argArray); - - /** - * 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 - * - * @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 object creation when the logger - * is disabled for the DEBUG level.

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

Typical usage pattern:

+ *
+ * import org.slf4j.Logger;
+ * import org.slf4j.LoggerFactory;
+ * 
+ * public class Wombat {
+ *
+ *   final static Logger logger = LoggerFactory.getLogger(Wombat.class);
+ *   Integer t;
+ *   Integer oldT;
+ *
+ *   public void setTemperature(Integer temperature) {
+ *     oldT = t;        
+ *     t = temperature;
+ *     logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);
+ *     if(temperature.intValue() > 50) {
+ *       logger.info("Temperature has risen above 50 degrees.");
+ *     }
+ *   }
+ * }
+ 
+ + + + * @author Ceki Gülcü + */ +public interface Logger { + + + /** + * Case insensitive String constant used to retrieve the name of the root logger. + * @since 1.3 + */ + final public String ROOT_LOGGER_NAME = "ROOT"; + + /** + * Return the name of this Logger instance. + */ + 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 object creation when the logger + * is disabled for the TRACE level.

+ * + * @param format the format string + * @param argArray an array of arguments + * + * @since 1.4 + */ + public void trace(String format, Object[] argArray); + + /** + * 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 + * + * @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 object creation when the logger + * is disabled for the DEBUG level.

+ * + * @param format the format string + * @param argArray an array of arguments + */ + public void debug(String format, Object[] argArray); + + /** + * 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 + */ + 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 argArray an array of arguments + */ + public void debug(Marker marker, String format, Object[] argArray); + + + /** + * 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 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); + + /** + * 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 + */ + 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 argArray an array of arguments + */ + public void info(Marker marker, String format, Object[] argArray); + + + /** + * 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 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); + + /** + * 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 + */ + 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 argArray an array of arguments + */ + public void warn(Marker marker, String format, Object[] argArray); + + + /** + * 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 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); + + /** + * 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 + */ + 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 argArray an array of arguments + */ + public void error(Marker marker, String format, Object[] argArray); + + + /** + * 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 94c8edbf..6dd10e49 100644 --- a/slf4j-api/src/main/java/org/slf4j/LoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/LoggerFactory.java @@ -1,290 +1,290 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j; - -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.List; - -import org.slf4j.helpers.SubstituteLoggerFactory; -import org.slf4j.helpers.Util; -import org.slf4j.impl.StaticLoggerBinder; - -/** - * The LoggerFactory is a utility class producing Loggers for - * various logging APIs, most notably for log4j, logback and JDK 1.4 logging. - * Other implementations such as {@link org.slf4j.impl.NOPLogger NOPLogger} and - * {@link org.slf4j.impl.SimpleLogger SimpleLogger} are also supported. - * - *

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

- * Please note that all methods in LoggerFactory are static. - * - * @author Ceki Gülcü - * @author Robert Elliot - */ -public final class LoggerFactory { - - static final String NO_STATICLOGGERBINDER_URL = "http://www.slf4j.org/codes.html#StaticLoggerBinder"; - static final String MULTIPLE_BINDINGS_URL = "http://www.slf4j.org/codes.html#multiple_bindings"; - static final String NULL_LF_URL = "http://www.slf4j.org/codes.html#null_LF"; - static final String VERSION_MISMATCH = "http://www.slf4j.org/codes.html#version_mismatch"; - static final String SUBSTITUTE_LOGGER_URL = "http://www.slf4j.org/codes.html#substituteLogger"; - - static final String UNSUCCESSFUL_INIT_URL = "http://www.slf4j.org/codes.html#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_INITILIZATION = 1; - static final int FAILED_INITILIZATION = 2; - static final int SUCCESSFUL_INITILIZATION = 3; - - static final int GET_SINGLETON_INEXISTENT = 1; - static final int GET_SINGLETON_EXISTS = 2; - - static int INITIALIZATION_STATE = UNINITIALIZED; - static int GET_SINGLETON_METHOD = UNINITIALIZED; - static SubstituteLoggerFactory TEMP_FACTORY = new SubstituteLoggerFactory(); - - /** - * It is LoggerFactory's responsibility to track version changes and manage - * the compatibility list. - * - *

- * It is assumed that qualifiers after the 3rd digit have no impact on - * compatibility. Thus, 1.5.7-SNAPSHOT, 1.5.7.RC0 are compatible with 1.5.7. - */ - static private final String[] API_COMPATIBILITY_LIST = new String[] { - "1.5.5", "1.5.6", "1.5.7", "1.5.8", "1.5.9", "1.5.10" }; - - // 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; - GET_SINGLETON_METHOD = UNINITIALIZED; - TEMP_FACTORY = new SubstituteLoggerFactory(); - } - - private final static void performInitialization() { - bind(); - versionSanityCheck(); - singleImplementationSanityCheck(); - - } - - private final static void bind() { - try { - // the next line does the binding - getSingleton(); - INITIALIZATION_STATE = SUCCESSFUL_INITILIZATION; - emitSubstituteLoggerWarning(); - } catch (NoClassDefFoundError ncde) { - INITIALIZATION_STATE = FAILED_INITILIZATION; - String msg = ncde.getMessage(); - if (msg != null && msg.indexOf("org/slf4j/impl/StaticLoggerBinder") != -1) { - Util - .reportFailure("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\"."); - Util.reportFailure("See " + NO_STATICLOGGERBINDER_URL - + " for further details."); - - } - throw ncde; - } catch (Exception e) { - INITIALIZATION_STATE = FAILED_INITILIZATION; - // we should never get here - Util.reportFailure("Failed to instantiate logger [" - + getSingleton().getLoggerFactoryClassStr() + "]", e); - } - } - - private final static void emitSubstituteLoggerWarning() { - List loggerNameList = TEMP_FACTORY.getLoggerNameList(); - if (loggerNameList.size() == 0) { - return; - } - Util - .reportFailure("The following loggers will not work becasue they were created"); - Util - .reportFailure("during the default configuration phase of the underlying logging system."); - Util.reportFailure("See also " + SUBSTITUTE_LOGGER_URL); - for (int i = 0; i < loggerNameList.size(); i++) { - String loggerName = (String) loggerNameList.get(i); - Util.reportFailure(loggerName); - } - } - - 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; - } - } - if (!match) { - Util.reportFailure("The requested version " + requested - + " by your slf4j binding is not compatible with " - + Arrays.asList(API_COMPATIBILITY_LIST).toString()); - Util.reportFailure("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.reportFailure( - "Unexpected problem occured during version sanity check", e); - } - } - - // We need to use the name of the StaticLoggerBinder class, we can't reference - // the class itseld. - private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class"; - - private static void singleImplementationSanityCheck() { - try { - ClassLoader loggerFactoryClassLoader = LoggerFactory.class - .getClassLoader(); - if (loggerFactoryClassLoader == null) { - // see http://bugzilla.slf4j.org/show_bug.cgi?id=146 - return; // better than a null pointer exception - } - Enumeration paths = loggerFactoryClassLoader - .getResources(STATIC_LOGGER_BINDER_PATH); - List implementationList = new ArrayList(); - while (paths.hasMoreElements()) { - URL path = (URL) paths.nextElement(); - implementationList.add(path); - } - if (implementationList.size() > 1) { - Util.reportFailure("Class path contains multiple SLF4J bindings."); - for (int i = 0; i < implementationList.size(); i++) { - Util.reportFailure("Found binding in [" + implementationList.get(i) - + "]"); - } - Util.reportFailure("See " + MULTIPLE_BINDINGS_URL - + " for an explanation."); - } - } catch (IOException ioe) { - Util.reportFailure("Error getting resources from path", ioe); - } - } - - private final static StaticLoggerBinder getSingleton() { - if (GET_SINGLETON_METHOD == GET_SINGLETON_INEXISTENT) { - return StaticLoggerBinder.SINGLETON; - } - - if (GET_SINGLETON_METHOD == GET_SINGLETON_EXISTS) { - return StaticLoggerBinder.getSingleton(); - } - - try { - StaticLoggerBinder singleton = StaticLoggerBinder.getSingleton(); - GET_SINGLETON_METHOD = GET_SINGLETON_EXISTS; - return singleton; - } catch (NoSuchMethodError nsme) { - GET_SINGLETON_METHOD = GET_SINGLETON_INEXISTENT; - return StaticLoggerBinder.SINGLETON; - } - } - - /** - * 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. - * - * @param clazz - * the returned logger will be named after clazz - * @return logger - */ - public static Logger getLogger(Class clazz) { - return getLogger(clazz.getName()); - } - - /** - * 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_INITILIZATION; - performInitialization(); - - } - switch (INITIALIZATION_STATE) { - case SUCCESSFUL_INITILIZATION: - return getSingleton().getLoggerFactory(); - case FAILED_INITILIZATION: - throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG); - case ONGOING_INITILIZATION: - // support re-entrant behavior. - // See also http://bugzilla.slf4j.org/show_bug.cgi?id=106 - return TEMP_FACTORY; - } - throw new IllegalStateException("Unreachable code"); - } -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j; + +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.List; + +import org.slf4j.helpers.SubstituteLoggerFactory; +import org.slf4j.helpers.Util; +import org.slf4j.impl.StaticLoggerBinder; + +/** + * The LoggerFactory is a utility class producing Loggers for + * various logging APIs, most notably for log4j, logback and JDK 1.4 logging. + * Other implementations such as {@link org.slf4j.impl.NOPLogger NOPLogger} and + * {@link org.slf4j.impl.SimpleLogger SimpleLogger} are also supported. + * + *

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

+ * Please note that all methods in LoggerFactory are static. + * + * @author Ceki Gülcü + * @author Robert Elliot + */ +public final class LoggerFactory { + + static final String NO_STATICLOGGERBINDER_URL = "http://www.slf4j.org/codes.html#StaticLoggerBinder"; + static final String MULTIPLE_BINDINGS_URL = "http://www.slf4j.org/codes.html#multiple_bindings"; + static final String NULL_LF_URL = "http://www.slf4j.org/codes.html#null_LF"; + static final String VERSION_MISMATCH = "http://www.slf4j.org/codes.html#version_mismatch"; + static final String SUBSTITUTE_LOGGER_URL = "http://www.slf4j.org/codes.html#substituteLogger"; + + static final String UNSUCCESSFUL_INIT_URL = "http://www.slf4j.org/codes.html#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_INITILIZATION = 1; + static final int FAILED_INITILIZATION = 2; + static final int SUCCESSFUL_INITILIZATION = 3; + + static final int GET_SINGLETON_INEXISTENT = 1; + static final int GET_SINGLETON_EXISTS = 2; + + static int INITIALIZATION_STATE = UNINITIALIZED; + static int GET_SINGLETON_METHOD = UNINITIALIZED; + static SubstituteLoggerFactory TEMP_FACTORY = new SubstituteLoggerFactory(); + + /** + * It is LoggerFactory's responsibility to track version changes and manage + * the compatibility list. + * + *

+ * It is assumed that qualifiers after the 3rd digit have no impact on + * compatibility. Thus, 1.5.7-SNAPSHOT, 1.5.7.RC0 are compatible with 1.5.7. + */ + static private final String[] API_COMPATIBILITY_LIST = new String[] { + "1.5.5", "1.5.6", "1.5.7", "1.5.8", "1.5.9", "1.5.10" }; + + // 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; + GET_SINGLETON_METHOD = UNINITIALIZED; + TEMP_FACTORY = new SubstituteLoggerFactory(); + } + + private final static void performInitialization() { + bind(); + versionSanityCheck(); + singleImplementationSanityCheck(); + + } + + private final static void bind() { + try { + // the next line does the binding + getSingleton(); + INITIALIZATION_STATE = SUCCESSFUL_INITILIZATION; + emitSubstituteLoggerWarning(); + } catch (NoClassDefFoundError ncde) { + INITIALIZATION_STATE = FAILED_INITILIZATION; + String msg = ncde.getMessage(); + if (msg != null && msg.indexOf("org/slf4j/impl/StaticLoggerBinder") != -1) { + Util + .reportFailure("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\"."); + Util.reportFailure("See " + NO_STATICLOGGERBINDER_URL + + " for further details."); + + } + throw ncde; + } catch (Exception e) { + INITIALIZATION_STATE = FAILED_INITILIZATION; + // we should never get here + Util.reportFailure("Failed to instantiate logger [" + + getSingleton().getLoggerFactoryClassStr() + "]", e); + } + } + + private final static void emitSubstituteLoggerWarning() { + List loggerNameList = TEMP_FACTORY.getLoggerNameList(); + if (loggerNameList.size() == 0) { + return; + } + Util + .reportFailure("The following loggers will not work becasue they were created"); + Util + .reportFailure("during the default configuration phase of the underlying logging system."); + Util.reportFailure("See also " + SUBSTITUTE_LOGGER_URL); + for (int i = 0; i < loggerNameList.size(); i++) { + String loggerName = (String) loggerNameList.get(i); + Util.reportFailure(loggerName); + } + } + + 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; + } + } + if (!match) { + Util.reportFailure("The requested version " + requested + + " by your slf4j binding is not compatible with " + + Arrays.asList(API_COMPATIBILITY_LIST).toString()); + Util.reportFailure("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.reportFailure( + "Unexpected problem occured during version sanity check", e); + } + } + + // We need to use the name of the StaticLoggerBinder class, we can't reference + // the class itseld. + private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class"; + + private static void singleImplementationSanityCheck() { + try { + ClassLoader loggerFactoryClassLoader = LoggerFactory.class + .getClassLoader(); + if (loggerFactoryClassLoader == null) { + // see http://bugzilla.slf4j.org/show_bug.cgi?id=146 + return; // better than a null pointer exception + } + Enumeration paths = loggerFactoryClassLoader + .getResources(STATIC_LOGGER_BINDER_PATH); + List implementationList = new ArrayList(); + while (paths.hasMoreElements()) { + URL path = (URL) paths.nextElement(); + implementationList.add(path); + } + if (implementationList.size() > 1) { + Util.reportFailure("Class path contains multiple SLF4J bindings."); + for (int i = 0; i < implementationList.size(); i++) { + Util.reportFailure("Found binding in [" + implementationList.get(i) + + "]"); + } + Util.reportFailure("See " + MULTIPLE_BINDINGS_URL + + " for an explanation."); + } + } catch (IOException ioe) { + Util.reportFailure("Error getting resources from path", ioe); + } + } + + private final static StaticLoggerBinder getSingleton() { + if (GET_SINGLETON_METHOD == GET_SINGLETON_INEXISTENT) { + return StaticLoggerBinder.SINGLETON; + } + + if (GET_SINGLETON_METHOD == GET_SINGLETON_EXISTS) { + return StaticLoggerBinder.getSingleton(); + } + + try { + StaticLoggerBinder singleton = StaticLoggerBinder.getSingleton(); + GET_SINGLETON_METHOD = GET_SINGLETON_EXISTS; + return singleton; + } catch (NoSuchMethodError nsme) { + GET_SINGLETON_METHOD = GET_SINGLETON_INEXISTENT; + return StaticLoggerBinder.SINGLETON; + } + } + + /** + * 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. + * + * @param clazz + * the returned logger will be named after clazz + * @return logger + */ + public static Logger getLogger(Class clazz) { + return getLogger(clazz.getName()); + } + + /** + * 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_INITILIZATION; + performInitialization(); + + } + switch (INITIALIZATION_STATE) { + case SUCCESSFUL_INITILIZATION: + return getSingleton().getLoggerFactory(); + case FAILED_INITILIZATION: + throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG); + case ONGOING_INITILIZATION: + // support re-entrant behavior. + // See also http://bugzilla.slf4j.org/show_bug.cgi?id=106 + return TEMP_FACTORY; + } + throw new IllegalStateException("Unreachable code"); + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/MDC.java b/slf4j-api/src/main/java/org/slf4j/MDC.java index 4d16be14..f8d232de 100644 --- a/slf4j-api/src/main/java/org/slf4j/MDC.java +++ b/slf4j-api/src/main/java/org/slf4j/MDC.java @@ -1,207 +1,207 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j; - -import java.util.Map; - -import org.slf4j.helpers.BasicMDCAdapter; -import org.slf4j.helpers.Util; -import org.slf4j.impl.StaticMDCBinder; -import org.slf4j.spi.MDCAdapter; - -/** - * This class hides and serves as a substitute for the underlying logging - * system's MDC implementation. - * - *

- * If the underlying logging system offers MDC functionality, then SLF4J's MDC, - * i.e. this class, will delegate to the underlying system's MDC. Note that at - * this time, only two logging systems, namely log4j and logback, offer MDC - * functionality. If the underlying system does not support MDC, e.g. java.util.logging, - * then SLF4J will use a {@link BasicMDCAdapter}. - * - *

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

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

- * Please note that all methods in this class are static. - * - * @author Ceki Gülcü - * @since 1.4.1 - */ -public class MDC { - - static final String NULL_MDCA_URL = "http://www.slf4j.org/codes.html#null_MDCA"; - static final String NO_STATIC_MDC_BINDER_URL = "http://www.slf4j.org/codes.html#no_static_mdc_binder"; - static MDCAdapter mdcAdapter; - - private MDC() { - } - - static { - try { - mdcAdapter = StaticMDCBinder.SINGLETON.getMDCA(); - } catch (NoClassDefFoundError ncde) { - String msg = ncde.getMessage(); - if (msg != null && msg.indexOf("org/slf4j/impl/StaticMDCBinder") != -1) { - Util - .reportFailure("Failed to load class \"org.slf4j.impl.StaticMDCBinder\"."); - Util.reportFailure("See " + NO_STATIC_MDC_BINDER_URL - + " for further details."); - - } - throw ncde; - } catch (Exception e) { - // we should never get here - Util.reportFailure("Could not bind with an instance of class [" - + StaticMDCBinder.SINGLETON.getMDCAdapterClassStr() + "]", e); - } - } - - /** - * Put a context value (the val parameter) as identified with - * the key parameter into the current thread's context map. - * The key parameter cannot be null. The val parameter - * can be null only if the underlying implementation supports it. - * - *

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

+ * If the underlying logging system offers MDC functionality, then SLF4J's MDC, + * i.e. this class, will delegate to the underlying system's MDC. Note that at + * this time, only two logging systems, namely log4j and logback, offer MDC + * functionality. If the underlying system does not support MDC, e.g. java.util.logging, + * then SLF4J will use a {@link BasicMDCAdapter}. + * + *

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

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

+ * Please note that all methods in this class are static. + * + * @author Ceki Gülcü + * @since 1.4.1 + */ +public class MDC { + + static final String NULL_MDCA_URL = "http://www.slf4j.org/codes.html#null_MDCA"; + static final String NO_STATIC_MDC_BINDER_URL = "http://www.slf4j.org/codes.html#no_static_mdc_binder"; + static MDCAdapter mdcAdapter; + + private MDC() { + } + + static { + try { + mdcAdapter = StaticMDCBinder.SINGLETON.getMDCA(); + } catch (NoClassDefFoundError ncde) { + String msg = ncde.getMessage(); + if (msg != null && msg.indexOf("org/slf4j/impl/StaticMDCBinder") != -1) { + Util + .reportFailure("Failed to load class \"org.slf4j.impl.StaticMDCBinder\"."); + Util.reportFailure("See " + NO_STATIC_MDC_BINDER_URL + + " for further details."); + + } + throw ncde; + } catch (Exception e) { + // we should never get here + Util.reportFailure("Could not bind with an instance of class [" + + StaticMDCBinder.SINGLETON.getMDCAdapterClassStr() + "]", e); + } + } + + /** + * Put a context value (the val parameter) as identified with + * the key parameter into the current thread's context map. + * The key parameter cannot be null. The val parameter + * can be null only if the underlying implementation supports it. + * + *

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

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

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

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

- * Please note that all methods in this class are static. - * - * @author Ceki Gülcü - */ -public class MarkerFactory { - static IMarkerFactory markerFactory; - - private MarkerFactory() { - } - - static { - try { - markerFactory = StaticMarkerBinder.SINGLETON.getMarkerFactory(); - } catch (Exception e) { - // we should never get here - Util.reportFailure("Could not instantiate instance of class [" - + StaticMarkerBinder.SINGLETON.getMarkerFactoryClassStr() + "]", 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. - * - * @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; - } +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j; + +import org.slf4j.helpers.Util; +import org.slf4j.impl.StaticMarkerBinder; + +/** + * MarkerFactory is a utility class producing {@link Marker} instances as + * appropriate for the logging system currently in use. + * + *

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

+ * Please note that all methods in this class are static. + * + * @author Ceki Gülcü + */ +public class MarkerFactory { + static IMarkerFactory markerFactory; + + private MarkerFactory() { + } + + static { + try { + markerFactory = StaticMarkerBinder.SINGLETON.getMarkerFactory(); + } catch (Exception e) { + // we should never get here + Util.reportFailure("Could not instantiate instance of class [" + + StaticMarkerBinder.SINGLETON.getMarkerFactoryClassStr() + "]", 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. + * + * @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 df4d470f..57589f50 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMDCAdapter.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMDCAdapter.java @@ -1,147 +1,147 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -package org.slf4j.helpers; - -import org.slf4j.spi.MDCAdapter; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * Basic MDC implementation, which can be used with logging systems that lack - * out-of-the-box MDC support. - * - * This code is largely based on logback's - * LogbackMDCAdapter. - * - * @author Ceki Gulcu - * @author Maarten Bosteels - * - * @since 1.5.0 - */ -public class BasicMDCAdapter implements MDCAdapter { - - private InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal(); - - /** - * 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"); - } - HashMap map = (HashMap) inheritableThreadLocal.get(); - if (map == null) { - map = new HashMap(); - inheritableThreadLocal.set(map); - } - map.put(key, val); - } - - /** - * Get the context identified by the key parameter. - */ - public String get(String key) { - HashMap hashMap = (HashMap) inheritableThreadLocal.get(); - if ((hashMap != null) && (key != null)) { - return (String) hashMap.get(key); - } else { - return null; - } - } - - /** - * Remove the the context identified by the key parameter. - */ - public void remove(String key) { - HashMap map = (HashMap) inheritableThreadLocal.get(); - if (map != null) { - map.remove(key); - } - } - - /** - * Clear all entries in the MDC. - */ - public void clear() { - HashMap hashMap = (HashMap) inheritableThreadLocal.get(); - if (hashMap != null) { - hashMap.clear(); - // the InheritableThreadLocal.remove method was introduced in JDK 1.5 - // Thus, invoking clear() on previous JDK's will fail - 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() { - HashMap hashMap = (HashMap) inheritableThreadLocal.get(); - if (hashMap != null) { - return hashMap.keySet(); - } else { - return null; - } - } - /** - * Return a copy of the current thread's context map. - * Returned value may be null. - * - */ - public Map getCopyOfContextMap() { - HashMap hashMap = (HashMap) inheritableThreadLocal.get(); - if (hashMap != null) { - return new HashMap(hashMap); - } else { - return null; - } - } - - public void setContextMap(Map contextMap) { - HashMap hashMap = (HashMap) inheritableThreadLocal.get(); - if (hashMap != null) { - hashMap.clear(); - hashMap.putAll(contextMap); - } else { - hashMap = new HashMap(contextMap); - inheritableThreadLocal.set(hashMap); - } - } - -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package org.slf4j.helpers; + +import org.slf4j.spi.MDCAdapter; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * Basic MDC implementation, which can be used with logging systems that lack + * out-of-the-box MDC support. + * + * This code is largely based on logback's + * LogbackMDCAdapter. + * + * @author Ceki Gulcu + * @author Maarten Bosteels + * + * @since 1.5.0 + */ +public class BasicMDCAdapter implements MDCAdapter { + + private InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal(); + + /** + * 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"); + } + HashMap map = (HashMap) inheritableThreadLocal.get(); + if (map == null) { + map = new HashMap(); + inheritableThreadLocal.set(map); + } + map.put(key, val); + } + + /** + * Get the context identified by the key parameter. + */ + public String get(String key) { + HashMap hashMap = (HashMap) inheritableThreadLocal.get(); + if ((hashMap != null) && (key != null)) { + return (String) hashMap.get(key); + } else { + return null; + } + } + + /** + * Remove the the context identified by the key parameter. + */ + public void remove(String key) { + HashMap map = (HashMap) inheritableThreadLocal.get(); + if (map != null) { + map.remove(key); + } + } + + /** + * Clear all entries in the MDC. + */ + public void clear() { + HashMap hashMap = (HashMap) inheritableThreadLocal.get(); + if (hashMap != null) { + hashMap.clear(); + // the InheritableThreadLocal.remove method was introduced in JDK 1.5 + // Thus, invoking clear() on previous JDK's will fail + 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() { + HashMap hashMap = (HashMap) inheritableThreadLocal.get(); + if (hashMap != null) { + return hashMap.keySet(); + } else { + return null; + } + } + /** + * Return a copy of the current thread's context map. + * Returned value may be null. + * + */ + public Map getCopyOfContextMap() { + HashMap hashMap = (HashMap) inheritableThreadLocal.get(); + if (hashMap != null) { + return new HashMap(hashMap); + } else { + return null; + } + } + + public void setContextMap(Map contextMap) { + HashMap hashMap = (HashMap) inheritableThreadLocal.get(); + if (hashMap != null) { + hashMap.clear(); + hashMap.putAll(contextMap); + } else { + hashMap = new HashMap(contextMap); + inheritableThreadLocal.set(hashMap); + } + } + +} 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 9529c340..de575d25 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarker.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarker.java @@ -1,196 +1,196 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.helpers; - -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import org.slf4j.Marker; - -/** - * A simple implementation of the {@link Marker} interface. - * - * @author Ceki Gülcü - * @author Joern Huxhorn - */ -public class BasicMarker implements Marker { - - private static final long serialVersionUID = 1803952589649545191L; - - private final String name; - private List refereceList; - - BasicMarker(String name) { - if (name == null) { - throw new IllegalArgumentException("A merker 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 (refereceList == null) { - refereceList = new Vector(); - } - refereceList.add(reference); - } - - } - - public synchronized boolean hasReferences() { - return ((refereceList != null) && (refereceList.size() > 0)); - } - - public boolean hasChildren() { - return hasReferences(); - } - - public synchronized Iterator iterator() { - if (refereceList != null) { - return refereceList.iterator(); - } else { - return Collections.EMPTY_LIST.iterator(); - } - } - - public synchronized boolean remove(Marker referenceToRemove) { - if (refereceList == null) { - return false; - } - - int size = refereceList.size(); - for (int i = 0; i < size; i++) { - Marker m = (Marker) refereceList.get(i); - if (referenceToRemove.equals(m)) { - refereceList.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 < refereceList.size(); i++) { - Marker ref = (Marker) refereceList.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 < refereceList.size(); i++) { - Marker ref = (Marker) refereceList.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; - StringBuffer sb = new StringBuffer(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(); - } -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.helpers; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + +import org.slf4j.Marker; + +/** + * A simple implementation of the {@link Marker} interface. + * + * @author Ceki Gülcü + * @author Joern Huxhorn + */ +public class BasicMarker implements Marker { + + private static final long serialVersionUID = 1803952589649545191L; + + private final String name; + private List refereceList; + + BasicMarker(String name) { + if (name == null) { + throw new IllegalArgumentException("A merker 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 (refereceList == null) { + refereceList = new Vector(); + } + refereceList.add(reference); + } + + } + + public synchronized boolean hasReferences() { + return ((refereceList != null) && (refereceList.size() > 0)); + } + + public boolean hasChildren() { + return hasReferences(); + } + + public synchronized Iterator iterator() { + if (refereceList != null) { + return refereceList.iterator(); + } else { + return Collections.EMPTY_LIST.iterator(); + } + } + + public synchronized boolean remove(Marker referenceToRemove) { + if (refereceList == null) { + return false; + } + + int size = refereceList.size(); + for (int i = 0; i < size; i++) { + Marker m = (Marker) refereceList.get(i); + if (referenceToRemove.equals(m)) { + refereceList.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 < refereceList.size(); i++) { + Marker ref = (Marker) refereceList.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 < refereceList.size(); i++) { + Marker ref = (Marker) refereceList.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; + StringBuffer sb = new StringBuffer(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 1f5be23f..7686684b 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarkerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/BasicMarkerFactory.java @@ -1,99 +1,99 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.helpers; - -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.IMarkerFactory; -import org.slf4j.Marker; - -/** - * An almost trivial implementation of the {@link IMarkerFactory} - * interface which creates {@link BasicMarker} instances. - * - *

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

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

- * For example, - * - *

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

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

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

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

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

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

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

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

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

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

- * For example, - * - *

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

- * - * @param messagePattern - * The message pattern which will be parsed and formatted - * @param argument - * The argument to be substituted in place of the formatting anchor - * @return The formatted message - */ - final public static String 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 String format(final String messagePattern, Object arg1, - Object arg2) { - return arrayFormat(messagePattern, new Object[] { arg1, arg2 }); - } - - /** - * 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 String arrayFormat(final String messagePattern, - final Object[] argArray) { - if (messagePattern == null) { - return null; - } - if (argArray == null) { - return messagePattern; - } - int i = 0; - int j; - StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50); - - for (int 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 messagePattern; - } else { // add the tail string which contains no variables and return - // the result. - sbuf.append(messagePattern.substring(i, messagePattern.length())); - return sbuf.toString(); - } - } 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())); - return sbuf.toString(); - } - - 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(StringBuffer 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(StringBuffer 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 objectArrayAppend(StringBuffer sbuf, Object[] a, - Map seenMap) { - sbuf.append('['); - if (!seenMap.containsKey(a)) { - seenMap.put(a, null); - final int len = a.length; - for (int i = 0; i < len; i++) { - deeplyAppendParameter(sbuf, a[i], seenMap); - if (i != len - 1) - sbuf.append(", "); - } - // allow repeats in siblings - seenMap.remove(a); - } else { - sbuf.append("..."); - } - sbuf.append(']'); - } - - private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } - - private static void byteArrayAppend(StringBuffer sbuf, byte[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } - - private static void charArrayAppend(StringBuffer 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(StringBuffer 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(StringBuffer 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(StringBuffer 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(StringBuffer 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(StringBuffer sbuf, double[] a) { - sbuf.append('['); - final int len = a.length; - for (int i = 0; i < len; i++) { - sbuf.append(a[i]); - if (i != len - 1) - sbuf.append(", "); - } - sbuf.append(']'); - } -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.helpers; + +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; + +// contributors: lizongbo: proposed special treatment of array parameter values +// Jörn Huxhorn: pointed out double[] omission, suggested deep array copy +/** + * Formats messages according to very simple substitution rules. Substitutions + * can be made 1, 2 or more arguments. + * + *

+ * For example, + * + *

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

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

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

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

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

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

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

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

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

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

+ * For example, + * + *

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

+ * + * @param messagePattern + * The message pattern which will be parsed and formatted + * @param argument + * The argument to be substituted in place of the formatting anchor + * @return The formatted message + */ + final public static String 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 String format(final String messagePattern, Object arg1, + Object arg2) { + return arrayFormat(messagePattern, new Object[] { arg1, arg2 }); + } + + /** + * 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 String arrayFormat(final String messagePattern, + final Object[] argArray) { + if (messagePattern == null) { + return null; + } + if (argArray == null) { + return messagePattern; + } + int i = 0; + int j; + StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50); + + for (int 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 messagePattern; + } else { // add the tail string which contains no variables and return + // the result. + sbuf.append(messagePattern.substring(i, messagePattern.length())); + return sbuf.toString(); + } + } 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())); + return sbuf.toString(); + } + + 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(StringBuffer 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(StringBuffer 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 objectArrayAppend(StringBuffer sbuf, Object[] a, + Map seenMap) { + sbuf.append('['); + if (!seenMap.containsKey(a)) { + seenMap.put(a, null); + final int len = a.length; + for (int i = 0; i < len; i++) { + deeplyAppendParameter(sbuf, a[i], seenMap); + if (i != len - 1) + sbuf.append(", "); + } + // allow repeats in siblings + seenMap.remove(a); + } else { + sbuf.append("..."); + } + sbuf.append(']'); + } + + private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void byteArrayAppend(StringBuffer sbuf, byte[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void charArrayAppend(StringBuffer 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(StringBuffer 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(StringBuffer 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(StringBuffer 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(StringBuffer 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(StringBuffer sbuf, double[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/NOPLogger.java b/slf4j-api/src/main/java/org/slf4j/helpers/NOPLogger.java index 251a7361..d263f91f 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NOPLogger.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NOPLogger.java @@ -1,238 +1,238 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.helpers; - -import org.slf4j.Logger; -import org.slf4j.helpers.MarkerIgnoringBase; - - -/** - * A direct NOP (no operation) implementation of {@link Logger}. - * - * @author Ceki Gülcü - */ -public class NOPLogger extends MarkerIgnoringBase { - - private static final long serialVersionUID = -517220405410904473L; - - /** - * The unique instance of NOPLogger. - */ - public static final NOPLogger NOP_LOGGER = new NOPLogger(); - - /** - * There is no point in creating multiple instances of NOPLOgger, - * except by derived classes, hence the protected access for the constructor. - */ - protected NOPLogger() { - } - - /** - * Always returns the string value "NOP". - */ - public String getName() { - return "NOP"; - } - - /** - * Always returns false. - * @return always false - */ - final public boolean isTraceEnabled() { - return false; - } - - /** A NOP implementation. */ - final public void trace(String msg) { - // NOP - } - - /** A NOP implementation. */ - final public void trace(String format, Object arg) { - // NOP - } - - /** A NOP implementation. */ - public final void trace(String format, Object arg1, Object arg2) { - // NOP - } - - /** A NOP implementation. */ - public final void trace(String format, Object[] argArray) { - // NOP - } - - /** A NOP implementation. */ - final public void trace(String msg, Throwable t) { - // NOP - } - - /** - * Always returns false. - * @return always false - */ - final public boolean isDebugEnabled() { - return false; - } - - /** A NOP implementation. */ - final public void debug(String msg) { - // NOP - } - - /** A NOP implementation. */ - final public void debug(String format, Object arg) { - // NOP - } - - /** A NOP implementation. */ - public final void debug(String format, Object arg1, Object arg2) { - // NOP - } - - /** A NOP implementation. */ - public final void debug(String format, Object[] argArray) { - // NOP - } - - - - /** A NOP implementation. */ - final public void debug(String msg, Throwable t) { - // NOP - } - - /** - * Always returns false. - * @return always false - */ - final public boolean isInfoEnabled() { - // NOP - return false; - } - - - /** A NOP implementation. */ - final public void info(String msg) { - // NOP - } - - /** A NOP implementation. */ - final public void info(String format, Object arg1) { - // NOP - } - - /** A NOP implementation. */ - final public void info(String format, Object arg1, Object arg2) { - // NOP - } - - /** A NOP implementation. */ - public final void info(String format, Object[] argArray) { - // NOP - } - - - /** A NOP implementation. */ - final public void info(String msg, Throwable t) { - // NOP - } - - - /** - * Always returns false. - * @return always false - */ - final public boolean isWarnEnabled() { - return false; - } - - /** A NOP implementation. */ - final public void warn(String msg) { - // NOP - } - - /** A NOP implementation. */ - final public void warn(String format, Object arg1) { - // NOP - } - - /** A NOP implementation. */ - final public void warn(String format, Object arg1, Object arg2) { - // NOP - } - - /** A NOP implementation. */ - public final void warn(String format, Object[] argArray) { - // NOP - } - - - /** A NOP implementation. */ - final public void warn(String msg, Throwable t) { - // NOP - } - - - /** A NOP implementation. */ - final public boolean isErrorEnabled() { - return false; - } - - /** A NOP implementation. */ - final public void error(String msg) { - // NOP - } - - /** A NOP implementation. */ - final public void error(String format, Object arg1) { - // NOP - } - - /** A NOP implementation. */ - final public void error(String format, Object arg1, Object arg2) { - // NOP - } - - /** A NOP implementation. */ - public final void error(String format, Object[] argArray) { - // NOP - } - - - /** A NOP implementation. */ - final public void error(String msg, Throwable t) { - // NOP - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.helpers; + +import org.slf4j.Logger; +import org.slf4j.helpers.MarkerIgnoringBase; + + +/** + * A direct NOP (no operation) implementation of {@link Logger}. + * + * @author Ceki Gülcü + */ +public class NOPLogger extends MarkerIgnoringBase { + + private static final long serialVersionUID = -517220405410904473L; + + /** + * The unique instance of NOPLogger. + */ + public static final NOPLogger NOP_LOGGER = new NOPLogger(); + + /** + * There is no point in creating multiple instances of NOPLOgger, + * except by derived classes, hence the protected access for the constructor. + */ + protected NOPLogger() { + } + + /** + * Always returns the string value "NOP". + */ + public String getName() { + return "NOP"; + } + + /** + * Always returns false. + * @return always false + */ + final public boolean isTraceEnabled() { + return false; + } + + /** A NOP implementation. */ + final public void trace(String msg) { + // NOP + } + + /** A NOP implementation. */ + final public void trace(String format, Object arg) { + // NOP + } + + /** A NOP implementation. */ + public final void trace(String format, Object arg1, Object arg2) { + // NOP + } + + /** A NOP implementation. */ + public final void trace(String format, Object[] argArray) { + // NOP + } + + /** A NOP implementation. */ + final public void trace(String msg, Throwable t) { + // NOP + } + + /** + * Always returns false. + * @return always false + */ + final public boolean isDebugEnabled() { + return false; + } + + /** A NOP implementation. */ + final public void debug(String msg) { + // NOP + } + + /** A NOP implementation. */ + final public void debug(String format, Object arg) { + // NOP + } + + /** A NOP implementation. */ + public final void debug(String format, Object arg1, Object arg2) { + // NOP + } + + /** A NOP implementation. */ + public final void debug(String format, Object[] argArray) { + // NOP + } + + + + /** A NOP implementation. */ + final public void debug(String msg, Throwable t) { + // NOP + } + + /** + * Always returns false. + * @return always false + */ + final public boolean isInfoEnabled() { + // NOP + return false; + } + + + /** A NOP implementation. */ + final public void info(String msg) { + // NOP + } + + /** A NOP implementation. */ + final public void info(String format, Object arg1) { + // NOP + } + + /** A NOP implementation. */ + final public void info(String format, Object arg1, Object arg2) { + // NOP + } + + /** A NOP implementation. */ + public final void info(String format, Object[] argArray) { + // NOP + } + + + /** A NOP implementation. */ + final public void info(String msg, Throwable t) { + // NOP + } + + + /** + * Always returns false. + * @return always false + */ + final public boolean isWarnEnabled() { + return false; + } + + /** A NOP implementation. */ + final public void warn(String msg) { + // NOP + } + + /** A NOP implementation. */ + final public void warn(String format, Object arg1) { + // NOP + } + + /** A NOP implementation. */ + final public void warn(String format, Object arg1, Object arg2) { + // NOP + } + + /** A NOP implementation. */ + public final void warn(String format, Object[] argArray) { + // NOP + } + + + /** A NOP implementation. */ + final public void warn(String msg, Throwable t) { + // NOP + } + + + /** A NOP implementation. */ + final public boolean isErrorEnabled() { + return false; + } + + /** A NOP implementation. */ + final public void error(String msg) { + // NOP + } + + /** A NOP implementation. */ + final public void error(String format, Object arg1) { + // NOP + } + + /** A NOP implementation. */ + final public void error(String format, Object arg1, Object arg2) { + // NOP + } + + /** A NOP implementation. */ + public final void error(String format, Object[] argArray) { + // NOP + } + + + /** A NOP implementation. */ + final public void error(String msg, Throwable t) { + // NOP + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/NOPMakerAdapter.java b/slf4j-api/src/main/java/org/slf4j/helpers/NOPMakerAdapter.java index 5ed9aa2e..ab857536 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NOPMakerAdapter.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NOPMakerAdapter.java @@ -1,39 +1,39 @@ -package org.slf4j.helpers; - -import java.util.Map; - -import org.slf4j.spi.MDCAdapter; - -/** - * This adapter is an empty implementation of the {@link MDCAdapter} interface. - * It is used for all logging systems which do not support mapped - * diagnostic contexts such as JDK14, simple and NOP. - * - * @author Ceki Gülcü - * - * @since 1.4.1 - */ -public class NOPMakerAdapter implements MDCAdapter { - - public void clear() { - } - - public String get(String key) { - return null; - } - - public void put(String key, String val) { - } - - public void remove(String key) { - } - - public Map getCopyOfContextMap() { - return null; - } - - public void setContextMap(Map contextMap) { - // NOP - } - -} +package org.slf4j.helpers; + +import java.util.Map; + +import org.slf4j.spi.MDCAdapter; + +/** + * This adapter is an empty implementation of the {@link MDCAdapter} interface. + * It is used for all logging systems which do not support mapped + * diagnostic contexts such as JDK14, simple and NOP. + * + * @author Ceki Gülcü + * + * @since 1.4.1 + */ +public class NOPMakerAdapter implements MDCAdapter { + + public void clear() { + } + + public String get(String key) { + return null; + } + + public void put(String key, String val) { + } + + public void remove(String key) { + } + + public Map getCopyOfContextMap() { + return null; + } + + public void setContextMap(Map contextMap) { + // NOP + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/NamedLoggerBase.java b/slf4j-api/src/main/java/org/slf4j/helpers/NamedLoggerBase.java index bd247db2..e84d0b2a 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/NamedLoggerBase.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/NamedLoggerBase.java @@ -1,46 +1,46 @@ -package org.slf4j.helpers; - -import java.io.ObjectStreamException; -import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Serves as base class for named logger implementation. More significantly, this - * class establishes deserialization behavior. See @see #readResolve. - * - * @author Ceki Gulcu - * @since 1.5.3 - */ -abstract class NamedLoggerBase implements Logger, Serializable { - - private static final long serialVersionUID = 7535258609338176893L; - - protected String name; - - public String getName() { - return name; - } - - /** - * Replace this instance with a homonymous (same name) logger returned - * by LoggerFactory. Note that this method is only called during - * deserialization. - * - *

- * This approach will work well if the desired ILoggerFactory is the one - * references by LoggerFactory. However, if the user manages its logger hierarchy - * through a different (non-static) mechanism, e.g. dependency injection, then - * this approach would be mostly counterproductive. - * - * @return logger with same name as returned by LoggerFactory - * @throws ObjectStreamException - */ - protected Object readResolve() throws ObjectStreamException { - // using getName() instead of this.name works even for - // NOPLogger - return LoggerFactory.getLogger(getName()); - } - -} +package org.slf4j.helpers; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Serves as base class for named logger implementation. More significantly, this + * class establishes deserialization behavior. See @see #readResolve. + * + * @author Ceki Gulcu + * @since 1.5.3 + */ +abstract class NamedLoggerBase implements Logger, Serializable { + + private static final long serialVersionUID = 7535258609338176893L; + + protected String name; + + public String getName() { + return name; + } + + /** + * Replace this instance with a homonymous (same name) logger returned + * by LoggerFactory. Note that this method is only called during + * deserialization. + * + *

+ * This approach will work well if the desired ILoggerFactory is the one + * references by LoggerFactory. However, if the user manages its logger hierarchy + * through a different (non-static) mechanism, e.g. dependency injection, then + * this approach would be mostly counterproductive. + * + * @return logger with same name as returned by LoggerFactory + * @throws ObjectStreamException + */ + protected Object readResolve() throws ObjectStreamException { + // using getName() instead of this.name works even for + // NOPLogger + return LoggerFactory.getLogger(getName()); + } + +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java b/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java index 513c8f48..bff64495 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/SubstituteLoggerFactory.java @@ -1,67 +1,67 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.helpers; - -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.ILoggerFactory; -import org.slf4j.Logger; - -/** - * SubstituteLoggerFactory is an trivial implementation of {@link - * ILoggerFactory} which always returns the unique instance of NOPLogger. - * - *

- * It used as a temporary substitute for the real ILoggerFactory during its - * auto-configuration which may re-enter LoggerFactory to obtain logger - * instances. See also http://bugzilla.slf4j.org/show_bug.cgi?id=106 - * - * @author Ceki Gülcü - */ -public class SubstituteLoggerFactory implements ILoggerFactory { - - // keep a record of requested logger names - final List loggerNameList = new ArrayList(); - - public Logger getLogger(String name) { - loggerNameList.add(name); - return NOPLogger.NOP_LOGGER; - } - - public List getLoggerNameList() { - return loggerNameList; - } - -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.helpers; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.ILoggerFactory; +import org.slf4j.Logger; + +/** + * SubstituteLoggerFactory is an trivial implementation of {@link + * ILoggerFactory} which always returns the unique instance of NOPLogger. + * + *

+ * It used as a temporary substitute for the real ILoggerFactory during its + * auto-configuration which may re-enter LoggerFactory to obtain logger + * instances. See also http://bugzilla.slf4j.org/show_bug.cgi?id=106 + * + * @author Ceki Gülcü + */ +public class SubstituteLoggerFactory implements ILoggerFactory { + + // keep a record of requested logger names + final List loggerNameList = new ArrayList(); + + public Logger getLogger(String name) { + loggerNameList.add(name); + return NOPLogger.NOP_LOGGER; + } + + public List getLoggerNameList() { + return loggerNameList; + } + +} 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 d91f1124..1ce0f972 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/Util.java +++ b/slf4j-api/src/main/java/org/slf4j/helpers/Util.java @@ -1,45 +1,45 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.helpers; - - -/** - * - * An internal utility class. - * - * @author Ceki Gülcü - */ -public class Util { - - static final public void reportFailure(String msg, Throwable t) { - System.err.println(msg); - System.err.println("Reported exception:"); - t.printStackTrace(); - } - - static final public void reportFailure(String msg) { - System.err.println("SLF4J: " +msg); - } -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.helpers; + + +/** + * + * An internal utility class. + * + * @author Ceki Gülcü + */ +public class Util { + + static final public void reportFailure(String msg, Throwable t) { + System.err.println(msg); + System.err.println("Reported exception:"); + t.printStackTrace(); + } + + static final public void reportFailure(String msg) { + System.err.println("SLF4J: " +msg); + } +} diff --git a/slf4j-api/src/main/java/org/slf4j/helpers/package.html b/slf4j-api/src/main/java/org/slf4j/helpers/package.html index 9d7c8c38..f223543d 100644 --- a/slf4j-api/src/main/java/org/slf4j/helpers/package.html +++ b/slf4j-api/src/main/java/org/slf4j/helpers/package.html @@ -1,16 +1,16 @@ - - - - - - - - - - - -

Helper classes.

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

Helper classes.

+ +
+ + diff --git a/slf4j-api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/slf4j-api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index 23e04445..89b97daf 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,77 +1,77 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * This class is meant to provide a dummy StaticLoggerBinder to the slf4j-api module. - * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop, - * slf4j-log4j12 etc. - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder { - - /** - * The unique instance of this class. - * - * @deprecated Please use the {@link #getSingleton()} method instead of - * accessing this field directly. In future versions, this field - * will become private. - */ - public 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.5.10"; // !final - - private StaticLoggerBinder() { - throw new UnsupportedOperationException("This code should have never made it into the jar"); - } - - public ILoggerFactory getLoggerFactory() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } - - public String getLoggerFactoryClassStr() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * This class is meant to provide a dummy StaticLoggerBinder to the slf4j-api module. + * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop, + * slf4j-log4j12 etc. + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder { + + /** + * The unique instance of this class. + * + * @deprecated Please use the {@link #getSingleton()} method instead of + * accessing this field directly. In future versions, this field + * will become private. + */ + public 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.5.10"; // !final + + private StaticLoggerBinder() { + throw new UnsupportedOperationException("This code should have never made it into the jar"); + } + + public ILoggerFactory getLoggerFactory() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + + public String getLoggerFactoryClassStr() { + throw new UnsupportedOperationException("This code should never make it into the 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 81f2a8c2..9be10fa5 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,35 +1,35 @@ -package org.slf4j.impl; - -import org.slf4j.spi.MDCAdapter; - - -/** - * This class is only a stub. Real implementations are found in - * each SLF4J binding project, e.g. slf4j-nop, slf4j-log4j12 etc. - * - * @author Ceki Gülcü - */ -public class StaticMDCBinder { - - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - - private StaticMDCBinder() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } - - /** - * 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"); - } -} +package org.slf4j.impl; + +import org.slf4j.spi.MDCAdapter; + + +/** + * This class is only a stub. Real implementations are found in + * each SLF4J binding project, e.g. slf4j-nop, slf4j-log4j12 etc. + * + * @author Ceki Gülcü + */ +public class StaticMDCBinder { + + + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + + /** + * 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 3bf01037..5d646249 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,71 +1,71 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * This class is meant to provide a *dummy* StaticMarkerBinder to the slf4j-api module. - * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop, - * slf4j-simple, slf4j-log4j12 etc. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - private StaticMarkerBinder() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - throw new UnsupportedOperationException("This code should never make it into the jar"); - } - - -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * This class is meant to provide a *dummy* StaticMarkerBinder to the slf4j-api module. + * Real implementations are found in each SLF4J binding project, e.g. slf4j-nop, + * slf4j-simple, slf4j-log4j12 etc. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + private StaticMarkerBinder() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + throw new UnsupportedOperationException("This code should never make it into the jar"); + } + + +} diff --git a/slf4j-api/src/main/java/org/slf4j/impl/package.html b/slf4j-api/src/main/java/org/slf4j/impl/package.html index f4311e30..6b84bada 100644 --- a/slf4j-api/src/main/java/org/slf4j/impl/package.html +++ b/slf4j-api/src/main/java/org/slf4j/impl/package.html @@ -1,17 +1,17 @@ - - - - - - - - - - - -

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

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

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

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

Core logging interfaces.

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

Core logging interfaces.

+ +
+ + diff --git a/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java b/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java index 61ed7186..97865512 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/LocationAwareLogger.java @@ -1,60 +1,60 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.spi; - -import org.slf4j.Logger; -import org.slf4j.Marker; - -/** - * An optional interface helping integration with logging systems capable of - * extracting location information. This interface is mainly used by SLF4J bridges - * such as jcl104-over-slf4j which need to provide hints so that the underlying logging - * system can extract the correct location information (method name, line number, etc.). - * - * - * @author Ceki Gulcu - * @since 1.3 - */ -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 - * @param fqcn The fully qualified class name of the caller - * @param level - * @param message - * @param t - */ - public void log(Marker marker, String fqcn, int level, String message, Throwable t); - -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.spi; + +import org.slf4j.Logger; +import org.slf4j.Marker; + +/** + * An optional interface helping integration with logging systems capable of + * extracting location information. This interface is mainly used by SLF4J bridges + * such as jcl104-over-slf4j which need to provide hints so that the underlying logging + * system can extract the correct location information (method name, line number, etc.). + * + * + * @author Ceki Gulcu + * @since 1.3 + */ +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 + * @param fqcn The fully qualified class name of the caller + * @param level + * @param message + * @param t + */ + public void log(Marker marker, String fqcn, int level, String message, 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 9abedc52..cef5a6ab 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/LoggerFactoryBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/LoggerFactoryBinder.java @@ -1,66 +1,66 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.spi; - -import org.slf4j.ILoggerFactory; - -/** - * An internal interface which helps the static {@link org.slf4j.LoggerFactory} - * class bind with the appropriate {@link ILoggerFactory} instance. - * - * @author Ceki Gülcü - */ -public interface LoggerFactoryBinder { - - /** - * Return the instance of {@link ILoggerFactory} that - * {@link org.slf4j.LoggerFactory} class should bind to. - * - * @return the instance of {@link ILoggerFactory} that - * {@link org.slf4j.LoggerFactory} class should bind to. - */ - public ILoggerFactory getLoggerFactory(); - - /** - * The String form of the {@link ILoggerFactory} object that this - * LoggerFactoryBinder instance is intended to return. - * - *

This method allows the developer to 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(); -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.spi; + +import org.slf4j.ILoggerFactory; + +/** + * An internal interface which helps the static {@link org.slf4j.LoggerFactory} + * class bind with the appropriate {@link ILoggerFactory} instance. + * + * @author Ceki Gülcü + */ +public interface LoggerFactoryBinder { + + /** + * Return the instance of {@link ILoggerFactory} that + * {@link org.slf4j.LoggerFactory} class should bind to. + * + * @return the instance of {@link ILoggerFactory} that + * {@link org.slf4j.LoggerFactory} class should bind to. + */ + public ILoggerFactory getLoggerFactory(); + + /** + * The String form of the {@link ILoggerFactory} object that this + * LoggerFactoryBinder instance is intended to return. + * + *

This method allows the developer to 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 bc9bbb76..74aa150b 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/MDCAdapter.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/MDCAdapter.java @@ -1,91 +1,91 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.spi; - -import java.util.Map; - -/** - * This interface abstracts the service offered by various MDC - * implementations. - * - * @author Ceki Gülcü - * @since 1.4.1 - */ -public interface MDCAdapter { - - /** - * Put a context value (the val parameter) as identified with - * the key parameter into the current thread's context map. - * The key parameter cannot be null. The 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); - - /** - * Remove the the context identified by the key parameter. - * The key parameter cannot be null. - * - *

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

+ * This method does nothing if there is no previous value + * associated with key. + */ + public void remove(String key); + + /** + * Clear all entries in the MDC. + */ + public void clear(); + + /** + * Return a copy of the current thread's context map, with keys and + * values of type String. Returned value may be null. + * + * @return A copy of the current thread's context map. May be null. + * @since 1.5.1 + */ + public Map getCopyOfContextMap(); + + /** + * Set the current thread's context map by first clearing any existing + * map and then copying the map passed as parameter. The context map + * parameter must only contain keys and values of type String. + * + * @param contextMap must contain only keys and values of type String + * + * @since 1.5.1 + */ + public void setContextMap(Map contextMap); +} diff --git a/slf4j-api/src/main/java/org/slf4j/spi/MarkerFactoryBinder.java b/slf4j-api/src/main/java/org/slf4j/spi/MarkerFactoryBinder.java index fc01d178..2a96e19d 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/MarkerFactoryBinder.java +++ b/slf4j-api/src/main/java/org/slf4j/spi/MarkerFactoryBinder.java @@ -1,67 +1,67 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.spi; - -import org.slf4j.IMarkerFactory; - - -/** - * An internal interface which helps the static {@link org.slf4j.MarkerFactory} - * class bind with the appropriate {@link IMarkerFactory} instance. - * - * @author Ceki Gülcü - */ -public interface MarkerFactoryBinder { - - /** - * Return the instance of {@link IMarkerFactory} that - * {@link org.slf4j.MarkerFactory} class should bind to. - * - * @return the instance of {@link IMarkerFactory} that - * {@link org.slf4j.MarkerFactory} class should bind to. - */ - public IMarkerFactory getMarkerFactory(); - - /** - * The String form of the {@link IMarkerFactory} object that this - * MarkerFactoryBinder instance is intended to return. - * - *

This method allows the developer to 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(); -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.spi; + +import org.slf4j.IMarkerFactory; + + +/** + * An internal interface which helps the static {@link org.slf4j.MarkerFactory} + * class bind with the appropriate {@link IMarkerFactory} instance. + * + * @author Ceki Gülcü + */ +public interface MarkerFactoryBinder { + + /** + * Return the instance of {@link IMarkerFactory} that + * {@link org.slf4j.MarkerFactory} class should bind to. + * + * @return the instance of {@link IMarkerFactory} that + * {@link org.slf4j.MarkerFactory} class should bind to. + */ + public IMarkerFactory getMarkerFactory(); + + /** + * The String form of the {@link IMarkerFactory} object that this + * MarkerFactoryBinder instance is intended to return. + * + *

This method allows the developer to 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/main/java/org/slf4j/spi/package.html b/slf4j-api/src/main/java/org/slf4j/spi/package.html index 242f19d5..13ea8923 100644 --- a/slf4j-api/src/main/java/org/slf4j/spi/package.html +++ b/slf4j-api/src/main/java/org/slf4j/spi/package.html @@ -1,8 +1,8 @@ - - - - -Classes and interfaces which are internal to SLF4J. Under most -circumstances SLF4J users should be oblivious even to the existence of -this package. + + + + +Classes and interfaces which are internal to SLF4J. Under most +circumstances SLF4J users should be oblivious even to the existence of +this package. \ No newline at end of file diff --git a/slf4j-api/src/main/resources/META-INF/MANIFEST.MF b/slf4j-api/src/main/resources/META-INF/MANIFEST.MF index 732e527c..9dfbf9f4 100644 --- a/slf4j-api/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-api/src/main/resources/META-INF/MANIFEST.MF @@ -1,8 +1,8 @@ -Implementation-Title: slf4j-api -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.api -Bundle-Name: slf4j-api -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.3 -Export-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j.impl;version=${slf4j.api.minimum.compatible.version} +Implementation-Title: slf4j-api +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.api +Bundle-Name: slf4j-api +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.3 +Export-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j.impl;version=${slf4j.api.minimum.compatible.version} diff --git a/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java b/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java index 23249a7b..af94e95b 100644 --- a/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java +++ b/slf4j-api/src/test/java/org/slf4j/BasicMarkerTest.java @@ -1,196 +1,196 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j; - -import java.util.Iterator; - -import junit.framework.TestCase; - -import org.slf4j.helpers.BasicMarkerFactory; - -/** - * Unit test BasicMarker - * - * @author Ceki Gülcü - * @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"; - - final IMarkerFactory factory; - final Marker blue; - final Marker red; - final Marker green; - final Marker comp; - final Marker multiComp; - - short diff = Differentiator.getDiffentiator(); - - public BasicMarkerTest() { - factory = new BasicMarkerFactory(); - - blue = factory.getMarker(BLUE_STR); - red = factory.getMarker(RED_STR); - green = factory.getMarker(GREEN_STR); - comp = factory.getMarker(COMP_STR); - comp.add(blue); - - multiComp = factory.getMarker(MULTI_COMP_STR); - multiComp.add(green); - multiComp.add(comp); - } - - 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); - } - - // 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 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)); - } - -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j; + +import java.util.Iterator; + +import junit.framework.TestCase; + +import org.slf4j.helpers.BasicMarkerFactory; + +/** + * Unit test BasicMarker + * + * @author Ceki Gülcü + * @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"; + + final IMarkerFactory factory; + final Marker blue; + final Marker red; + final Marker green; + final Marker comp; + final Marker multiComp; + + short diff = Differentiator.getDiffentiator(); + + public BasicMarkerTest() { + factory = new BasicMarkerFactory(); + + blue = factory.getMarker(BLUE_STR); + red = factory.getMarker(RED_STR); + green = factory.getMarker(GREEN_STR); + comp = factory.getMarker(COMP_STR); + comp.add(blue); + + multiComp = factory.getMarker(MULTI_COMP_STR); + multiComp.add(green); + multiComp.add(comp); + } + + 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); + } + + // 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 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)); + } + +} diff --git a/slf4j-api/src/test/java/org/slf4j/Differentiator.java b/slf4j-api/src/test/java/org/slf4j/Differentiator.java index b7795267..e40991f1 100644 --- a/slf4j-api/src/test/java/org/slf4j/Differentiator.java +++ b/slf4j-api/src/test/java/org/slf4j/Differentiator.java @@ -1,37 +1,37 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - - -package org.slf4j; - -import java.util.Random; - -public class Differentiator { - - static Random random = new Random(System.currentTimeMillis()); - - static public short getDiffentiator() { - return (short) random.nextInt(Short.MAX_VALUE); - } -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +package org.slf4j; + +import java.util.Random; + +public class Differentiator { + + static Random random = new Random(System.currentTimeMillis()); + + static public short getDiffentiator() { + return (short) random.nextInt(Short.MAX_VALUE); + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java b/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java index b51f8833..e906513a 100644 --- a/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java +++ b/slf4j-api/src/test/java/org/slf4j/NoBindingTest.java @@ -1,25 +1,25 @@ -package org.slf4j; - -import junit.framework.TestCase; - -public class NoBindingTest extends TestCase { - - public void testLogger() { - try { - Logger logger = LoggerFactory.getLogger(NoBindingTest.class); - logger.debug("hello"); - fail("slf4j-api does not ship with a binding"); - } catch (NoClassDefFoundError e) { - - } - } - - public void testMDC() { - try { - MDC.put("k", "v"); - fail("slf4j-api does not ship with a binding"); - } catch (NoClassDefFoundError e) { - - } - } -} +package org.slf4j; + +import junit.framework.TestCase; + +public class NoBindingTest extends TestCase { + + public void testLogger() { + try { + Logger logger = LoggerFactory.getLogger(NoBindingTest.class); + logger.debug("hello"); + fail("slf4j-api does not ship with a binding"); + } catch (NoClassDefFoundError e) { + + } + } + + public void testMDC() { + try { + MDC.put("k", "v"); + fail("slf4j-api does not ship with a binding"); + } catch (NoClassDefFoundError e) { + + } + } +} 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 7e5bf58f..8e8b97a4 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/BogoPerf.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/BogoPerf.java @@ -1,159 +1,159 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.helpers; - -import junit.framework.AssertionFailedError; - -/** - * BogoPerf is used to check that the time required to perform a certain - * operation does not deteriorate over time. BogoPerf adjusts to the CPU speed - * and capabilities of the host. - * - * @author Ceki Gülcü - * - */ -public class BogoPerf { - - private static long NANOS_IN_ONE_SECOND = 1000 * 1000 * 1000; - private static int INITIAL_N = 1000; - private static int LAST_N = 100; - private static int SLACK_FACTOR = 3; - - static { - // let the JIT warm up - computeBogoIPS(INITIAL_N); - double bogo_ips = computeBogoIPS(INITIAL_N); - System.out.println("Host runs at " + bogo_ips + " BIPS"); - } - - /** - * Compute bogoInstructions per second - *

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

+ * on a 3.2 Ghz Pentium D CPU (around 2007), we obtain about 9'000 bogoIPS. + * + * @param N + * number of bogoInstructions to average over in order to + * compute the result + * @return bogo Instructions Per Second + */ + private static double computeBogoIPS(int N) { + long begin = System.nanoTime(); + + for (int i = 0; i < N; i++) { + bogoInstruction(); + } + long end = System.nanoTime(); + + // duration + double D = end - begin; + // average duration per instruction + double avgDPIS = D / N; + // System.out.println(D + " nanos for " + N + " instructions"); + // System.out.println(avgD + " nanos per instruction"); + + double bogoIPS = NANOS_IN_ONE_SECOND / avgDPIS; + // System.out.println(bogoIPS + " bogoIPS"); + + return bogoIPS; + } + + private static void bogoInstruction() { + // use our own random number generator, independent of the host JDK + MyRandom myRandom = new MyRandom(100); + int len = 150; + int[] intArray = new int[len]; + for (int i = 0; i < len; i++) { + intArray[i] = myRandom.nextInt(); + } + // use our own sort algorithm, independent of the host JDK + BubbleSort.sort(intArray); + } + + /** + * Computed the BogoIPS for this host CPU. + * + * @return + */ + public static double currentBIPS() { + return computeBogoIPS(LAST_N); + } + + static double min(double a, double b) { + return (a <= b) ? a : b; + } + + /** + * Assertion used for values that decrease with faster CPUs, typically + * the time (duration) needed to perform a task. + * + * @param currentDuration + * @param referenceDuration + * @param referenceBIPS + * @throws AssertionFailedError + */ + public static void assertDuration(double currentDuration, + long referenceDuration, double referenceBIPS) throws AssertionFailedError { + double ajustedDuration = adjustExpectedDuration(referenceDuration, + referenceBIPS); + if (currentDuration > ajustedDuration * SLACK_FACTOR) { + throw new AssertionFailedError("current duration " + currentDuration + + " exceeded expected " + ajustedDuration + " (adjusted reference), " + + referenceDuration + " (raw reference)"); + } + } + + /** + * Assertion used for values that increase with faster CPUs, typically + * the number of operations accomplished per unit of time. + * + * @param currentPerformance + * @param referencePerformance + * @param referenceBIPS + * @throws AssertionFailedError + */ + public static void assertPerformance(double currentPerformance, + long referencePerformance, double referenceBIPS) + throws AssertionFailedError { + double ajustedPerf = adjustExpectedPerformance(referencePerformance, + referenceBIPS); + if (currentPerformance * SLACK_FACTOR < ajustedPerf) { + throw new AssertionFailedError(currentPerformance + " below expected " + + ajustedPerf + " (adjusted), " + referencePerformance + " (raw)"); + } + } + + private static double adjustExpectedPerformance(long referenceDuration, + double referenceBIPS) { + double currentBIPS = currentBIPS(); + return referenceDuration * (currentBIPS / referenceBIPS); + } + + private static double adjustExpectedDuration(long referenceDuration, + double referenceBIPS) { + double currentBIPS = currentBIPS(); + System.out.println("currentBIPS=" + currentBIPS + " BIPS"); + return referenceDuration * (referenceBIPS / currentBIPS); + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSort.java b/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSort.java index 45b58f30..a1b55ebc 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSort.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSort.java @@ -1,50 +1,50 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.helpers; - -/** - * This class is used internally by BogoPerf, hence the package private - * (default) access. - * - * @author Ceki - */ -class BubbleSort { - - static void sort(int[] a) { - int len = a.length; - for (int i = 0; i < len - 1; i++) { - for (int j = 0; j < len - 1 - i; j++) { - if (a[j] > a[j + 1]) { - swap(a, j, j + 1); - } - } - } - } - static void swap(int[] a, int i, int j) { - int t = a[i]; - a[i] = a[j]; - a[j] = t; - } -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.helpers; + +/** + * This class is used internally by BogoPerf, hence the package private + * (default) access. + * + * @author Ceki + */ +class BubbleSort { + + static void sort(int[] a) { + int len = a.length; + for (int i = 0; i < len - 1; i++) { + for (int j = 0; j < len - 1 - i; j++) { + if (a[j] > a[j + 1]) { + swap(a, j, j + 1); + } + } + } + } + static void swap(int[] a, int i, int j) { + int t = a[i]; + a[i] = a[j]; + a[j] = t; + } +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSortTest.java b/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSortTest.java index 8106c226..662f5e27 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSortTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/BubbleSortTest.java @@ -1,101 +1,101 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.helpers; - -import java.util.Arrays; -import java.util.Random; - -import junit.framework.TestCase; - -/** - * Test that our BubbleSort algorithm is correctly implemented. - * - * @author Ceki - * - */ -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; - } - BubbleSort.sort(a); - Arrays.sort(witness); - assertTrue(Arrays.equals(witness, a)); - } - -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.helpers; + +import java.util.Arrays; +import java.util.Random; + +import junit.framework.TestCase; + +/** + * Test that our BubbleSort algorithm is correctly implemented. + * + * @author Ceki + * + */ +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; + } + 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 bddbcbbd..3c6f2366 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterPerfTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterPerfTest.java @@ -1,58 +1,58 @@ -package org.slf4j.helpers; - -import java.text.MessageFormat; - -import junit.framework.TestCase; - -public class MessageFormatterPerfTest extends TestCase { - - Integer i1 = new Integer(1); - static long RUN_LENGTH = 100000; - static long REFERENCE_BIPS = 9000; - - 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() { - slf4jMessageFormatter(RUN_LENGTH); - double duration = slf4jMessageFormatter(RUN_LENGTH); - long referencePerf = 140; - BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS); - } - - public double slf4jMessageFormatter(long len) { - String s = ""; - s += ""; // keep compiler happy - long start = System.currentTimeMillis(); - for (int i = 0; i < len; i++) { - s = MessageFormatter.format("This is some rather short message {} ", i1); - } - long end = System.currentTimeMillis(); - return (1.0*end - start); - } - public double jdkMessageFormatter(long len) { - 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); - } - -} +package org.slf4j.helpers; + +import java.text.MessageFormat; + +import junit.framework.TestCase; + +public class MessageFormatterPerfTest extends TestCase { + + Integer i1 = new Integer(1); + static long RUN_LENGTH = 100000; + static long REFERENCE_BIPS = 9000; + + 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() { + slf4jMessageFormatter(RUN_LENGTH); + double duration = slf4jMessageFormatter(RUN_LENGTH); + long referencePerf = 140; + BogoPerf.assertDuration(duration, referencePerf, REFERENCE_BIPS); + } + + public double slf4jMessageFormatter(long len) { + String s = ""; + s += ""; // keep compiler happy + long start = System.currentTimeMillis(); + for (int i = 0; i < len; i++) { + s = MessageFormatter.format("This is some rather short message {} ", i1); + } + long end = System.currentTimeMillis(); + return (1.0*end - start); + } + public double jdkMessageFormatter(long len) { + String s = ""; + s += ""; // keep compiler happy + long start = System.currentTimeMillis(); + Object[] oa = new Object[] {i1}; + for (int i = 0; i < len; i++) { + s = MessageFormat.format("This is some rather short message {0}", oa); + } + long end = System.currentTimeMillis(); + return (1.0*end - start); + } + +} diff --git a/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java b/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java index 27428a6b..829cd0f4 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/MessageFormatterTest.java @@ -1,286 +1,286 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.CH - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.helpers; - -import junit.framework.TestCase; - -/** - * @author Ceki Gulcu - * - */ -public class MessageFormatterTest extends TestCase { - - 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; - - - public void testNull() { - result = MessageFormatter.format(null, i1); - assertEquals(null, result); - } - - public void testNullParam() { - result = MessageFormatter.format("Value is {}.", null); - assertEquals("Value is null.", result); - - result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, null); - assertEquals("Val1 is null, val2 is null.", result); - - result = MessageFormatter.format("Val1 is {}, val2 is {}.", i1, null); - assertEquals("Val1 is 1, val2 is null.", result); - - result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, i2); - assertEquals("Val1 is null, val2 is 2.", result); - - result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", - new Integer[] { null, null, null }); - 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 }); - 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 }); - assertEquals("Val1 is null, val2 is null, val3 is 3", result); - } - - public void testOneParameter() { - result = MessageFormatter.format("Value is {}.", i3); - assertEquals("Value is 3.", result); - - result = MessageFormatter.format("Value is {", i3); - assertEquals("Value is {", result); - - result = MessageFormatter.format("{} is larger than 2.", i3); - assertEquals("3 is larger than 2.", result); - - result = MessageFormatter.format("No subst", i3); - assertEquals("No subst", result); - - result = MessageFormatter.format("Incorrect {subst", i3); - assertEquals("Incorrect {subst", result); - - result = MessageFormatter.format("Value is {bla} {}", i3); - assertEquals("Value is {bla} 3", result); - - result = MessageFormatter.format("Escaped \\{} subst", i3); - assertEquals("Escaped {} subst", result); - - result = MessageFormatter.format("{Escaped", i3); - assertEquals("{Escaped", result); - - result = MessageFormatter.format("\\{}Escaped", i3); - assertEquals("{}Escaped", result); - - result = MessageFormatter.format("File name is {{}}.", "App folder.zip"); - assertEquals("File name is {App folder.zip}.", result); - - // escaping the escape character - result = MessageFormatter - .format("File name is C:\\\\{}.", "App folder.zip"); - assertEquals("File name is C:\\App folder.zip.", result); - } - - public void testTwoParameters() { - result = MessageFormatter.format("Value {} is smaller than {}.", i1, i2); - assertEquals("Value 1 is smaller than 2.", result); - - result = MessageFormatter.format("Value {} is smaller than {}", i1, i2); - assertEquals("Value 1 is smaller than 2", result); - - result = MessageFormatter.format("{}{}", i1, i2); - assertEquals("12", result); - - result = MessageFormatter.format("Val1={}, Val2={", i1, i2); - assertEquals("Val1=1, Val2={", result); - - result = MessageFormatter.format("Value {} is smaller than \\{}", i1, i2); - assertEquals("Value 1 is smaller than {}", result); - - result = MessageFormatter.format("Value {} is smaller than \\{} tail", i1, - i2); - assertEquals("Value 1 is smaller than {} tail", result); - - result = MessageFormatter.format("Value {} is smaller than \\{", i1, i2); - assertEquals("Value 1 is smaller than \\{", result); - - result = MessageFormatter - .format("Value {} is smaller than {tail", i1, i2); - assertEquals("Value 1 is smaller than {tail", result); - - result = MessageFormatter.format("Value \\{} is smaller than {}", i1, i2); - assertEquals("Value {} is smaller than 1", result); - } - - - public void testExceptionInToString() { - Object o = new Object() { - public String toString() { - throw new IllegalStateException("a"); - } - }; - result = MessageFormatter.format("Troublesome object {}", o); - assertEquals("Troublesome object [FAILED toString()]", result); - - } - - public void testNullArray() { - String msg0 = "msg0"; - String msg1 = "msg1 {}"; - String msg2 = "msg2 {} {}"; - String msg3 = "msg3 {} {} {}"; - - Object[] args = null; - - result = MessageFormatter.arrayFormat(msg0, args); - assertEquals(msg0, result); - - result = MessageFormatter.arrayFormat(msg1, args); - assertEquals(msg1, result); - - result = MessageFormatter.arrayFormat(msg2, args); - assertEquals(msg2, result); - - result = MessageFormatter.arrayFormat(msg3, args); - assertEquals(msg3, result); - } - - // tests the case when the parameters are supplied in a single array - public void testArrayFormat() { - result = MessageFormatter.arrayFormat( - "Value {} is smaller than {} and {}.", ia0); - assertEquals("Value 1 is smaller than 2 and 3.", result); - - result = MessageFormatter.arrayFormat("{}{}{}", ia0); - assertEquals("123", result); - - result = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia0); - assertEquals("Value 1 is smaller than 2.", result); - - result = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia0); - assertEquals("Value 1 is smaller than 2", result); - - result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0); - assertEquals("Val=1, {, Val=2", result); - - result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0); - assertEquals("Val=1, {, Val=2", result); - - result = MessageFormatter.arrayFormat("Val1={}, Val2={", ia0); - assertEquals("Val1=1, Val2={", result); - } - - public void testArrayValues() { - Integer p0 = i1; - Integer[] p1 = new Integer[] { i2, i3 }; - - result = MessageFormatter.format("{}{}", p0, p1); - assertEquals("1[2, 3]", result); - - // Integer[] - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", p1 }); - assertEquals("a[2, 3]", result); - - // byte[] - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", - new byte[] { 1, 2 } }); - assertEquals("a[1, 2]", result); - - // int[] - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", - new int[] { 1, 2 } }); - assertEquals("a[1, 2]", result); - - // float[] - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", - new float[] { 1, 2 } }); - assertEquals("a[1.0, 2.0]", result); - - // double[] - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", - new double[] { 1, 2 } }); - assertEquals("a[1.0, 2.0]", result); - - } - - public void testMultiDimensionalArrayValues() { - Integer[][] multiIntegerA = new Integer[][] { ia0, ia1 }; - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", - multiIntegerA }); - assertEquals("a[[1, 2, 3], [10, 20, 30]]", result); - - int[][] multiIntA = new int[][] { { 1, 2 }, { 10, 20 } }; - result = MessageFormatter.arrayFormat("{}{}", - new Object[] { "a", multiIntA }); - assertEquals("a[[1, 2], [10, 20]]", result); - - float[][] multiFloatA = new float[][] { { 1, 2 }, { 10, 20 } }; - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", - multiFloatA }); - assertEquals("a[[1.0, 2.0], [10.0, 20.0]]", result); - - Object[][] multiOA = new Object[][] { ia0, ia1 }; - result = MessageFormatter - .arrayFormat("{}{}", new Object[] { "a", multiOA }); - assertEquals("a[[1, 2, 3], [10, 20, 30]]", result); - - Object[][][] _3DOA = new Object[][][] { multiOA, multiOA }; - result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", _3DOA }); - assertEquals("a[[[1, 2, 3], [10, 20, 30]], [[1, 2, 3], [10, 20, 30]]]", - result); - } - - public void testCyclicArrays() { - { - Object[] cyclicA = new Object[1]; - cyclicA[0] = cyclicA; - assertEquals("[[...]]", MessageFormatter.arrayFormat("{}", cyclicA)); - } - { - 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)); - } - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.CH + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.helpers; + +import junit.framework.TestCase; + +/** + * @author Ceki Gulcu + * + */ +public class MessageFormatterTest extends TestCase { + + 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; + + + public void testNull() { + result = MessageFormatter.format(null, i1); + assertEquals(null, result); + } + + public void testNullParam() { + result = MessageFormatter.format("Value is {}.", null); + assertEquals("Value is null.", result); + + result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, null); + assertEquals("Val1 is null, val2 is null.", result); + + result = MessageFormatter.format("Val1 is {}, val2 is {}.", i1, null); + assertEquals("Val1 is 1, val2 is null.", result); + + result = MessageFormatter.format("Val1 is {}, val2 is {}.", null, i2); + assertEquals("Val1 is null, val2 is 2.", result); + + result = MessageFormatter.arrayFormat("Val1 is {}, val2 is {}, val3 is {}", + new Integer[] { null, null, null }); + 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 }); + 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 }); + assertEquals("Val1 is null, val2 is null, val3 is 3", result); + } + + public void testOneParameter() { + result = MessageFormatter.format("Value is {}.", i3); + assertEquals("Value is 3.", result); + + result = MessageFormatter.format("Value is {", i3); + assertEquals("Value is {", result); + + result = MessageFormatter.format("{} is larger than 2.", i3); + assertEquals("3 is larger than 2.", result); + + result = MessageFormatter.format("No subst", i3); + assertEquals("No subst", result); + + result = MessageFormatter.format("Incorrect {subst", i3); + assertEquals("Incorrect {subst", result); + + result = MessageFormatter.format("Value is {bla} {}", i3); + assertEquals("Value is {bla} 3", result); + + result = MessageFormatter.format("Escaped \\{} subst", i3); + assertEquals("Escaped {} subst", result); + + result = MessageFormatter.format("{Escaped", i3); + assertEquals("{Escaped", result); + + result = MessageFormatter.format("\\{}Escaped", i3); + assertEquals("{}Escaped", result); + + result = MessageFormatter.format("File name is {{}}.", "App folder.zip"); + assertEquals("File name is {App folder.zip}.", result); + + // escaping the escape character + result = MessageFormatter + .format("File name is C:\\\\{}.", "App folder.zip"); + assertEquals("File name is C:\\App folder.zip.", result); + } + + public void testTwoParameters() { + result = MessageFormatter.format("Value {} is smaller than {}.", i1, i2); + assertEquals("Value 1 is smaller than 2.", result); + + result = MessageFormatter.format("Value {} is smaller than {}", i1, i2); + assertEquals("Value 1 is smaller than 2", result); + + result = MessageFormatter.format("{}{}", i1, i2); + assertEquals("12", result); + + result = MessageFormatter.format("Val1={}, Val2={", i1, i2); + assertEquals("Val1=1, Val2={", result); + + result = MessageFormatter.format("Value {} is smaller than \\{}", i1, i2); + assertEquals("Value 1 is smaller than {}", result); + + result = MessageFormatter.format("Value {} is smaller than \\{} tail", i1, + i2); + assertEquals("Value 1 is smaller than {} tail", result); + + result = MessageFormatter.format("Value {} is smaller than \\{", i1, i2); + assertEquals("Value 1 is smaller than \\{", result); + + result = MessageFormatter + .format("Value {} is smaller than {tail", i1, i2); + assertEquals("Value 1 is smaller than {tail", result); + + result = MessageFormatter.format("Value \\{} is smaller than {}", i1, i2); + assertEquals("Value {} is smaller than 1", result); + } + + + public void testExceptionInToString() { + Object o = new Object() { + public String toString() { + throw new IllegalStateException("a"); + } + }; + result = MessageFormatter.format("Troublesome object {}", o); + assertEquals("Troublesome object [FAILED toString()]", result); + + } + + public void testNullArray() { + String msg0 = "msg0"; + String msg1 = "msg1 {}"; + String msg2 = "msg2 {} {}"; + String msg3 = "msg3 {} {} {}"; + + Object[] args = null; + + result = MessageFormatter.arrayFormat(msg0, args); + assertEquals(msg0, result); + + result = MessageFormatter.arrayFormat(msg1, args); + assertEquals(msg1, result); + + result = MessageFormatter.arrayFormat(msg2, args); + assertEquals(msg2, result); + + result = MessageFormatter.arrayFormat(msg3, args); + assertEquals(msg3, result); + } + + // tests the case when the parameters are supplied in a single array + public void testArrayFormat() { + result = MessageFormatter.arrayFormat( + "Value {} is smaller than {} and {}.", ia0); + assertEquals("Value 1 is smaller than 2 and 3.", result); + + result = MessageFormatter.arrayFormat("{}{}{}", ia0); + assertEquals("123", result); + + result = MessageFormatter.arrayFormat("Value {} is smaller than {}.", ia0); + assertEquals("Value 1 is smaller than 2.", result); + + result = MessageFormatter.arrayFormat("Value {} is smaller than {}", ia0); + assertEquals("Value 1 is smaller than 2", result); + + result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0); + assertEquals("Val=1, {, Val=2", result); + + result = MessageFormatter.arrayFormat("Val={}, {, Val={}", ia0); + assertEquals("Val=1, {, Val=2", result); + + result = MessageFormatter.arrayFormat("Val1={}, Val2={", ia0); + assertEquals("Val1=1, Val2={", result); + } + + public void testArrayValues() { + Integer p0 = i1; + Integer[] p1 = new Integer[] { i2, i3 }; + + result = MessageFormatter.format("{}{}", p0, p1); + assertEquals("1[2, 3]", result); + + // Integer[] + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", p1 }); + assertEquals("a[2, 3]", result); + + // byte[] + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", + new byte[] { 1, 2 } }); + assertEquals("a[1, 2]", result); + + // int[] + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", + new int[] { 1, 2 } }); + assertEquals("a[1, 2]", result); + + // float[] + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", + new float[] { 1, 2 } }); + assertEquals("a[1.0, 2.0]", result); + + // double[] + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", + new double[] { 1, 2 } }); + assertEquals("a[1.0, 2.0]", result); + + } + + public void testMultiDimensionalArrayValues() { + Integer[][] multiIntegerA = new Integer[][] { ia0, ia1 }; + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", + multiIntegerA }); + assertEquals("a[[1, 2, 3], [10, 20, 30]]", result); + + int[][] multiIntA = new int[][] { { 1, 2 }, { 10, 20 } }; + result = MessageFormatter.arrayFormat("{}{}", + new Object[] { "a", multiIntA }); + assertEquals("a[[1, 2], [10, 20]]", result); + + float[][] multiFloatA = new float[][] { { 1, 2 }, { 10, 20 } }; + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", + multiFloatA }); + assertEquals("a[[1.0, 2.0], [10.0, 20.0]]", result); + + Object[][] multiOA = new Object[][] { ia0, ia1 }; + result = MessageFormatter + .arrayFormat("{}{}", new Object[] { "a", multiOA }); + assertEquals("a[[1, 2, 3], [10, 20, 30]]", result); + + Object[][][] _3DOA = new Object[][][] { multiOA, multiOA }; + result = MessageFormatter.arrayFormat("{}{}", new Object[] { "a", _3DOA }); + assertEquals("a[[[1, 2, 3], [10, 20, 30]], [[1, 2, 3], [10, 20, 30]]]", + result); + } + + public void testCyclicArrays() { + { + Object[] cyclicA = new Object[1]; + cyclicA[0] = cyclicA; + assertEquals("[[...]]", MessageFormatter.arrayFormat("{}", cyclicA)); + } + { + 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)); + } + } +} 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 702164e7..e7f0ccd1 100644 --- a/slf4j-api/src/test/java/org/slf4j/helpers/MyRandom.java +++ b/slf4j-api/src/test/java/org/slf4j/helpers/MyRandom.java @@ -1,56 +1,56 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.helpers; - - -class MyRandom { - - private static final long serialVersionUID = -907426287094698288L; - - private final static long m = 200000000041L; // a prime number - private final static long a = 2000000011L; // a prime number - - long y; - long unused; - int bits = 32; - - public MyRandom() { - this(System.nanoTime()); - } - - - public MyRandom(long seed) { - this.y = seed; - } - - - int nextInt() { - // we don't really care about the randomness of this - // generator - y = (a*y + 1) % m; - unused = y >>> (48-bits); // just exercise the >>> operator - return (int)(y); - } -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.helpers; + + +class MyRandom { + + private static final long serialVersionUID = -907426287094698288L; + + private final static long m = 200000000041L; // a prime number + private final static long a = 2000000011L; // a prime number + + long y; + long unused; + int bits = 32; + + public MyRandom() { + this(System.nanoTime()); + } + + + public MyRandom(long seed) { + this.y = seed; + } + + + int nextInt() { + // we don't really care about the randomness of this + // generator + y = (a*y + 1) % m; + unused = y >>> (48-bits); // just exercise the >>> operator + return (int)(y); + } +} diff --git a/slf4j-ext/pom.xml b/slf4j-ext/pom.xml index 3448f30b..636f9b09 100644 --- a/slf4j-ext/pom.xml +++ b/slf4j-ext/pom.xml @@ -1,105 +1,105 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - slf4j-ext - jar - SLF4J Extensions Module - - http://www.slf4j.org - Extensions to the SLF4J API - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - ${parent.version} - test - - - ch.qos.cal10n - cal10n-api - - - javassist - javassist - 3.4.GA - true - - - commons-lang - commons-lang - 2.4 - true - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.5 - 1.5 - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - false - once - plain - false - - **/AllTest.java - **/PackageTest.java - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - ${parsedVersion.osgiVersion} - ${project.description} - ${project.version} - org.slf4j.agent.AgentPremain - - ../../../../javassist/javassist/3.4.GA/javassist-3.4.GA.jar javassist-3.4.GA.jar javassist.jar - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - - - - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + slf4j-ext + jar + SLF4J Extensions Module + + http://www.slf4j.org + Extensions to the SLF4J API + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + ${parent.version} + test + + + ch.qos.cal10n + cal10n-api + + + javassist + javassist + 3.4.GA + true + + + commons-lang + commons-lang + 2.4 + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + false + once + plain + false + + **/AllTest.java + **/PackageTest.java + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + ${parsedVersion.osgiVersion} + ${project.description} + ${project.version} + org.slf4j.agent.AgentPremain + + ../../../../javassist/javassist/3.4.GA/javassist-3.4.GA.jar javassist-3.4.GA.jar javassist.jar + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + + + + + + + + + \ No newline at end of file diff --git a/slf4j-ext/src/main/java/org/slf4j/NDC.java b/slf4j-ext/src/main/java/org/slf4j/NDC.java index 2724f0f6..b85e35cd 100644 --- a/slf4j-ext/src/main/java/org/slf4j/NDC.java +++ b/slf4j-ext/src/main/java/org/slf4j/NDC.java @@ -1,61 +1,61 @@ -/* - * Copyright (c) 2004-2009 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -package org.slf4j; - -import org.slf4j.MDC; - -public class NDC { - public final static String PREFIX = "NDC"; - - private static int size() { - int i = 0; - while (true) { - String val = MDC.get(PREFIX + i); - if (val != null) { - i++; - } else { - break; - } - } - return i; - } - - public static void push(String val) { - int next = size(); - MDC.put(PREFIX + next, val); - } - - public static String pop() { - int next = size(); - if(next == 0) { - return ""; - } - int last = next-1; - String key = PREFIX+last; - String val = MDC.get(key); - MDC.remove(key); - return val; - } - -} +/* + * Copyright (c) 2004-2009 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package org.slf4j; + +import org.slf4j.MDC; + +public class NDC { + public final static String PREFIX = "NDC"; + + private static int size() { + int i = 0; + while (true) { + String val = MDC.get(PREFIX + i); + if (val != null) { + i++; + } else { + break; + } + } + return i; + } + + public static void push(String val) { + int next = size(); + MDC.put(PREFIX + next, val); + } + + public static String pop() { + int next = size(); + if(next == 0) { + return ""; + } + int last = next-1; + String key = PREFIX+last; + String val = MDC.get(key); + MDC.remove(key); + return val; + } + +} diff --git a/slf4j-ext/src/main/java/org/slf4j/agent/package.html b/slf4j-ext/src/main/java/org/slf4j/agent/package.html index ed68a70c..61726464 100644 --- a/slf4j-ext/src/main/java/org/slf4j/agent/package.html +++ b/slf4j-ext/src/main/java/org/slf4j/agent/package.html @@ -1,33 +1,33 @@ - - - - - - - - - -

"-javaagent" routines for SLF4J.

-

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

-

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

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

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

"-javaagent" routines for SLF4J.

+

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

+

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

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

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

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

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

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

+ * Contrary to {@link LoggerFactory#getLogger(String)} method of + * {@link LoggerFactory}, each call to {@link getLocLogger} produces a new + * instance of {@link LocLogger}. This should not matter because a LocLogger + * instance does have any state beyond that of the {@link Logger} in stance it + * wraps and its message conveyor. + * + * @author Ceki Gücü + * + */ +public class LocLoggerFactory { + + final IMessageConveyor imc; + + public LocLoggerFactory(IMessageConveyor imc) { + this.imc = imc; + } + + /** + * Get an LocLogger instance by name. + * + * @param name + * @return + */ + 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 + */ + @SuppressWarnings("unchecked") + public LocLogger getLocLogger(Class clazz) { + return getLocLogger(clazz.getName()); + } +} 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 8d422979..5ca7aebb 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/LoggerWrapper.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/LoggerWrapper.java @@ -1,868 +1,868 @@ -package org.slf4j.ext; - -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.helpers.MessageFormatter; -import org.slf4j.spi.LocationAwareLogger; - -/** - * A helper class wrapping an {@link org.slf4j.Logger} - * instance preserving location information if the wrapped - * instance supports it. - * - * @author Ralph Goers - * @author Ceki Gülcü - */ -public class LoggerWrapper implements Logger { - - // To ensure consistency between two instances sharing the same name (homonyms) - // a LoggerWrapper should not contain any state beyond - // the Logger instance it wraps. - // Note that 'instanceofLAL' directly depends on Logger. - // fqcn depend on the caller, but its value would not be different - // between successive invocations of a factory class - - protected final Logger logger; - final String fqcn; - // is this logger instance a LocationAwareLogger - protected final boolean instanceofLAL; - - public LoggerWrapper(Logger logger, String fqcn) { - this.logger = logger; - this.fqcn = fqcn; - if (logger instanceof LocationAwareLogger) { - instanceofLAL = true; - } else { - instanceofLAL = false; - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isTraceEnabled(Marker marker) { - return logger.isTraceEnabled(marker); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(String msg) { - if (!logger.isTraceEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.TRACE_INT, msg, null); - } else { - logger.trace(msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(String format, Object arg) { - if (!logger.isTraceEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.TRACE_INT, formattedMessage, null); - } else { - logger.trace(format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(String format, Object arg1, Object arg2) { - if (!logger.isTraceEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.TRACE_INT, formattedMessage, null); - } else { - logger.trace(format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(String format, Object[] argArray) { - if (!logger.isTraceEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.TRACE_INT, formattedMessage, null); - } else { - logger.trace(format, argArray); - } - } - - /** - * 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, t); - } else { - logger.trace(msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(Marker marker, String msg) { - if (!logger.isTraceEnabled()) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.TRACE_INT, msg, null); - } else { - logger.trace(marker, msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(Marker marker, String format, Object arg) { - if (!logger.isTraceEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.TRACE_INT, formattedMessage, null); - } else { - logger.trace(marker, format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(Marker marker, String format, Object arg1, Object arg2) { - if (!logger.isTraceEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.TRACE_INT, formattedMessage, null); - } else { - logger.trace(marker, format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(Marker marker, String format, Object[] argArray) { - if (!logger.isTraceEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.TRACE_INT, formattedMessage, null); - } else { - logger.trace(marker, format, argArray); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void trace(Marker marker, String msg, Throwable t) { - if (!logger.isTraceEnabled()) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.TRACE_INT, msg, t); - } else { - logger.trace(marker, msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isDebugEnabled(Marker marker) { - return logger.isDebugEnabled(marker); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String msg) { - if (!logger.isDebugEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.DEBUG_INT, msg, null); - } else { - logger.debug(msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String format, Object arg) { - if (!logger.isDebugEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.DEBUG_INT, formattedMessage, null); - } else { - logger.debug(format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String format, Object arg1, Object arg2) { - if (!logger.isDebugEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.DEBUG_INT, formattedMessage, null); - } else { - logger.debug(format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String format, Object[] argArray) { - if (!logger.isDebugEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.DEBUG_INT, formattedMessage, null); - } else { - logger.debug(format, argArray); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(String msg, Throwable t) { - if (!logger.isDebugEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.DEBUG_INT, msg, t); - } else { - logger.debug(msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(Marker marker, String msg) { - if (!logger.isDebugEnabled()) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.DEBUG_INT, msg, null); - } else { - logger.debug(marker, msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(Marker marker, String format, Object arg) { - if (!logger.isDebugEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.DEBUG_INT, formattedMessage, null); - } else { - logger.debug(marker, format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(Marker marker, String format, Object arg1, Object arg2) { - if (!logger.isDebugEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.DEBUG_INT, formattedMessage, null); - } else { - logger.debug(marker, format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(Marker marker, String format, Object[] argArray) { - if (!logger.isDebugEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.DEBUG_INT, formattedMessage, null); - } else { - logger.debug(marker, format, argArray); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void debug(Marker marker, String msg, Throwable t) { - if (!logger.isDebugEnabled()) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.DEBUG_INT, msg, t); - } else { - logger.debug(marker, msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isInfoEnabled(Marker marker) { - return logger.isInfoEnabled(marker); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(String msg) { - if (!logger.isInfoEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.INFO_INT, msg, null); - } else { - logger.info(msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(String format, Object arg) { - if (!logger.isInfoEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.INFO_INT, formattedMessage, null); - } else { - logger.info(format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(String format, Object arg1, Object arg2) { - if (!logger.isInfoEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.INFO_INT, formattedMessage, null); - } else { - logger.info(format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(String format, Object[] argArray) { - if (!logger.isInfoEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.INFO_INT, formattedMessage, null); - } else { - logger.info(format, argArray); - } - } - - /** - * 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, t); - } else { - logger.info(msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(Marker marker, String msg) { - if (!logger.isInfoEnabled()) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.INFO_INT, msg, null); - } else { - logger.info(marker, msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(Marker marker, String format, Object arg) { - if (!logger.isInfoEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.INFO_INT, formattedMessage, null); - } else { - logger.info(marker, format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(Marker marker, String format, Object arg1, Object arg2) { - if (!logger.isInfoEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.INFO_INT, formattedMessage, null); - } else { - logger.info(marker, format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(Marker marker, String format, Object[] argArray) { - if (!logger.isInfoEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.INFO_INT, formattedMessage, null); - } else { - logger.info(marker, format, argArray); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void info(Marker marker, String msg, Throwable t) { - if (!logger.isInfoEnabled()) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.INFO_INT, msg, t); - } else { - logger.info(marker, msg, t); - } - } - - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isWarnEnabled(Marker marker) { - return logger.isWarnEnabled(marker); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(String msg) { - if (!logger.isWarnEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.WARN_INT, msg, null); - } else { - logger.warn(msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(String format, Object arg) { - if (!logger.isWarnEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.WARN_INT, formattedMessage, null); - } else { - logger.warn(format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(String format, Object arg1, Object arg2) { - if (!logger.isWarnEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.WARN_INT, formattedMessage, null); - } else { - logger.warn(format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(String format, Object[] argArray) { - if (!logger.isWarnEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.WARN_INT, formattedMessage, null); - } else { - logger.warn(format, argArray); - } - } - - /** - * 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, t); - } else { - logger.warn(msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(Marker marker, String msg) { - if (!logger.isWarnEnabled()) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.WARN_INT, msg, null); - } else { - logger.warn(marker, msg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(Marker marker, String format, Object arg) { - if (!logger.isWarnEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.WARN_INT, formattedMessage, null); - } else { - logger.warn(marker, format, arg); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(Marker marker, String format, Object arg1, Object arg2) { - if (!logger.isWarnEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.WARN_INT, formattedMessage, null); - } else { - logger.warn(marker, format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(Marker marker, String format, Object[] argArray) { - if (!logger.isWarnEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.WARN_INT, formattedMessage, null); - } else { - logger.warn(marker, format, argArray); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void warn(Marker marker, String msg, Throwable t) { - if (!logger.isWarnEnabled()) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.WARN_INT, msg, t); - } else { - logger.warn(marker, msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public boolean isErrorEnabled(Marker marker) { - return logger.isErrorEnabled(marker); - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(String msg) { - if (!logger.isErrorEnabled()) - return; - - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.ERROR_INT, msg, null); - } 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); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.ERROR_INT, formattedMessage, 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); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.ERROR_INT, formattedMessage, null); - } else { - logger.error(format, arg1, arg2); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(String format, Object[] argArray) { - if (!logger.isErrorEnabled()) - return; - - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(null, fqcn, - LocationAwareLogger.ERROR_INT, formattedMessage, null); - } else { - logger.error(format, argArray); - } - } - - /** - * 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, 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()) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.ERROR_INT, msg, 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()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.ERROR_INT, formattedMessage, 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()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.format(format, arg1, arg2); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.ERROR_INT, formattedMessage, 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[] argArray) { - if (!logger.isErrorEnabled()) - return; - if (instanceofLAL) { - String formattedMessage = MessageFormatter.arrayFormat(format, argArray); - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.ERROR_INT, formattedMessage, null); - } else { - logger.error(marker, format, argArray); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public void error(Marker marker, String msg, Throwable t) { - if (!logger.isErrorEnabled()) - return; - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(marker, fqcn, - LocationAwareLogger.ERROR_INT, msg, t); - } else { - logger.error(marker, msg, t); - } - } - - /** - * Delegate to the appropriate method of the underlying logger. - */ - public String getName() { - return logger.getName(); - } -} +package org.slf4j.ext; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.helpers.MessageFormatter; +import org.slf4j.spi.LocationAwareLogger; + +/** + * A helper class wrapping an {@link org.slf4j.Logger} + * instance preserving location information if the wrapped + * instance supports it. + * + * @author Ralph Goers + * @author Ceki Gülcü + */ +public class LoggerWrapper implements Logger { + + // To ensure consistency between two instances sharing the same name (homonyms) + // a LoggerWrapper should not contain any state beyond + // the Logger instance it wraps. + // Note that 'instanceofLAL' directly depends on Logger. + // fqcn depend on the caller, but its value would not be different + // between successive invocations of a factory class + + protected final Logger logger; + final String fqcn; + // is this logger instance a LocationAwareLogger + protected final boolean instanceofLAL; + + public LoggerWrapper(Logger logger, String fqcn) { + this.logger = logger; + this.fqcn = fqcn; + if (logger instanceof LocationAwareLogger) { + instanceofLAL = true; + } else { + instanceofLAL = false; + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isTraceEnabled(Marker marker) { + return logger.isTraceEnabled(marker); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String msg) { + if (!logger.isTraceEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.TRACE_INT, msg, null); + } else { + logger.trace(msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String format, Object arg) { + if (!logger.isTraceEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.TRACE_INT, formattedMessage, null); + } else { + logger.trace(format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String format, Object arg1, Object arg2) { + if (!logger.isTraceEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.TRACE_INT, formattedMessage, null); + } else { + logger.trace(format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(String format, Object[] argArray) { + if (!logger.isTraceEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.TRACE_INT, formattedMessage, null); + } else { + logger.trace(format, argArray); + } + } + + /** + * 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, t); + } else { + logger.trace(msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(Marker marker, String msg) { + if (!logger.isTraceEnabled()) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.TRACE_INT, msg, null); + } else { + logger.trace(marker, msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(Marker marker, String format, Object arg) { + if (!logger.isTraceEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.TRACE_INT, formattedMessage, null); + } else { + logger.trace(marker, format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(Marker marker, String format, Object arg1, Object arg2) { + if (!logger.isTraceEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.TRACE_INT, formattedMessage, null); + } else { + logger.trace(marker, format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(Marker marker, String format, Object[] argArray) { + if (!logger.isTraceEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.TRACE_INT, formattedMessage, null); + } else { + logger.trace(marker, format, argArray); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void trace(Marker marker, String msg, Throwable t) { + if (!logger.isTraceEnabled()) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.TRACE_INT, msg, t); + } else { + logger.trace(marker, msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isDebugEnabled(Marker marker) { + return logger.isDebugEnabled(marker); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String msg) { + if (!logger.isDebugEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.DEBUG_INT, msg, null); + } else { + logger.debug(msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String format, Object arg) { + if (!logger.isDebugEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.DEBUG_INT, formattedMessage, null); + } else { + logger.debug(format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String format, Object arg1, Object arg2) { + if (!logger.isDebugEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.DEBUG_INT, formattedMessage, null); + } else { + logger.debug(format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String format, Object[] argArray) { + if (!logger.isDebugEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.DEBUG_INT, formattedMessage, null); + } else { + logger.debug(format, argArray); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(String msg, Throwable t) { + if (!logger.isDebugEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.DEBUG_INT, msg, t); + } else { + logger.debug(msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(Marker marker, String msg) { + if (!logger.isDebugEnabled()) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.DEBUG_INT, msg, null); + } else { + logger.debug(marker, msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(Marker marker, String format, Object arg) { + if (!logger.isDebugEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.DEBUG_INT, formattedMessage, null); + } else { + logger.debug(marker, format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(Marker marker, String format, Object arg1, Object arg2) { + if (!logger.isDebugEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.DEBUG_INT, formattedMessage, null); + } else { + logger.debug(marker, format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(Marker marker, String format, Object[] argArray) { + if (!logger.isDebugEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.DEBUG_INT, formattedMessage, null); + } else { + logger.debug(marker, format, argArray); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void debug(Marker marker, String msg, Throwable t) { + if (!logger.isDebugEnabled()) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.DEBUG_INT, msg, t); + } else { + logger.debug(marker, msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isInfoEnabled(Marker marker) { + return logger.isInfoEnabled(marker); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(String msg) { + if (!logger.isInfoEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.INFO_INT, msg, null); + } else { + logger.info(msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(String format, Object arg) { + if (!logger.isInfoEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.INFO_INT, formattedMessage, null); + } else { + logger.info(format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(String format, Object arg1, Object arg2) { + if (!logger.isInfoEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.INFO_INT, formattedMessage, null); + } else { + logger.info(format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(String format, Object[] argArray) { + if (!logger.isInfoEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.INFO_INT, formattedMessage, null); + } else { + logger.info(format, argArray); + } + } + + /** + * 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, t); + } else { + logger.info(msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(Marker marker, String msg) { + if (!logger.isInfoEnabled()) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.INFO_INT, msg, null); + } else { + logger.info(marker, msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(Marker marker, String format, Object arg) { + if (!logger.isInfoEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.INFO_INT, formattedMessage, null); + } else { + logger.info(marker, format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(Marker marker, String format, Object arg1, Object arg2) { + if (!logger.isInfoEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.INFO_INT, formattedMessage, null); + } else { + logger.info(marker, format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(Marker marker, String format, Object[] argArray) { + if (!logger.isInfoEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.INFO_INT, formattedMessage, null); + } else { + logger.info(marker, format, argArray); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void info(Marker marker, String msg, Throwable t) { + if (!logger.isInfoEnabled()) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.INFO_INT, msg, t); + } else { + logger.info(marker, msg, t); + } + } + + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isWarnEnabled(Marker marker) { + return logger.isWarnEnabled(marker); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String msg) { + if (!logger.isWarnEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.WARN_INT, msg, null); + } else { + logger.warn(msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String format, Object arg) { + if (!logger.isWarnEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.WARN_INT, formattedMessage, null); + } else { + logger.warn(format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String format, Object arg1, Object arg2) { + if (!logger.isWarnEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.WARN_INT, formattedMessage, null); + } else { + logger.warn(format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(String format, Object[] argArray) { + if (!logger.isWarnEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.WARN_INT, formattedMessage, null); + } else { + logger.warn(format, argArray); + } + } + + /** + * 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, t); + } else { + logger.warn(msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(Marker marker, String msg) { + if (!logger.isWarnEnabled()) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.WARN_INT, msg, null); + } else { + logger.warn(marker, msg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(Marker marker, String format, Object arg) { + if (!logger.isWarnEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.WARN_INT, formattedMessage, null); + } else { + logger.warn(marker, format, arg); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(Marker marker, String format, Object arg1, Object arg2) { + if (!logger.isWarnEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.WARN_INT, formattedMessage, null); + } else { + logger.warn(marker, format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(Marker marker, String format, Object[] argArray) { + if (!logger.isWarnEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.WARN_INT, formattedMessage, null); + } else { + logger.warn(marker, format, argArray); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void warn(Marker marker, String msg, Throwable t) { + if (!logger.isWarnEnabled()) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.WARN_INT, msg, t); + } else { + logger.warn(marker, msg, t); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public boolean isErrorEnabled(Marker marker) { + return logger.isErrorEnabled(marker); + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(String msg) { + if (!logger.isErrorEnabled()) + return; + + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.ERROR_INT, msg, null); + } 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); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.ERROR_INT, formattedMessage, 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); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.ERROR_INT, formattedMessage, null); + } else { + logger.error(format, arg1, arg2); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(String format, Object[] argArray) { + if (!logger.isErrorEnabled()) + return; + + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(null, fqcn, + LocationAwareLogger.ERROR_INT, formattedMessage, null); + } else { + logger.error(format, argArray); + } + } + + /** + * 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, 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()) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.ERROR_INT, msg, 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()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.ERROR_INT, formattedMessage, 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()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.format(format, arg1, arg2); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.ERROR_INT, formattedMessage, 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[] argArray) { + if (!logger.isErrorEnabled()) + return; + if (instanceofLAL) { + String formattedMessage = MessageFormatter.arrayFormat(format, argArray); + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.ERROR_INT, formattedMessage, null); + } else { + logger.error(marker, format, argArray); + } + } + + /** + * Delegate to the appropriate method of the underlying logger. + */ + public void error(Marker marker, String msg, Throwable t) { + if (!logger.isErrorEnabled()) + return; + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(marker, fqcn, + LocationAwareLogger.ERROR_INT, msg, 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/XLogger.java b/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java index 1e967ea2..10087def 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/XLogger.java @@ -1,197 +1,197 @@ -package org.slf4j.ext; - -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.MessageFormatter; -import org.slf4j.spi.LocationAwareLogger; - -/** - * A utility that provides standard mechanisms for logging certain kinds of - * activities. - * - * @author Ralph Goers - * @author Ceki Gülcü - */ -public class XLogger extends LoggerWrapper implements Logger { - - private static final String FQCN = XLogger.class.getName(); - static Marker FLOW_MARKER = MarkerFactory.getMarker("FLOW"); - static Marker ENTRY_MARKER = MarkerFactory.getMarker("ENTRY"); - static Marker EXIT_MARKER = MarkerFactory.getMarker("EXIT"); - - static Marker EXCEPTION_MARKER = MarkerFactory.getMarker("EXCEPTION"); - static Marker THROWING_MARKER = MarkerFactory.getMarker("THROWING"); - static Marker CATCHING_MARKER = MarkerFactory.getMarker("CATCHING"); - - static String EXIT_MESSAGE_0 = "exit"; - static String EXIT_MESSAGE_1 = "exit with ({})"; - - static String ENTRY_MESSAGE_0 = "entry"; - static String ENTRY_MESSAGE_1 = "entry with ({})"; - static String ENTRY_MESSAGE_2 = "entry with ({}, {})"; - static String ENTRY_MESSAGE_3 = "entry with ({}, {}, {})"; - static String ENTRY_MESSAGE_4 = "entry with ({}, {}, {}, {})"; - static int ENTRY_MESSAGE_ARRAY_LEN = 5; - static String[] ENTRY_MESSAGE_ARRAY = new String[ENTRY_MESSAGE_ARRAY_LEN]; - static { - ENTRY_MARKER.add(FLOW_MARKER); - EXIT_MARKER.add(FLOW_MARKER); - THROWING_MARKER.add(EXCEPTION_MARKER); - CATCHING_MARKER.add(EXCEPTION_MARKER); - - ENTRY_MESSAGE_ARRAY[0] = ENTRY_MESSAGE_0; - ENTRY_MESSAGE_ARRAY[1] = ENTRY_MESSAGE_1; - ENTRY_MESSAGE_ARRAY[2] = ENTRY_MESSAGE_2; - ENTRY_MESSAGE_ARRAY[3] = ENTRY_MESSAGE_3; - ENTRY_MESSAGE_ARRAY[4] = ENTRY_MESSAGE_4; - } - - public enum Level { - TRACE("TRACE", LocationAwareLogger.TRACE_INT), - DEBUG("DEBUG", LocationAwareLogger.DEBUG_INT), - INFO("INFO", LocationAwareLogger.INFO_INT), - WARN("WARN", LocationAwareLogger.WARN_INT), - ERROR("ERROR", LocationAwareLogger.ERROR_INT); - - private final String name; - private final int level; - - public String toString() { - return this.name; - } - - public int intValue() { - return this.level; - } - - private Level(String name, int level) { - this.name = name; - this.level = level; - } - } - - /** - * Given an underlying logger, construct an XLogger - * - * @param logger - * underlying logger - */ - public XLogger(Logger logger) { - // If class B extends A, assuming B does not override method x(), the caller - // of new B().x() is A and not B, see also - // http://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); - } - String formattedMessage = MessageFormatter.arrayFormat(messagePattern, - argArray); - ((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, - LocationAwareLogger.TRACE_INT, formattedMessage, 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); - } - } - - /** - * Log method exit - * - * @param result - * The result of the method being exited - */ - public void exit(Object result) { - if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { - String formattedMessage = MessageFormatter.format(EXIT_MESSAGE_1, result); - ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, - LocationAwareLogger.TRACE_INT, formattedMessage, null); - } - } - - /** - * Log an exception being thrown. The generated log event uses Level ERROR. - * - * @param throwable - * the exception being caught. - */ - public void throwing(Throwable throwable) { - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, - LocationAwareLogger.ERROR_INT, "throwing", 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 void throwing(Level level, Throwable throwable) { - if (instanceofLAL) { - ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, - level.level, "throwing", 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", 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", throwable); - } - } - - private static String buildMessagePattern(int len) { - StringBuilder sb = new StringBuilder(); - sb.append(" entry with ("); - for (int i = 0; i < len; i++) { - sb.append("{}"); - if (i != len - 1) - sb.append(", "); - } - sb.append(')'); - return sb.toString(); - } -} +package org.slf4j.ext; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.MessageFormatter; +import org.slf4j.spi.LocationAwareLogger; + +/** + * A utility that provides standard mechanisms for logging certain kinds of + * activities. + * + * @author Ralph Goers + * @author Ceki Gülcü + */ +public class XLogger extends LoggerWrapper implements Logger { + + private static final String FQCN = XLogger.class.getName(); + static Marker FLOW_MARKER = MarkerFactory.getMarker("FLOW"); + static Marker ENTRY_MARKER = MarkerFactory.getMarker("ENTRY"); + static Marker EXIT_MARKER = MarkerFactory.getMarker("EXIT"); + + static Marker EXCEPTION_MARKER = MarkerFactory.getMarker("EXCEPTION"); + static Marker THROWING_MARKER = MarkerFactory.getMarker("THROWING"); + static Marker CATCHING_MARKER = MarkerFactory.getMarker("CATCHING"); + + static String EXIT_MESSAGE_0 = "exit"; + static String EXIT_MESSAGE_1 = "exit with ({})"; + + static String ENTRY_MESSAGE_0 = "entry"; + static String ENTRY_MESSAGE_1 = "entry with ({})"; + static String ENTRY_MESSAGE_2 = "entry with ({}, {})"; + static String ENTRY_MESSAGE_3 = "entry with ({}, {}, {})"; + static String ENTRY_MESSAGE_4 = "entry with ({}, {}, {}, {})"; + static int ENTRY_MESSAGE_ARRAY_LEN = 5; + static String[] ENTRY_MESSAGE_ARRAY = new String[ENTRY_MESSAGE_ARRAY_LEN]; + static { + ENTRY_MARKER.add(FLOW_MARKER); + EXIT_MARKER.add(FLOW_MARKER); + THROWING_MARKER.add(EXCEPTION_MARKER); + CATCHING_MARKER.add(EXCEPTION_MARKER); + + ENTRY_MESSAGE_ARRAY[0] = ENTRY_MESSAGE_0; + ENTRY_MESSAGE_ARRAY[1] = ENTRY_MESSAGE_1; + ENTRY_MESSAGE_ARRAY[2] = ENTRY_MESSAGE_2; + ENTRY_MESSAGE_ARRAY[3] = ENTRY_MESSAGE_3; + ENTRY_MESSAGE_ARRAY[4] = ENTRY_MESSAGE_4; + } + + public enum Level { + TRACE("TRACE", LocationAwareLogger.TRACE_INT), + DEBUG("DEBUG", LocationAwareLogger.DEBUG_INT), + INFO("INFO", LocationAwareLogger.INFO_INT), + WARN("WARN", LocationAwareLogger.WARN_INT), + ERROR("ERROR", LocationAwareLogger.ERROR_INT); + + private final String name; + private final int level; + + public String toString() { + return this.name; + } + + public int intValue() { + return this.level; + } + + private Level(String name, int level) { + this.name = name; + this.level = level; + } + } + + /** + * Given an underlying logger, construct an XLogger + * + * @param logger + * underlying logger + */ + public XLogger(Logger logger) { + // If class B extends A, assuming B does not override method x(), the caller + // of new B().x() is A and not B, see also + // http://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); + } + String formattedMessage = MessageFormatter.arrayFormat(messagePattern, + argArray); + ((LocationAwareLogger) logger).log(ENTRY_MARKER, FQCN, + LocationAwareLogger.TRACE_INT, formattedMessage, 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); + } + } + + /** + * Log method exit + * + * @param result + * The result of the method being exited + */ + public void exit(Object result) { + if (instanceofLAL && logger.isTraceEnabled(ENTRY_MARKER)) { + String formattedMessage = MessageFormatter.format(EXIT_MESSAGE_1, result); + ((LocationAwareLogger) logger).log(EXIT_MARKER, FQCN, + LocationAwareLogger.TRACE_INT, formattedMessage, null); + } + } + + /** + * Log an exception being thrown. The generated log event uses Level ERROR. + * + * @param throwable + * the exception being caught. + */ + public void throwing(Throwable throwable) { + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, + LocationAwareLogger.ERROR_INT, "throwing", 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 void throwing(Level level, Throwable throwable) { + if (instanceofLAL) { + ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, + level.level, "throwing", 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", 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", throwable); + } + } + + private static String buildMessagePattern(int len) { + StringBuilder sb = new StringBuilder(); + sb.append(" entry with ("); + for (int i = 0; i < len; i++) { + sb.append("{}"); + if (i != len - 1) + sb.append(", "); + } + sb.append(')'); + return sb.toString(); + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/ext/XLoggerFactory.java b/slf4j-ext/src/main/java/org/slf4j/ext/XLoggerFactory.java index 457fa93a..257dcf39 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/XLoggerFactory.java +++ b/slf4j-ext/src/main/java/org/slf4j/ext/XLoggerFactory.java @@ -1,42 +1,42 @@ -package org.slf4j.ext; - -import org.slf4j.LoggerFactory; - -/** - * - * This class is essentially a wrapper around an - * {@link LoggerFactory} producing {@link XLogger} instances. - * - *

Contrary to {@link LoggerFactory#getLogger(String)} method of - * {@link LoggerFactory}, each call to {@link getXLogger} - * produces a new instance of XLogger. This should not matter because an - * XLogger instance does not have any state beyond that of the Logger instance - * it wraps. - * - * @author Ralph Goers - * @author Ceki Gülcü - */ -public class XLoggerFactory { - - /** - * Get an XLogger instance by name. - * - * @param name - * @return - */ - 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 - */ - @SuppressWarnings("unchecked") - public static XLogger getXLogger(Class clazz) { - return getXLogger(clazz.getName()); - } -} +package org.slf4j.ext; + +import org.slf4j.LoggerFactory; + +/** + * + * This class is essentially a wrapper around an + * {@link LoggerFactory} producing {@link XLogger} instances. + * + *

Contrary to {@link LoggerFactory#getLogger(String)} method of + * {@link LoggerFactory}, each call to {@link getXLogger} + * produces a new instance of XLogger. This should not matter because an + * XLogger instance does not have any state beyond that of the Logger instance + * it wraps. + * + * @author Ralph Goers + * @author Ceki Gülcü + */ +public class XLoggerFactory { + + /** + * Get an XLogger instance by name. + * + * @param name + * @return + */ + 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 + */ + @SuppressWarnings("unchecked") + public static XLogger getXLogger(Class clazz) { + return getXLogger(clazz.getName()); + } +} diff --git a/slf4j-ext/src/main/java/org/slf4j/ext/package.html b/slf4j-ext/src/main/java/org/slf4j/ext/package.html index 1cfc28d5..f9ea74a8 100644 --- a/slf4j-ext/src/main/java/org/slf4j/ext/package.html +++ b/slf4j-ext/src/main/java/org/slf4j/ext/package.html @@ -1,12 +1,12 @@ - - - - - - - - - -

SLF4J API extensions

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

SLF4J API extensions

+ + diff --git a/slf4j-ext/src/main/java/org/slf4j/instrumentation/package.html b/slf4j-ext/src/main/java/org/slf4j/instrumentation/package.html index 0afac0cf..76001498 100644 --- a/slf4j-ext/src/main/java/org/slf4j/instrumentation/package.html +++ b/slf4j-ext/src/main/java/org/slf4j/instrumentation/package.html @@ -1,18 +1,18 @@ - - - - - - - - - -

Java instrumentation routines for SLF4J.

- -

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

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

Java instrumentation routines for SLF4J.

+ +

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

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

Poor man's profiler API

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

Poor man's profiler API

+ + diff --git a/slf4j-ext/src/main/resources/META-INF/MANIFEST.MF b/slf4j-ext/src/main/resources/META-INF/MANIFEST.MF index f90c7af8..eddd2a31 100644 --- a/slf4j-ext/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-ext/src/main/resources/META-INF/MANIFEST.MF @@ -1,8 +1,8 @@ -Implementation-Title: slf4j-ext -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.ext -Bundle-Name: slf4j-log4j12 -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Export-Package: org.slf4j.profiler;version=${parsedVersion.osgiVersion}, org.slf4j.cal10n;version=${parsedVersion.osgiVersion}, org.slf4j.ext;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, ch.qos.cal10n;version=${cal10n.version} +Implementation-Title: slf4j-ext +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.ext +Bundle-Name: slf4j-log4j12 +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.slf4j.profiler;version=${parsedVersion.osgiVersion}, org.slf4j.cal10n;version=${parsedVersion.osgiVersion}, org.slf4j.ext;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, ch.qos.cal10n;version=${cal10n.version} diff --git a/slf4j-ext/src/test/java/org/slf4j/NDCTest.java b/slf4j-ext/src/test/java/org/slf4j/NDCTest.java index 8765a97a..c58283e2 100644 --- a/slf4j-ext/src/test/java/org/slf4j/NDCTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/NDCTest.java @@ -1,57 +1,57 @@ -/* - * Copyright (c) 2004-2009 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -package org.slf4j; - -import junit.framework.TestCase; - -public class NDCTest extends TestCase { - - 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); - } - - public void testSmoke2() { - NDC.push("a"); - NDC.push("b"); - String result1 = NDC.pop(); - String result0 = NDC.pop(); - assertEquals("b",result1); - assertEquals("a",result0); - } -} +/* + * Copyright (c) 2004-2009 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package org.slf4j; + +import junit.framework.TestCase; + +public class NDCTest extends TestCase { + + 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); + } + + 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 690474df..88d301ae 100644 --- a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/LocLoggerTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/LocLoggerTest.java @@ -1,79 +1,79 @@ -/* - * Copyright (c) 2004-2009 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -package org.slf4j.cal10n_dummy; - -import java.util.Locale; - -import junit.framework.TestCase; - -import org.apache.log4j.spi.LoggingEvent; -import org.slf4j.cal10n.LocLogger; -import org.slf4j.cal10n.LocLoggerFactory; -import org.slf4j.dummyExt.ListAppender; - -import ch.qos.cal10n.IMessageConveyor; -import ch.qos.cal10n.MessageConveyor; - -public class LocLoggerTest extends TestCase { - - ListAppender listAppender; - org.apache.log4j.Logger log4jRoot; - - IMessageConveyor imc = new MessageConveyor(Locale.UK); - LocLoggerFactory llFactory_uk = new LocLoggerFactory(imc); - - final static String EXPECTED_FILE_NAME = "LocLoggerTest.java"; - - public LocLoggerTest(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); - } - - void verify(LoggingEvent le, String expectedMsg) { - assertEquals(expectedMsg, le.getMessage()); - assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName()); - } - - 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"); - - } -} +/* + * Copyright (c) 2004-2009 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package org.slf4j.cal10n_dummy; + +import java.util.Locale; + +import junit.framework.TestCase; + +import org.apache.log4j.spi.LoggingEvent; +import org.slf4j.cal10n.LocLogger; +import org.slf4j.cal10n.LocLoggerFactory; +import org.slf4j.dummyExt.ListAppender; + +import ch.qos.cal10n.IMessageConveyor; +import ch.qos.cal10n.MessageConveyor; + +public class LocLoggerTest extends TestCase { + + ListAppender listAppender; + org.apache.log4j.Logger log4jRoot; + + IMessageConveyor imc = new MessageConveyor(Locale.UK); + LocLoggerFactory llFactory_uk = new LocLoggerFactory(imc); + + final static String EXPECTED_FILE_NAME = "LocLoggerTest.java"; + + public LocLoggerTest(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); + } + + void verify(LoggingEvent le, String expectedMsg) { + assertEquals(expectedMsg, le.getMessage()); + assertEquals(EXPECTED_FILE_NAME, le.getLocationInformation().getFileName()); + } + + 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 5f4bceb0..42e99477 100644 --- a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Months.java +++ b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Months.java @@ -1,10 +1,10 @@ -package org.slf4j.cal10n_dummy; - -import ch.qos.cal10n.BaseName; - -@BaseName("months") -public enum Months { - - JAN, FEB, MAR, APR, MAY, JUN; - -} +package org.slf4j.cal10n_dummy; + +import ch.qos.cal10n.BaseName; + +@BaseName("months") +public enum Months { + + JAN, FEB, MAR, APR, MAY, JUN; + +} diff --git a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/MyApplication.java b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/MyApplication.java index 15991059..a4b97b77 100644 --- a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/MyApplication.java +++ b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/MyApplication.java @@ -1,32 +1,32 @@ -package org.slf4j.cal10n_dummy; - -import java.util.Locale; - -import org.slf4j.cal10n.LocLogger; -import org.slf4j.cal10n.LocLoggerFactory; - -import ch.qos.cal10n.IMessageConveyor; -import ch.qos.cal10n.MessageConveyor; - -public class MyApplication { - - // create a message conveyor for a given locale - IMessageConveyor messageConveyor = new MessageConveyor(Locale.JAPAN); - - // create the LogLoggerFactory - LocLoggerFactory llFactory_uk = new LocLoggerFactory(messageConveyor); - - // create a locLogger - LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass()); - - - public void applicationStart() { - locLogger.info(Production.APPLICATION_STARTED); - // .. - } - - public void applicationStop() { - locLogger.info(Production.APPLICATION_STOPPED); - // ... - } -} +package org.slf4j.cal10n_dummy; + +import java.util.Locale; + +import org.slf4j.cal10n.LocLogger; +import org.slf4j.cal10n.LocLoggerFactory; + +import ch.qos.cal10n.IMessageConveyor; +import ch.qos.cal10n.MessageConveyor; + +public class MyApplication { + + // create a message conveyor for a given locale + IMessageConveyor messageConveyor = new MessageConveyor(Locale.JAPAN); + + // create the LogLoggerFactory + LocLoggerFactory llFactory_uk = new LocLoggerFactory(messageConveyor); + + // create a locLogger + LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass()); + + + public void applicationStart() { + locLogger.info(Production.APPLICATION_STARTED); + // .. + } + + public void applicationStop() { + locLogger.info(Production.APPLICATION_STOPPED); + // ... + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Production.java b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Production.java index 95fce9d1..8e954210 100644 --- a/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Production.java +++ b/slf4j-ext/src/test/java/org/slf4j/cal10n_dummy/Production.java @@ -1,14 +1,14 @@ -package org.slf4j.cal10n_dummy; - -import ch.qos.cal10n.LocaleData; -import ch.qos.cal10n.Locale; -import ch.qos.cal10n.BaseName; - -@BaseName("production") -@LocaleData( { @Locale("en_UK"), @Locale("fr") }) -public enum Production { - APPLICATION_STARTED, - APPLICATION_STOPPED, - DB_CONNECTION, - DB_CONNECTION_FAILURE; +package org.slf4j.cal10n_dummy; + +import ch.qos.cal10n.LocaleData; +import ch.qos.cal10n.Locale; +import ch.qos.cal10n.BaseName; + +@BaseName("production") +@LocaleData( { @Locale("en_UK"), @Locale("fr") }) +public enum Production { + APPLICATION_STARTED, + APPLICATION_STOPPED, + DB_CONNECTION, + DB_CONNECTION_FAILURE; } \ 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 e0544207..18178f9d 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/EventLoggerTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/EventLoggerTest.java @@ -1,108 +1,108 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.dummyExt; - -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import junit.framework.TestCase; - -import org.apache.log4j.spi.LocationInfo; -import org.apache.log4j.spi.LoggingEvent; -import org.slf4j.MDC; -import org.slf4j.ext.EventData; -import org.slf4j.ext.EventLogger; - -public class EventLoggerTest extends TestCase { - - ListAppender listAppender; - org.apache.log4j.Logger log4; - - 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"); - } - } +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.dummyExt; + +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import junit.framework.TestCase; + +import org.apache.log4j.spi.LocationInfo; +import org.apache.log4j.spi.LoggingEvent; +import org.slf4j.MDC; +import org.slf4j.ext.EventData; +import org.slf4j.ext.EventLogger; + +public class EventLoggerTest extends TestCase { + + ListAppender listAppender; + org.apache.log4j.Logger log4; + + 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"); + } + } } \ 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 6a4098e3..7b72b0e5 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/ListAppender.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/ListAppender.java @@ -1,30 +1,30 @@ -package org.slf4j.dummyExt; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.spi.LoggingEvent; - -public class ListAppender extends AppenderSkeleton { - - public List list = new ArrayList(); - - public boolean extractLocationInfo = false; - - protected void append(LoggingEvent event) { - list.add(event); - if(extractLocationInfo) { - event.getLocationInformation(); - } - } - - public void close() { - } - - public boolean requiresLayout() { - return false; - } - -} - +package org.slf4j.dummyExt; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class ListAppender extends AppenderSkeleton { + + public List list = new ArrayList(); + + public boolean extractLocationInfo = false; + + protected void append(LoggingEvent event) { + list.add(event); + if(extractLocationInfo) { + event.getLocationInformation(); + } + } + + public void close() { + } + + public boolean requiresLayout() { + return false; + } + +} + diff --git a/slf4j-ext/src/test/java/org/slf4j/dummyExt/XLoggerTest.java b/slf4j-ext/src/test/java/org/slf4j/dummyExt/XLoggerTest.java index 51ddf050..a8c45430 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/XLoggerTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/XLoggerTest.java @@ -1,157 +1,157 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.dummyExt; - -import junit.framework.TestCase; - -import org.apache.log4j.spi.LocationInfo; -import org.apache.log4j.spi.LoggingEvent; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -public class XLoggerTest extends TestCase { - - ListAppender listAppender; - org.apache.log4j.Logger log4jRoot; - - 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(); - logger.exit(0); - 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"); - logger.throwing(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()); - } - - } -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.dummyExt; + +import junit.framework.TestCase; + +import org.apache.log4j.spi.LocationInfo; +import org.apache.log4j.spi.LoggingEvent; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +public class XLoggerTest extends TestCase { + + ListAppender listAppender; + org.apache.log4j.Logger log4jRoot; + + 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(); + logger.exit(0); + 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"); + logger.throwing(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()); + } + + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/dummyExt/package.html b/slf4j-ext/src/test/java/org/slf4j/dummyExt/package.html index 5ceec8f2..ddd4f3ad 100644 --- a/slf4j-ext/src/test/java/org/slf4j/dummyExt/package.html +++ b/slf4j-ext/src/test/java/org/slf4j/dummyExt/package.html @@ -1,4 +1,4 @@ -Tests related to the org.slfj.ext package. However, location information code -required the caller class (XLogger) to have a different prefix than -the test class XLoggerTest. This is ensured by having the test class +Tests related to the org.slfj.ext package. However, location information code +required the caller class (XLogger) to have a different prefix than +the test class XLoggerTest. This is ensured by having the test class placed in a different package. \ No newline at end of file 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 563c5ded..7f9b309f 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/BasicProfilerDemo.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/BasicProfilerDemo.java @@ -1,63 +1,63 @@ -package org.slf4j.profiler; - -/** - * - * This demo illustrates usage of SLF4J profilers. - * - *

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

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

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

-   + Profiler [BASIC]
-   |-- elapsed time                      [A]   213.186 milliseconds.
-   |-- elapsed time                      [B]  2499.107 milliseconds.
-   |-- elapsed time                  [OTHER]  3300.752 milliseconds.
-   |-- Total                         [BASIC]  6014.161 milliseconds.
-  
- * - * @author Ceki Gulcu - */ -public class BasicProfilerDemo { - - public static void main(String[] args) { - // create a profiler called "BASIC" - Profiler profiler = new Profiler("BASIC"); - profiler.start("A"); - doA(); - - profiler.start("B"); - doB(); - - profiler.start("OTHER"); - doOther(); - profiler.stop().print(); - } - - static private void doA() { - delay(200); - } - - static private void doB() { - delay(2500); - } - - static private void doOther() { - delay(3300); - } - - static private void delay(int millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - } - } -} +package org.slf4j.profiler; + +/** + * + * This demo illustrates usage of SLF4J profilers. + * + *

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

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

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

+   + Profiler [BASIC]
+   |-- elapsed time                      [A]   213.186 milliseconds.
+   |-- elapsed time                      [B]  2499.107 milliseconds.
+   |-- elapsed time                  [OTHER]  3300.752 milliseconds.
+   |-- Total                         [BASIC]  6014.161 milliseconds.
+  
+ * + * @author Ceki Gulcu + */ +public class BasicProfilerDemo { + + public static void main(String[] args) { + // create a profiler called "BASIC" + Profiler profiler = new Profiler("BASIC"); + profiler.start("A"); + doA(); + + profiler.start("B"); + doB(); + + profiler.start("OTHER"); + doOther(); + profiler.stop().print(); + } + + static private void doA() { + delay(200); + } + + static private void doB() { + delay(2500); + } + + static private void doOther() { + delay(3300); + } + + static private void delay(int millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + } + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo.java b/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo.java index 93eab8a6..b5ece60a 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo.java @@ -1,62 +1,62 @@ -package org.slf4j.profiler; - - - -/** - * - * This demo illustrates usage of SLF4J profilers. - * - *

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

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

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

- + Profiler [DEMO]
-|-- elapsed time                       [RANDOM]     0.089  seconds.
-|---+ Profiler [SORT_AND_PRUNE]
-    |-- elapsed time                         [SORT]     0.221  seconds.
-    |-- elapsed time             [PRUNE_COMPOSITES]    11.567  seconds.
-    |-- Subtotal                   [SORT_AND_PRUNE]    11.788  seconds.
-|-- elapsed time               [SORT_AND_PRUNE]    11.788  seconds.
-|-- Total                                [DEMO]    11.877  seconds.
-
- * - * @author Ceki Gulcu - */ -public class NestedProfilerDemo { - - public static void main(String[] args) { - // create a profiler called "DEMO" - Profiler profiler = new Profiler("DEMO"); - - // register this profiler in the thread context's profiler registry - ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); - profiler.registerWith(profilerRegistry); - - // start a stopwatch called "RANDOM" - profiler.start("RANDOM"); - RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator(); - int n = 10*1000; - int[] randomArray = riaGenerator.generate(n); - - // create and start a nested profiler called "SORT_AND_PRUNE" - // By virtue of its parent-child relationship with the "DEMO" - // profiler, and the previous registration of the parent profiler, - // this nested profiler will be automatically registered - // with the thread context's profiler registry - profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME); - - SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray); - pruner.sortAndPruneComposites(); - - // stop and print the "DEMO" printer - profiler.stop().print(); - } -} +package org.slf4j.profiler; + + + +/** + * + * This demo illustrates usage of SLF4J profilers. + * + *

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

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

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

+ + Profiler [DEMO]
+|-- elapsed time                       [RANDOM]     0.089  seconds.
+|---+ Profiler [SORT_AND_PRUNE]
+    |-- elapsed time                         [SORT]     0.221  seconds.
+    |-- elapsed time             [PRUNE_COMPOSITES]    11.567  seconds.
+    |-- Subtotal                   [SORT_AND_PRUNE]    11.788  seconds.
+|-- elapsed time               [SORT_AND_PRUNE]    11.788  seconds.
+|-- Total                                [DEMO]    11.877  seconds.
+
+ * + * @author Ceki Gulcu + */ +public class NestedProfilerDemo { + + public static void main(String[] args) { + // create a profiler called "DEMO" + Profiler profiler = new Profiler("DEMO"); + + // register this profiler in the thread context's profiler registry + ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); + profiler.registerWith(profilerRegistry); + + // start a stopwatch called "RANDOM" + profiler.start("RANDOM"); + RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator(); + int n = 10*1000; + int[] randomArray = riaGenerator.generate(n); + + // create and start a nested profiler called "SORT_AND_PRUNE" + // By virtue of its parent-child relationship with the "DEMO" + // profiler, and the previous registration of the parent profiler, + // this nested profiler will be automatically registered + // with the thread context's profiler registry + profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME); + + SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray); + pruner.sortAndPruneComposites(); + + // stop and print the "DEMO" printer + profiler.stop().print(); + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java b/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java index a2edafd4..5bd0d250 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java @@ -1,42 +1,42 @@ -package org.slf4j.profiler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - - -/** - * - * This demo illustrates usage of SLF4J profilers. It is almost identical to - * the first NestProfilerDemo, except that it uses a logger instead of - * printing its output on the console. - * - - * @author Ceki Gulcu - */ -public class NestedProfilerDemo2 { - - static Logger logger = LoggerFactory.getLogger(NestedProfilerDemo2.class); - - public static void main(String[] args) { - Profiler profiler = new Profiler("DEMO"); - // associate a logger with the profiler - profiler.setLogger(logger); - - ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); - profiler.registerWith(profilerRegistry); - - profiler.start("RANDOM"); - RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator(); - int n = 10*1000; - int[] randomArray = riaGenerator.generate(n); - - profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME); - - SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray); - pruner.sortAndPruneComposites(); - - // stop and log - profiler.stop().log(); - } -} +package org.slf4j.profiler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + + +/** + * + * This demo illustrates usage of SLF4J profilers. It is almost identical to + * the first NestProfilerDemo, except that it uses a logger instead of + * printing its output on the console. + * + + * @author Ceki Gulcu + */ +public class NestedProfilerDemo2 { + + static Logger logger = LoggerFactory.getLogger(NestedProfilerDemo2.class); + + public static void main(String[] args) { + Profiler profiler = new Profiler("DEMO"); + // associate a logger with the profiler + profiler.setLogger(logger); + + ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); + profiler.registerWith(profilerRegistry); + + profiler.start("RANDOM"); + RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator(); + int n = 10*1000; + int[] randomArray = riaGenerator.generate(n); + + profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME); + + SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray); + pruner.sortAndPruneComposites(); + + // stop and log + profiler.stop().log(); + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/PackageTest.java b/slf4j-ext/src/test/java/org/slf4j/profiler/PackageTest.java index 97d318e3..0b608b60 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/PackageTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/PackageTest.java @@ -1,38 +1,38 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.profiler; - - -import 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; - } +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.profiler; + + +import 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; + } } \ 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 3ca6cb71..c6ca9d04 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/ProfilerTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/ProfilerTest.java @@ -1,136 +1,136 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.profiler; - -import junit.framework.TestCase; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ProfilerTest extends TestCase { - - 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); - } - Profiler nested = profiler.startNested("subtask"); - doSubtask(nested); - profiler.start("doZ"); - doZ(2); - profiler.stop(); - - // verify - profiler.sanityCheck(); - StopWatch gSW = profiler.globalStopWatch; - assertEquals(TimeInstrumentStatus.STOPPED, gSW.status); - //assertEquals(3, profiler.stopwatchList.size()); - assertEquals(4, profiler.childTimeInstrumentList.size()); - assertNotNull(profiler.getLastTimeInstrument()); - assertEquals("doZ", profiler.getLastTimeInstrument().getName()); - - } - - private void doX(int millis) { - delay(millis); - } - private void doY(int millis) { - delay(millis); - } - private void doZ(int millis) { - delay(millis); - } - - public void doSubtask(Profiler nested) { - nested.start("n1"); - doX(1); - - nested.start("n2"); - doX(5); - nested.stop(); - } - - - void delay(int millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - } - } -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.profiler; + +import junit.framework.TestCase; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ProfilerTest extends TestCase { + + 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); + } + 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 d31a50de..7153247b 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/RandomIntegerArrayGenerator.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/RandomIntegerArrayGenerator.java @@ -1,16 +1,16 @@ -package org.slf4j.profiler; - -import java.util.Random; - -public class RandomIntegerArrayGenerator { - Random rand = new Random(11); - - int[] generate(int size) { - int[] result = new int[size]; - for(int i = 0; i < size; i++) { - int r = rand.nextInt(); - result[i] = r; - } - return result; - } -} +package org.slf4j.profiler; + +import java.util.Random; + +public class RandomIntegerArrayGenerator { + Random rand = new Random(11); + + int[] generate(int size) { + int[] result = new int[size]; + for(int i = 0; i < size; i++) { + int r = rand.nextInt(); + result[i] = r; + } + return result; + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/SortAndPruneComposites.java b/slf4j-ext/src/test/java/org/slf4j/profiler/SortAndPruneComposites.java index e6413fdd..cac36a94 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/SortAndPruneComposites.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/SortAndPruneComposites.java @@ -1,72 +1,72 @@ -package org.slf4j.profiler; - -import java.util.ArrayList; -import java.util.Arrays; - -public class SortAndPruneComposites { - - static String NESTED_PROFILER_NAME = "SORT_AND_PRUNE"; - - final int[] originalArray; - final int originalArrrayLength; - - public SortAndPruneComposites(int[] randomArray) { - this.originalArray = randomArray; - this.originalArrrayLength = randomArray.length; - - } - - public int[] sortAndPruneComposites() { - // retrieve previously registered profiler named "SORT_AND_PRUNE" - ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); - Profiler sortProfiler = profilerRegistry.get(NESTED_PROFILER_NAME); - - // start a new stopwatch called SORT - sortProfiler.start("SORT"); - int[] sortedArray = sort(); - // start a new stopwatch called PRUNE_COMPOSITES - sortProfiler.start("PRUNE_COMPOSITES"); - int result[] = pruneComposites(sortedArray); - - return result; - } - - private int[] sort() { - int[] sortedArray = new int[originalArrrayLength]; - System.arraycopy(originalArray, 0, sortedArray, 0, originalArrrayLength); - Arrays.sort(sortedArray); - return sortedArray; - } - - int[] pruneComposites(int[] sortedArray) { - ArrayList primesArray = new ArrayList(); - for(int i = 0; i < originalArrrayLength; i++) { - int n = sortedArray[i]; - if(isPrime(n)) { - primesArray.add(n); - } - } - int resultSize = primesArray.size(); - int[] result = new int[resultSize]; - - for(int i = 0; i < resultSize; i++) { - result[i] = primesArray.get(i); - } - return result; - } - - public boolean isPrime(int n) { - if(n < 2) { - return false; - } - if(n%2 == 0) { - return false; - } - for(int i = 3; i*i <=n; i += 2) { - if(n%i ==0) { - return false; - } - } - return true; - } -} +package org.slf4j.profiler; + +import java.util.ArrayList; +import java.util.Arrays; + +public class SortAndPruneComposites { + + static String NESTED_PROFILER_NAME = "SORT_AND_PRUNE"; + + final int[] originalArray; + final int originalArrrayLength; + + public SortAndPruneComposites(int[] randomArray) { + this.originalArray = randomArray; + this.originalArrrayLength = randomArray.length; + + } + + public int[] sortAndPruneComposites() { + // retrieve previously registered profiler named "SORT_AND_PRUNE" + ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); + Profiler sortProfiler = profilerRegistry.get(NESTED_PROFILER_NAME); + + // start a new stopwatch called SORT + sortProfiler.start("SORT"); + int[] sortedArray = sort(); + // start a new stopwatch called PRUNE_COMPOSITES + sortProfiler.start("PRUNE_COMPOSITES"); + int result[] = pruneComposites(sortedArray); + + return result; + } + + private int[] sort() { + int[] sortedArray = new int[originalArrrayLength]; + System.arraycopy(originalArray, 0, sortedArray, 0, originalArrrayLength); + Arrays.sort(sortedArray); + return sortedArray; + } + + int[] pruneComposites(int[] sortedArray) { + ArrayList primesArray = new ArrayList(); + for(int i = 0; i < originalArrrayLength; i++) { + int n = sortedArray[i]; + if(isPrime(n)) { + primesArray.add(n); + } + } + int resultSize = primesArray.size(); + int[] result = new int[resultSize]; + + for(int i = 0; i < resultSize; i++) { + result[i] = primesArray.get(i); + } + return result; + } + + public boolean isPrime(int n) { + if(n < 2) { + return false; + } + if(n%2 == 0) { + return false; + } + for(int i = 3; i*i <=n; i += 2) { + if(n%i ==0) { + return false; + } + } + return true; + } +} diff --git a/slf4j-ext/src/test/java/org/slf4j/profiler/UtilTest.java b/slf4j-ext/src/test/java/org/slf4j/profiler/UtilTest.java index 86d145e1..bf70b7cf 100644 --- a/slf4j-ext/src/test/java/org/slf4j/profiler/UtilTest.java +++ b/slf4j-ext/src/test/java/org/slf4j/profiler/UtilTest.java @@ -1,52 +1,52 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.profiler; - -import junit.framework.TestCase; - -public class UtilTest extends TestCase { - - public UtilTest(String name) { - super(name); - } - - 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)); - } - -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.profiler; + +import junit.framework.TestCase; + +public class UtilTest extends TestCase { + + public UtilTest(String name) { + super(name); + } + + 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)); + } + +} diff --git a/slf4j-ext/src/test/resources/log4j.properties b/slf4j-ext/src/test/resources/log4j.properties index bac0aa41..10c11706 100644 --- a/slf4j-ext/src/test/resources/log4j.properties +++ b/slf4j-ext/src/test/resources/log4j.properties @@ -1,6 +1,6 @@ - -log4j.rootLogger=DEBUG, CONSOLE - -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n + +log4j.rootLogger=DEBUG, CONSOLE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n diff --git a/slf4j-ext/src/test/resources/months_en.properties b/slf4j-ext/src/test/resources/months_en.properties index e3e20a19..fca46d4c 100644 --- a/slf4j-ext/src/test/resources/months_en.properties +++ b/slf4j-ext/src/test/resources/months_en.properties @@ -1,6 +1,6 @@ -JAN=January -FEB=February -MAR=March -APR=April -MAY=May -JUN=June +JAN=January +FEB=February +MAR=March +APR=April +MAY=May +JUN=June diff --git a/slf4j-jcl/LICENSE.txt b/slf4j-jcl/LICENSE.txt index f6e2f31f..508a2728 100644 --- a/slf4j-jcl/LICENSE.txt +++ b/slf4j-jcl/LICENSE.txt @@ -1,24 +1,24 @@ -Copyright (c) 2004-2007 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java b/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java index 2c635d10..9cb2a5e0 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerAdapter.java @@ -1,535 +1,535 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - - -package org.slf4j.impl; - -import org.apache.commons.logging.Log; -import org.slf4j.Logger; -import org.slf4j.helpers.MarkerIgnoringBase; -import org.slf4j.helpers.MessageFormatter; - -/** - * A wrapper over {@link org.apache.commons.logging.Log - * org.apache.commons.logging.Log} in conformance with the {@link Logger} - * interface. - * - * @author Ceki Gülcü - */ -public final class JCLLoggerAdapter extends MarkerIgnoringBase { - - private static final long serialVersionUID = 4141593417490482209L; - final Log log; - - // WARN: JCLLoggerAdapter constructor should have only package access so - // that only JCLLoggerFactory be able to create one. - JCLLoggerAdapter(Log log, String name) { - this.log = log; - this.name = name; - } - - /** - * Delegates to the {@link Log#isTraceEnabled} method of the underlying - * {@link Log} instance. - */ - public boolean isTraceEnabled() { - return log.isTraceEnabled(); - } - - // - - /** - * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - * @param msg - the message object to be logged - */ - public void trace(String msg) { - log.trace(msg); - } - - /** - * Delegates to the {@link Log#trace(java.lang.Object)} method of the underlying - * {@link Log} instance. - * - *

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

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

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

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void trace(String format, Object arg) { + if (log.isDebugEnabled()) { + String msgStr = MessageFormatter.format(format, arg); + log.trace(msgStr); + } + } + + /** + * 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.isDebugEnabled()) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + log.trace(msgStr); + } + } + + + /** + * 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 argArray an array of arguments + */ + public void trace(String format, Object[] argArray) { + if (log.isDebugEnabled()) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + log.trace(msgStr); + } + } + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg); + log.debug(msgStr); + } + } + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + log.debug(msgStr); + } + } + + + /** + * 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 argArray an array of arguments + */ + public void debug(String format, Object[] argArray) { + if (log.isDebugEnabled()) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + log.debug(msgStr); + } + } + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg); + log.info(msgStr); + } + } + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + log.info(msgStr); + } + } + + /** + * 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 argArray an array of arguments + */ + public void info(String format, Object[] argArray) { + if (log.isInfoEnabled()) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + log.info(msgStr); + } + } + + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg); + log.warn(msgStr); + } + } + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + log.warn(msgStr); + } + } + + /** + * 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 argArray an array of arguments + */ + public void warn(String format, Object[] argArray) { + if (log.isWarnEnabled()) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + log.warn(msgStr); + } + } + + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg); + log.error(msgStr); + } + } + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + log.error(msgStr); + } + } + + /** + * 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 argArray an array of arguments + */ + public void error(String format, Object[] argArray) { + if (log.isErrorEnabled()) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + log.error(msgStr); + } + } + + + /** + * 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 e955b53d..fddaf91a 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerFactory.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/JCLLoggerFactory.java @@ -1,76 +1,76 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.logging.LogFactory; -import org.slf4j.ILoggerFactory; -import org.slf4j.Logger; - -/** - * JCLLoggerFactory is an implementation of {@link ILoggerFactory} returning the - * appropriately named {@link JCLLoggerAdapter} instance. - * - * @author Ceki Gülcü - */ -public class JCLLoggerFactory implements ILoggerFactory { - - // key: name (String), value: a JCLLoggerAdapter; - Map loggerMap; - - public JCLLoggerFactory() { - loggerMap = new HashMap(); - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) - */ - public Logger getLogger(String name) { - Logger logger = null; - // protect against concurrent access of loggerMap - synchronized (this) { - logger = (Logger) loggerMap.get(name); - if (logger == null) { - org.apache.commons.logging.Log jclLogger = LogFactory.getLog(name); - logger = new JCLLoggerAdapter(jclLogger, name); - loggerMap.put(name, logger); - } - } - return logger; - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.logging.LogFactory; +import org.slf4j.ILoggerFactory; +import org.slf4j.Logger; + +/** + * JCLLoggerFactory is an implementation of {@link ILoggerFactory} returning the + * appropriately named {@link JCLLoggerAdapter} instance. + * + * @author Ceki Gülcü + */ +public class JCLLoggerFactory implements ILoggerFactory { + + // key: name (String), value: a JCLLoggerAdapter; + Map loggerMap; + + public JCLLoggerFactory() { + loggerMap = new HashMap(); + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) + */ + public Logger getLogger(String name) { + Logger logger = null; + // protect against concurrent access of loggerMap + synchronized (this) { + logger = (Logger) loggerMap.get(name); + if (logger == null) { + org.apache.commons.logging.Log jclLogger = LogFactory.getLog(name); + logger = new JCLLoggerAdapter(jclLogger, name); + loggerMap.put(name, logger); + } + } + return logger; + } +} 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 6c63536a..2b2514ae 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,92 +1,92 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - /** - * 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.5.10"; - - // Binding specific code: - private static final String loggerFactoryClassStr = JCLLoggerFactory.class - .getName(); - - /** - * The ILoggerFactory instance returned by the {@link #getLoggerFactory} - * method should always be the same object - */ - private final ILoggerFactory loggerFactory; - - private StaticLoggerBinder() { - // Binding specific code: - loggerFactory = new JCLLoggerFactory(); - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + /** + * 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.5.10"; + + // Binding specific code: + private static final String loggerFactoryClassStr = JCLLoggerFactory.class + .getName(); + + /** + * The ILoggerFactory instance returned by the {@link #getLoggerFactory} + * method should always be the same object + */ + private final ILoggerFactory loggerFactory; + + private StaticLoggerBinder() { + // Binding specific code: + loggerFactory = new JCLLoggerFactory(); + } + + public ILoggerFactory getLoggerFactory() { + return loggerFactory; + } + + public String getLoggerFactoryClassStr() { + return loggerFactoryClassStr; + } +} diff --git a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMDCBinder.java index 62b9f865..0b9fb17e 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,34 +1,34 @@ -package org.slf4j.impl; - -import org.slf4j.helpers.NOPMakerAdapter; -import org.slf4j.spi.MDCAdapter; - - -/** - * This implementation is bound to {@link NOPMakerAdapter}. - * - * @author Ceki Gülcü - */ -public class 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 NOPMakerAdapter(); - } - - public String getMDCAdapterClassStr() { - return NOPMakerAdapter.class.getName(); - } -} +package org.slf4j.impl; + +import org.slf4j.helpers.NOPMakerAdapter; +import org.slf4j.spi.MDCAdapter; + + +/** + * This implementation is bound to {@link NOPMakerAdapter}. + * + * @author Ceki Gülcü + */ +public class 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 NOPMakerAdapter(); + } + + public String getMDCAdapterClassStr() { + return NOPMakerAdapter.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 b37c3640..cb4faa9b 100644 --- a/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-jcl/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,77 +1,77 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - - -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + + +} diff --git a/slf4j-jcl/src/main/resources/META-INF/MANIFEST.MF b/slf4j-jcl/src/main/resources/META-INF/MANIFEST.MF index a905c8f4..ea973a0d 100644 --- a/slf4j-jcl/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-jcl/src/main/resources/META-INF/MANIFEST.MF @@ -1,10 +1,10 @@ -Implementation-Title: slf4j-jcl -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.jcl -Bundle-Name: slf4j-jcl -Bundle-Vendor: SLF4J.ORG -Require-Bundle: slf4j.api -Bundle-RequiredExecutionEnvironment: J2SE-1.3 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, org.apache.commons.logging +Implementation-Title: slf4j-jcl +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.jcl +Bundle-Name: slf4j-jcl +Bundle-Vendor: SLF4J.ORG +Require-Bundle: slf4j.api +Bundle-RequiredExecutionEnvironment: J2SE-1.3 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, org.apache.commons.logging Fragment-Host: slf4j.api \ No newline at end of file diff --git a/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java b/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java index 0fa8c497..56d2cfe6 100644 --- a/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-jcl/src/test/java/org/slf4j/InvocationTest.java @@ -1,138 +1,138 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.CH - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j; - -import java.util.logging.Level; - -import junit.framework.TestCase; - - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - * - */ -public class InvocationTest extends TestCase { - - Level oldLevel; - java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); - - - public InvocationTest (String arg0) { - super(arg0); - } - - protected void setUp() throws Exception { - super.setUp(); - oldLevel = root.getLevel(); - root.setLevel(Level.OFF); - } - - 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(); - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.CH + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j; + +import java.util.logging.Level; + +import junit.framework.TestCase; + + +/** + * Test whether invoking the SLF4J API causes problems or not. + * + * @author Ceki Gulcu + * + */ +public class InvocationTest extends TestCase { + + Level oldLevel; + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); + + + public InvocationTest (String arg0) { + super(arg0); + } + + protected void setUp() throws Exception { + super.setUp(); + oldLevel = root.getLevel(); + root.setLevel(Level.OFF); + } + + 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/LICENSE.txt b/slf4j-jdk14/LICENSE.txt index f6e2f31f..508a2728 100644 --- a/slf4j-jdk14/LICENSE.txt +++ b/slf4j-jdk14/LICENSE.txt @@ -1,24 +1,24 @@ -Copyright (c) 2004-2007 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-jdk14/pom.xml b/slf4j-jdk14/pom.xml index ce76d61d..8ca8ef6b 100644 --- a/slf4j-jdk14/pom.xml +++ b/slf4j-jdk14/pom.xml @@ -1,69 +1,69 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - slf4j-jdk14 - - jar - SLF4J JDK14 Binding - - http://www.slf4j.org - - The slf4j JDK14 binding - - - - - org.slf4j - slf4j-api - - - - org.slf4j - slf4j-api - test-jar - ${project.version} - test - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.4 - 1.4 - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - ${parsedVersion.osgiVersion} - ${project.description} - ${project.version} - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + slf4j-jdk14 + + jar + SLF4J JDK14 Binding + + http://www.slf4j.org + + The slf4j JDK14 binding + + + + + org.slf4j + slf4j-api + + + + org.slf4j + slf4j-api + test-jar + ${project.version} + test + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.4 + 1.4 + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + ${parsedVersion.osgiVersion} + ${project.description} + ${project.version} + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + + \ No newline at end of file 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 c892ce51..4b6401b0 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerAdapter.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerAdapter.java @@ -1,662 +1,662 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import java.util.logging.Level; -import java.util.logging.LogRecord; - -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.helpers.MarkerIgnoringBase; -import org.slf4j.helpers.MessageFormatter; -import org.slf4j.spi.LocationAwareLogger; - -/** - * A wrapper over {@link java.util.logging.Logger java.util.logging.Logger} in - * conformity with the {@link Logger} interface. Note that the logging levels - * mentioned in this class refer to those defined in the java.util.logging - * package. - * - * @author Ceki Gülcü - * @author Peter Royal - */ -public final class JDK14LoggerAdapter extends MarkerIgnoringBase implements - LocationAwareLogger { - - private static final long serialVersionUID = -8053026990503422791L; - - 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)) { - String msgStr = MessageFormatter.format(format, arg); - log(SELF, Level.FINEST, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg1, arg2); - log(SELF, Level.FINEST, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.FINEST, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg); - log(SELF, Level.FINE, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg1, arg2); - log(SELF, Level.FINE, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.FINE, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg); - log(SELF, Level.INFO, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg1, arg2); - log(SELF, Level.INFO, msgStr, 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.isLoggable(Level.INFO)) { - String msgStr = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.INFO, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg); - log(SELF, Level.WARNING, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg1, arg2); - log(SELF, Level.WARNING, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.WARNING, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg); - log(SELF, Level.SEVERE, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg1, arg2); - log(SELF, Level.SEVERE, msgStr, null); - } - } - - /** - * 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 argArray - * an array of arguments - */ - public void error(String format, Object[] argArray) { - if (logger.isLoggable(Level.SEVERE)) { - String msgStr = MessageFormatter.arrayFormat(format, argArray); - log(SELF, Level.SEVERE, msgStr, null); - } - } - - /** - * 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, - 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); - } - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.helpers.MarkerIgnoringBase; +import org.slf4j.helpers.MessageFormatter; +import org.slf4j.spi.LocationAwareLogger; + +/** + * A wrapper over {@link java.util.logging.Logger java.util.logging.Logger} in + * conformity with the {@link Logger} interface. Note that the logging levels + * mentioned in this class refer to those defined in the java.util.logging + * package. + * + * @author Ceki Gülcü + * @author Peter Royal + */ +public final class JDK14LoggerAdapter extends MarkerIgnoringBase implements + LocationAwareLogger { + + private static final long serialVersionUID = -8053026990503422791L; + + 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)) { + String msgStr = MessageFormatter.format(format, arg); + log(SELF, Level.FINEST, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + log(SELF, Level.FINEST, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.FINEST, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg); + log(SELF, Level.FINE, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + log(SELF, Level.FINE, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.FINE, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg); + log(SELF, Level.INFO, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + log(SELF, Level.INFO, msgStr, 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.isLoggable(Level.INFO)) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.INFO, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg); + log(SELF, Level.WARNING, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + log(SELF, Level.WARNING, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.WARNING, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg); + log(SELF, Level.SEVERE, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + log(SELF, Level.SEVERE, msgStr, null); + } + } + + /** + * 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 argArray + * an array of arguments + */ + public void error(String format, Object[] argArray) { + if (logger.isLoggable(Level.SEVERE)) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.SEVERE, msgStr, null); + } + } + + /** + * 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, + 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 5165beb8..77243534 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerFactory.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/JDK14LoggerFactory.java @@ -1,80 +1,80 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.slf4j.Logger; -import org.slf4j.ILoggerFactory; - -import java.util.HashMap; -import java.util.Map; - -/** - * JDK14LoggerFactory is an implementation of {@link ILoggerFactory} returning - * the appropriately named {@link JDK14LoggerAdapter} instance. - * - * @author Ceki Gülcü - */ -public class JDK14LoggerFactory implements ILoggerFactory { - - // key: name (String), value: a JDK14LoggerAdapter; - Map loggerMap; - - public JDK14LoggerFactory() { - loggerMap = new HashMap(); - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) - */ - public synchronized Logger getLogger(String name) { - Logger ulogger = null; - // protect against concurrent access of loggerMap - synchronized (this) { - // the root logger is called "" in JUL - if(name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) { - name = ""; - } - ulogger = (Logger) loggerMap.get(name); - if (ulogger == null) { - java.util.logging.Logger logger = java.util.logging.Logger - .getLogger(name); - ulogger = new JDK14LoggerAdapter(logger); - loggerMap.put(name, ulogger); - } - } - return ulogger; - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.slf4j.Logger; +import org.slf4j.ILoggerFactory; + +import java.util.HashMap; +import java.util.Map; + +/** + * JDK14LoggerFactory is an implementation of {@link ILoggerFactory} returning + * the appropriately named {@link JDK14LoggerAdapter} instance. + * + * @author Ceki Gülcü + */ +public class JDK14LoggerFactory implements ILoggerFactory { + + // key: name (String), value: a JDK14LoggerAdapter; + Map loggerMap; + + public JDK14LoggerFactory() { + loggerMap = new HashMap(); + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) + */ + public synchronized Logger getLogger(String name) { + Logger ulogger = null; + // protect against concurrent access of loggerMap + synchronized (this) { + // the root logger is called "" in JUL + if(name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) { + name = ""; + } + ulogger = (Logger) loggerMap.get(name); + if (ulogger == null) { + java.util.logging.Logger logger = java.util.logging.Logger + .getLogger(name); + ulogger = new JDK14LoggerAdapter(logger); + loggerMap.put(name, ulogger); + } + } + return ulogger; + } +} 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 b32a59d5..c4d2073e 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,91 +1,91 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - * - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - - /** - * Declare the version of the SLF4J API this implementation is compiled against. - * The value of this field is 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.5.10"; // !final - - - private static final String loggerFactoryClassStr = org.slf4j.impl.JDK14LoggerFactory.class.getName(); - - /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method - * should always be the same object - */ - private final ILoggerFactory loggerFactory; - - private StaticLoggerBinder() { -// Note: JCL gets substituted at build time by an appropriate Ant task - loggerFactory = new org.slf4j.impl.JDK14LoggerFactory(); - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + * + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is 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.5.10"; // !final + + + private static final String loggerFactoryClassStr = org.slf4j.impl.JDK14LoggerFactory.class.getName(); + + /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method + * should always be the same object + */ + private final ILoggerFactory loggerFactory; + + private StaticLoggerBinder() { +// Note: JCL gets substituted at build time by an appropriate Ant task + loggerFactory = new org.slf4j.impl.JDK14LoggerFactory(); + } + + public ILoggerFactory getLoggerFactory() { + return loggerFactory; + } + + public String getLoggerFactoryClassStr() { + return loggerFactoryClassStr; + } +} diff --git a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMDCBinder.java index 09b3a03f..1d2bf919 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,36 +1,36 @@ -package org.slf4j.impl; - -import org.slf4j.helpers.BasicMDCAdapter; -import org.slf4j.spi.MDCAdapter; - - -/** - * This implementation is bound to {@link BasicMDCAdapter}. - * - * @author Ceki Gülcü - */ -public class StaticMDCBinder { - - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - - private StaticMDCBinder() { - } - - /** - * 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(); - } -} +package org.slf4j.impl; + +import org.slf4j.helpers.BasicMDCAdapter; +import org.slf4j.spi.MDCAdapter; + + +/** + * This implementation is bound to {@link BasicMDCAdapter}. + * + * @author Ceki Gülcü + */ +public class StaticMDCBinder { + + + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + } + + /** + * 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 b37c3640..cb4faa9b 100644 --- a/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-jdk14/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,77 +1,77 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - - -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + + +} diff --git a/slf4j-jdk14/src/main/resources/META-INF/MANIFEST.MF b/slf4j-jdk14/src/main/resources/META-INF/MANIFEST.MF index 4838f9db..1593db31 100644 --- a/slf4j-jdk14/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-jdk14/src/main/resources/META-INF/MANIFEST.MF @@ -1,9 +1,9 @@ -Implementation-Title: slf4j-jdk14 -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.jdk14 -Bundle-Name: slf4j-jdk14 -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.3 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion} +Implementation-Title: slf4j-jdk14 +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.jdk14 +Bundle-Name: slf4j-jdk14 +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.3 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion} Fragment-Host: slf4j.api \ No newline at end of file diff --git a/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java b/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java index 46073e93..78513daa 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/InvocationTest.java @@ -1,149 +1,149 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.CH - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j; - -import java.util.logging.Level; - -import junit.framework.TestCase; - - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - * - */ -public class InvocationTest extends TestCase { - - Level oldLevel; - java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); - - public InvocationTest (String arg0) { - super(arg0); - } - - protected void setUp() throws Exception { - super.setUp(); - oldLevel = root.getLevel(); - root.setLevel(Level.OFF); - } - - 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"); - 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) { - } - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.CH + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j; + +import java.util.logging.Level; + +import junit.framework.TestCase; + + +/** + * Test whether invoking the SLF4J API causes problems or not. + * + * @author Ceki Gulcu + * + */ +public class InvocationTest extends TestCase { + + Level oldLevel; + java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); + + public InvocationTest (String arg0) { + super(arg0); + } + + protected void setUp() throws Exception { + super.setUp(); + oldLevel = root.getLevel(); + root.setLevel(Level.OFF); + } + + 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"); + 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) { + } + } +} 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 cc511adb..dfaecb2d 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/impl/JDK14AdapterLoggerNameTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/impl/JDK14AdapterLoggerNameTest.java @@ -1,98 +1,98 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import java.util.logging.Handler; -import java.util.logging.LogRecord; -import java.util.logging.Logger; - -import junit.framework.TestCase; - -public class JDK14AdapterLoggerNameTest extends TestCase { - 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 { - } - - public void flush() { - } - - public void publish(LogRecord record) { - this.record = record; - } - - } +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import junit.framework.TestCase; + +public class JDK14AdapterLoggerNameTest extends TestCase { + 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 { + } + + 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 cf321e1a..c239de29 100644 --- a/slf4j-jdk14/src/test/java/org/slf4j/impl/PerfTest.java +++ b/slf4j-jdk14/src/test/java/org/slf4j/impl/PerfTest.java @@ -1,52 +1,52 @@ -package org.slf4j.impl; - -import junit.framework.TestCase; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.helpers.BogoPerf; - -public class PerfTest extends TestCase { - - 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"); - } - - long end = System.currentTimeMillis(); - - long duration = end - start; - return duration; - } - -} +package org.slf4j.impl; + +import junit.framework.TestCase; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.helpers.BogoPerf; + +public class PerfTest extends TestCase { + + 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"); + } + + long end = System.currentTimeMillis(); + + long duration = end - start; + return duration; + } + +} diff --git a/slf4j-log4j12/LICENSE.txt b/slf4j-log4j12/LICENSE.txt index f6e2f31f..508a2728 100644 --- a/slf4j-log4j12/LICENSE.txt +++ b/slf4j-log4j12/LICENSE.txt @@ -1,24 +1,24 @@ -Copyright (c) 2004-2007 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-log4j12/pom.xml b/slf4j-log4j12/pom.xml index 976dadbf..e8a65485 100644 --- a/slf4j-log4j12/pom.xml +++ b/slf4j-log4j12/pom.xml @@ -1,56 +1,56 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - slf4j-log4j12 - jar - SLF4J LOG4J-12 Binding - - http://www.slf4j.org - - - The slf4j log4j-12 binding - - - - - org.slf4j - slf4j-api - - - - log4j - log4j - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - ${parsedVersion.osgiVersion} - ${project.description} - ${project.version} - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + slf4j-log4j12 + jar + SLF4J LOG4J-12 Binding + + http://www.slf4j.org + + + The slf4j log4j-12 binding + + + + + org.slf4j + slf4j-api + + + + log4j + log4j + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + ${parsedVersion.osgiVersion} + ${project.description} + ${project.version} + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + + \ No newline at end of file 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 28e3dccf..39016756 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerAdapter.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerAdapter.java @@ -1,600 +1,600 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - - -package org.slf4j.impl; - -import java.io.Serializable; - -import org.apache.log4j.Level; -import org.slf4j.Logger; -import org.slf4j.Marker; -import org.slf4j.helpers.MarkerIgnoringBase; -import org.slf4j.helpers.MessageFormatter; -import org.slf4j.spi.LocationAwareLogger; - -/** - * A wrapper over {@link org.apache.log4j.Logger org.apache.log4j.Logger} in - * conforming to the {@link Logger} interface. - * - *

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

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

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

- * - * @param format - * the format string - * @param arg - * the argument - */ - public void trace(String format, Object arg) { - if (isTraceEnabled()) { - String msgStr = MessageFormatter.format(format, arg); - logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msgStr, 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 arg1 - * the first argument - * @param arg2 - * the second argument - */ - public void trace(String format, Object arg1, Object arg2) { - if (isTraceEnabled()) { - String msgStr = MessageFormatter.format(format, arg1, arg2); - logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msgStr, 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 argArray - * an array of arguments - */ - public void trace(String format, Object[] argArray) { - if (isTraceEnabled()) { - String msgStr = MessageFormatter.arrayFormat(format, argArray); - logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msgStr, null); - } - } - - /** - * 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()) { - String msgStr = MessageFormatter.format(format, arg); - logger.log(FQCN, Level.DEBUG, msgStr, null); - } - } - - /** - * 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()) { - String msgStr = MessageFormatter.format(format, arg1, arg2); - logger.log(FQCN, Level.DEBUG, msgStr, null); - } - } - - /** - * Log a message at level DEBUG according to the specified format and - * arguments. - * - *

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

- * - * @param format - * the format string - * @param argArray - * an array of arguments - */ - public void debug(String format, Object[] argArray) { - if (logger.isDebugEnabled()) { - String msgStr = MessageFormatter.arrayFormat(format, argArray); - logger.log(FQCN, Level.DEBUG, msgStr, null); - } - } - - /** - * 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()) { - String msgStr = MessageFormatter.format(format, arg); - logger.log(FQCN, Level.INFO, msgStr, null); - } - } - - /** - * 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()) { - String msgStr = MessageFormatter.format(format, arg1, arg2); - logger.log(FQCN, Level.INFO, msgStr, 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()) { - String msgStr = MessageFormatter.arrayFormat(format, argArray); - logger.log(FQCN, Level.INFO, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg); - logger.log(FQCN, Level.WARN, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg1, arg2); - logger.log(FQCN, Level.WARN, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.arrayFormat(format, argArray); - logger.log(FQCN, Level.WARN, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg); - logger.log(FQCN, Level.ERROR, msgStr, null); - } - } - - /** - * 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)) { - String msgStr = MessageFormatter.format(format, arg1, arg2); - logger.log(FQCN, Level.ERROR, msgStr, 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)) { - String msgStr = MessageFormatter.arrayFormat(format, argArray); - logger.log(FQCN, Level.ERROR, msgStr, null); - } - } - - /** - * 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, - 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); - } - -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +package org.slf4j.impl; + +import java.io.Serializable; + +import org.apache.log4j.Level; +import org.slf4j.Logger; +import org.slf4j.Marker; +import org.slf4j.helpers.MarkerIgnoringBase; +import org.slf4j.helpers.MessageFormatter; +import org.slf4j.spi.LocationAwareLogger; + +/** + * A wrapper over {@link org.apache.log4j.Logger org.apache.log4j.Logger} in + * conforming to the {@link Logger} interface. + * + *

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

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

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

+ * + * @param format + * the format string + * @param arg + * the argument + */ + public void trace(String format, Object arg) { + if (isTraceEnabled()) { + String msgStr = MessageFormatter.format(format, arg); + logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msgStr, 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 arg1 + * the first argument + * @param arg2 + * the second argument + */ + public void trace(String format, Object arg1, Object arg2) { + if (isTraceEnabled()) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msgStr, 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 argArray + * an array of arguments + */ + public void trace(String format, Object[] argArray) { + if (isTraceEnabled()) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + logger.log(FQCN, traceCapable ? Level.TRACE : Level.DEBUG, msgStr, null); + } + } + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg); + logger.log(FQCN, Level.DEBUG, msgStr, null); + } + } + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + logger.log(FQCN, Level.DEBUG, msgStr, null); + } + } + + /** + * Log a message at level DEBUG according to the specified format and + * arguments. + * + *

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

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + public void debug(String format, Object[] argArray) { + if (logger.isDebugEnabled()) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + logger.log(FQCN, Level.DEBUG, msgStr, null); + } + } + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg); + logger.log(FQCN, Level.INFO, msgStr, null); + } + } + + /** + * 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()) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + logger.log(FQCN, Level.INFO, msgStr, 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()) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + logger.log(FQCN, Level.INFO, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg); + logger.log(FQCN, Level.WARN, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + logger.log(FQCN, Level.WARN, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + logger.log(FQCN, Level.WARN, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg); + logger.log(FQCN, Level.ERROR, msgStr, null); + } + } + + /** + * 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)) { + String msgStr = MessageFormatter.format(format, arg1, arg2); + logger.log(FQCN, Level.ERROR, msgStr, 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)) { + String msgStr = MessageFormatter.arrayFormat(format, argArray); + logger.log(FQCN, Level.ERROR, msgStr, null); + } + } + + /** + * 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, + 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); + } + +} 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 627ee514..da1329d2 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerFactory.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jLoggerFactory.java @@ -1,81 +1,81 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.LogManager; -import org.slf4j.ILoggerFactory; -import org.slf4j.Logger; - -/** - * Log4jLoggerFactory is an implementation of {@link ILoggerFactory} returning - * the appropriate named {@link Log4jLoggerAdapter} instance. - * - * @author Ceki Gülcü - */ -public class Log4jLoggerFactory implements ILoggerFactory { - - // key: name (String), value: a Log4jLoggerAdapter; - Map loggerMap; - - public Log4jLoggerFactory() { - loggerMap = new HashMap(); - } - - /* - * (non-Javadoc) - * - * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) - */ - public Logger getLogger(String name) { - Logger slf4jLogger = null; - // protect against concurrent access of loggerMap - synchronized (this) { - slf4jLogger = (Logger) loggerMap.get(name); - if (slf4jLogger == null) { - org.apache.log4j.Logger log4jLogger; - if(name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) { - log4jLogger = LogManager.getRootLogger(); - } else { - log4jLogger = LogManager.getLogger(name); - } - slf4jLogger = new Log4jLoggerAdapter(log4jLogger); - loggerMap.put(name, slf4jLogger); - } - } - return slf4jLogger; - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.LogManager; +import org.slf4j.ILoggerFactory; +import org.slf4j.Logger; + +/** + * Log4jLoggerFactory is an implementation of {@link ILoggerFactory} returning + * the appropriate named {@link Log4jLoggerAdapter} instance. + * + * @author Ceki Gülcü + */ +public class Log4jLoggerFactory implements ILoggerFactory { + + // key: name (String), value: a Log4jLoggerAdapter; + Map loggerMap; + + public Log4jLoggerFactory() { + loggerMap = new HashMap(); + } + + /* + * (non-Javadoc) + * + * @see org.slf4j.ILoggerFactory#getLogger(java.lang.String) + */ + public Logger getLogger(String name) { + Logger slf4jLogger = null; + // protect against concurrent access of loggerMap + synchronized (this) { + slf4jLogger = (Logger) loggerMap.get(name); + if (slf4jLogger == null) { + org.apache.log4j.Logger log4jLogger; + if(name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) { + log4jLogger = LogManager.getRootLogger(); + } else { + log4jLogger = LogManager.getLogger(name); + } + slf4jLogger = new Log4jLoggerAdapter(log4jLogger); + loggerMap.put(name, slf4jLogger); + } + } + return slf4jLogger; + } +} 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 f68355ff..e6efed7c 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jMDCAdapter.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/Log4jMDCAdapter.java @@ -1,64 +1,64 @@ -package org.slf4j.impl; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.slf4j.spi.MDCAdapter; - -public class Log4jMDCAdapter implements MDCAdapter { - - public void clear() { - 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); - } - - public Map getCopyOfContextMap() { - Map old = org.apache.log4j.MDC.getContext(); - if(old != null) { - return new HashMap(old); - } else { - return null; - } - } - - 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); - } - } -} +package org.slf4j.impl; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.slf4j.spi.MDCAdapter; + +public class Log4jMDCAdapter implements MDCAdapter { + + public void clear() { + 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); + } + + public Map getCopyOfContextMap() { + Map old = org.apache.log4j.MDC.getContext(); + if(old != null) { + return new HashMap(old); + } else { + return null; + } + } + + 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 03543caa..6cf6d230 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,97 +1,97 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.apache.log4j.Level; -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.helpers.Util; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - * - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - /** - * Declare the version of the SLF4J API this implementation is compiled - * against. The value of this field is 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.5.10"; // !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 { - Level level = Level.TRACE; - } catch (NoSuchFieldError nsfe) { - Util - .reportFailure("This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version"); - } - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/* + * Copyright (c) 2004-2008 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.apache.log4j.Level; +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.helpers.Util; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + * + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + /** + * Declare the version of the SLF4J API this implementation is compiled + * against. The value of this field is 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.5.10"; // !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 { + Level level = Level.TRACE; + } catch (NoSuchFieldError nsfe) { + Util + .reportFailure("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 897fda15..037bccaf 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,33 +1,33 @@ -package org.slf4j.impl; - -import org.slf4j.spi.MDCAdapter; - - -/** - * This implementation is bound to {@link Log4jMDCAdapter}. - * - * @author Ceki Gülcü - */ -public class StaticMDCBinder { - - - /** - * The unique instance of this class. - */ - public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); - - private StaticMDCBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link StaticMDCBinder}. - */ - public MDCAdapter getMDCA() { - return new Log4jMDCAdapter(); - } - - public String getMDCAdapterClassStr() { - return Log4jMDCAdapter.class.getName(); - } -} +package org.slf4j.impl; + +import org.slf4j.spi.MDCAdapter; + + +/** + * This implementation is bound to {@link Log4jMDCAdapter}. + * + * @author Ceki Gülcü + */ +public class StaticMDCBinder { + + + /** + * The unique instance of this class. + */ + public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); + + private StaticMDCBinder() { + } + + /** + * 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 b37c3640..cb4faa9b 100644 --- a/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-log4j12/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,77 +1,77 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - - -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + + +} diff --git a/slf4j-log4j12/src/main/resources/META-INF/MANIFEST.MF b/slf4j-log4j12/src/main/resources/META-INF/MANIFEST.MF index d925dccb..a76da1c9 100644 --- a/slf4j-log4j12/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-log4j12/src/main/resources/META-INF/MANIFEST.MF @@ -1,9 +1,9 @@ -Implementation-Title: slf4j-log4j12 -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.log4j12 -Bundle-Name: slf4j-log4j12 -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.3 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, org.apache.log4j +Implementation-Title: slf4j-log4j12 +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.log4j12 +Bundle-Name: slf4j-log4j12 +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.3 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion}, org.apache.log4j Fragment-Host: slf4j.api \ No newline at end of file diff --git a/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java b/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java index 9d6dc682..c26e5850 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/InvocationTest.java @@ -1,183 +1,183 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.CH - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.spi.LoggingEvent; - -import junit.framework.TestCase; - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - * - */ -public class InvocationTest extends TestCase { - - ListAppender listAppender = new ListAppender(); - org.apache.log4j.Logger root; - public InvocationTest(String arg0) { - super(arg0); - } - - 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")); - } - -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.CH + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.spi.LoggingEvent; + +import junit.framework.TestCase; + +/** + * Test whether invoking the SLF4J API causes problems or not. + * + * @author Ceki Gulcu + * + */ +public class InvocationTest extends TestCase { + + ListAppender listAppender = new ListAppender(); + org.apache.log4j.Logger root; + public InvocationTest(String arg0) { + super(arg0); + } + + 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 87c4d836..29b64cfc 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/ListAppender.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/ListAppender.java @@ -1,29 +1,29 @@ -package org.slf4j; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.spi.LoggingEvent; - -public class ListAppender extends AppenderSkeleton { - - public List list = new ArrayList(); - - public boolean extractLocationInfo = false; - - protected void append(LoggingEvent event) { - list.add(event); - if(extractLocationInfo) { - event.getLocationInformation(); - } - } - - public void close() { - } - - public boolean requiresLayout() { - return false; - } - -} +package org.slf4j; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class ListAppender extends AppenderSkeleton { + + public List list = new ArrayList(); + + public boolean extractLocationInfo = false; + + protected void append(LoggingEvent event) { + list.add(event); + if(extractLocationInfo) { + event.getLocationInformation(); + } + } + + public void close() { + } + + public boolean requiresLayout() { + return false; + } + +} diff --git a/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveAppender.java b/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveAppender.java index b83664dd..c67edd95 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveAppender.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveAppender.java @@ -1,30 +1,30 @@ -package org.slf4j.impl; - -import java.util.Random; - -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.spi.LoggingEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RecursiveAppender extends AppenderSkeleton { - - int diff = new Random().nextInt(); - - 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) { - } - - public void close() { - } - - public boolean requiresLayout() { - return false; - } -} +package org.slf4j.impl; + +import java.util.Random; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RecursiveAppender extends AppenderSkeleton { + + int diff = new Random().nextInt(); + + 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) { + } + + 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 fd8b05ba..6e936009 100644 --- a/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java +++ b/slf4j-log4j12/src/test/java/org/slf4j/impl/RecursiveInitializationTest.java @@ -1,33 +1,33 @@ -package org.slf4j.impl; - -import java.util.Random; - -import junit.framework.TestCase; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RecursiveInitializationTest extends TestCase { - - // 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(); - } - - 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"); - } - -} +package org.slf4j.impl; + +import java.util.Random; + +import junit.framework.TestCase; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RecursiveInitializationTest extends TestCase { + + // 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(); + } + + 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-log4j12/src/test/resources/recursiveInit.properties b/slf4j-log4j12/src/test/resources/recursiveInit.properties index 49031550..a8d5d765 100644 --- a/slf4j-log4j12/src/test/resources/recursiveInit.properties +++ b/slf4j-log4j12/src/test/resources/recursiveInit.properties @@ -1,8 +1,8 @@ -log4j.debug=true -log4j.rootLogger=DEBUG, RECURSIVE - -log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -log4j.appender.CONSOLE.layout.ConversionPattern=%d [%t] %c - %m%n - +log4j.debug=true +log4j.rootLogger=DEBUG, RECURSIVE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d [%t] %c - %m%n + log4j.appender.RECURSIVE=org.slf4j.impl.RecursiveAppender \ No newline at end of file diff --git a/slf4j-migrator/LIMITATIONS.txt b/slf4j-migrator/LIMITATIONS.txt index dcba5dc9..7770f242 100644 --- a/slf4j-migrator/LIMITATIONS.txt +++ b/slf4j-migrator/LIMITATIONS.txt @@ -1,35 +1,35 @@ - -The slf4j-migrator aims to - -General limitations -=================== - -- the FATAL level is not supported. - - This is limitation is not deemed serious because there are usually - very few log statements bearing the FATAL level. - - -- if a method declares multipe loggers on the same line, the conversion will not be complete. Example: - - - public void someMethod(Log l1, Log l2) { - ... - } - - will be converted as - - public void someMethod(Log l1, Logger l2) { - ... - } - - -When migrating from log4j -========================= - -- Since NDC is not supported by SLF4J, the migrator cannot properly handle - NDC statements. - -- Calls to PropertyConfigurator or DomConfigurator cannot be migrated since - SLF4J the equivalents. + +The slf4j-migrator aims to + +General limitations +=================== + +- the FATAL level is not supported. + + This is limitation is not deemed serious because there are usually + very few log statements bearing the FATAL level. + + +- if a method declares multipe loggers on the same line, the conversion will not be complete. Example: + + + public void someMethod(Log l1, Log l2) { + ... + } + + will be converted as + + public void someMethod(Log l1, Logger l2) { + ... + } + + +When migrating from log4j +========================= + +- Since NDC is not supported by SLF4J, the migrator cannot properly handle + NDC statements. + +- Calls to PropertyConfigurator or DomConfigurator cannot be migrated since + SLF4J the equivalents. \ No newline at end of file diff --git a/slf4j-migrator/pom.xml b/slf4j-migrator/pom.xml index cb91f799..69392d03 100644 --- a/slf4j-migrator/pom.xml +++ b/slf4j-migrator/pom.xml @@ -1,46 +1,46 @@ - - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - slf4j-migrator - jar - SLF4J Migrator - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.5 - 1.5 - - - - - org.apache.maven.plugins - maven-jar-plugin - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - - - + + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + slf4j-migrator + jar + SLF4J Migrator + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.5 + 1.5 + + + + + org.apache.maven.plugins + maven-jar-plugin + + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + + + + \ No newline at end of file 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 7875e96c..d685eccf 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/FileSelector.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/FileSelector.java @@ -1,45 +1,45 @@ -package org.slf4j.migrator; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.migrator.internal.ProgressListener; - -public class FileSelector { - - private List javaFileList = new ArrayList(); - - ProgressListener pl; - - FileSelector(ProgressListener pl) { - this.pl = pl; - } - - public List selectJavaFilesInFolder(File folder) { - if (folder.isDirectory()) { - selectFiles(folder); - return javaFileList; - } else { - throw new IllegalArgumentException("[" + folder + "] is not a directory"); - } - } - - private void selectFiles(File file) { - if (file.isDirectory()) { - pl.onDirectory(file); - File[] files = file.listFiles(); - if (files != null) { - for (int i = 0; i < files.length; i++) { - selectFiles(files[i]); - } - } - } else { - if (file.getName().endsWith(".java")) { - pl.onFileAddition(file); - javaFileList.add(file); - } - - } - } -} +package org.slf4j.migrator; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.migrator.internal.ProgressListener; + +public class FileSelector { + + private List javaFileList = new ArrayList(); + + ProgressListener pl; + + FileSelector(ProgressListener pl) { + this.pl = pl; + } + + public List selectJavaFilesInFolder(File folder) { + if (folder.isDirectory()) { + selectFiles(folder); + return javaFileList; + } else { + throw new IllegalArgumentException("[" + folder + "] is not a directory"); + } + } + + private void selectFiles(File file) { + if (file.isDirectory()) { + pl.onDirectory(file); + File[] files = file.listFiles(); + if (files != null) { + for (int i = 0; i < files.length; i++) { + selectFiles(files[i]); + } + } + } else { + if (file.getName().endsWith(".java")) { + pl.onFileAddition(file); + javaFileList.add(file); + } + + } + } +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java index b3a013c6..5ce29af3 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/InplaceFileConverter.java @@ -1,87 +1,87 @@ -package org.slf4j.migrator; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; - -import org.slf4j.migrator.internal.ProgressListener; -import org.slf4j.migrator.line.LineConverter; -import org.slf4j.migrator.line.RuleSet; - -public class InplaceFileConverter { - - final static int BUFFER_LEN = 8 * 1024; - final LineConverter lineConverter; - final String lineTerminator; - final ProgressListener pl; - - InplaceFileConverter(RuleSet ruleSet, ProgressListener pl) { - this.lineConverter = new LineConverter(ruleSet); - lineTerminator = System.getProperty("line.separator"); - this.pl = pl; - } - - private byte[] readIntoByteArray(File file) throws IOException { - FileInputStream fis = new FileInputStream(file); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - int n = 0; - byte[] buffer = new byte[BUFFER_LEN]; - while ((n = fis.read(buffer)) != -1) { - // System.out.println("ba="+new String(buffer, "UTF-8")); - baos.write(buffer, 0, n); - } - fis.close(); - return baos.toByteArray(); - } - - void convert(File file) throws IOException { - byte[] originalBytes = readIntoByteArray(file); - byte[] convertedBytes = convertIntoTempByteArray(originalBytes); - if (lineConverter.atLeastOneMatchOccured()) { - //System.out.println("Converting ["+file+"]"); - writeConvertedBytesIntoFile(file, convertedBytes); - pl.onInplaceConversion(file); - } else { - //System.out.println("Not touching ["+file+"]"); - } - } - - private void writeConvertedBytesIntoFile(File file, byte[] convertedBytes) throws IOException { - FileOutputStream fos = new FileOutputStream(file); - fos.write(convertedBytes); - fos.flush(); - fos.close(); - } - - private byte[] convertIntoTempByteArray(byte[] input) throws IOException { - ByteArrayInputStream bais = new ByteArrayInputStream(input); - Reader reader = new InputStreamReader(bais); - BufferedReader breader = new BufferedReader(reader); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - while (true) { - String line = breader.readLine(); - if (line != null) { - String[] replacement = lineConverter.getReplacement(line); - writeReplacement(baos, replacement); - } else { - break; - } - } - return baos.toByteArray(); - } - - private void writeReplacement(OutputStream os, String[] replacement) - throws IOException { - for (int i = 0; i < replacement.length; i++) { - os.write(replacement[i].getBytes()); - os.write(lineTerminator.getBytes()); - } - } -} +package org.slf4j.migrator; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; + +import org.slf4j.migrator.internal.ProgressListener; +import org.slf4j.migrator.line.LineConverter; +import org.slf4j.migrator.line.RuleSet; + +public class InplaceFileConverter { + + final static int BUFFER_LEN = 8 * 1024; + final LineConverter lineConverter; + final String lineTerminator; + final ProgressListener pl; + + InplaceFileConverter(RuleSet ruleSet, ProgressListener pl) { + this.lineConverter = new LineConverter(ruleSet); + lineTerminator = System.getProperty("line.separator"); + this.pl = pl; + } + + private byte[] readIntoByteArray(File file) throws IOException { + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + int n = 0; + byte[] buffer = new byte[BUFFER_LEN]; + while ((n = fis.read(buffer)) != -1) { + // System.out.println("ba="+new String(buffer, "UTF-8")); + baos.write(buffer, 0, n); + } + fis.close(); + return baos.toByteArray(); + } + + void convert(File file) throws IOException { + byte[] originalBytes = readIntoByteArray(file); + byte[] convertedBytes = convertIntoTempByteArray(originalBytes); + if (lineConverter.atLeastOneMatchOccured()) { + //System.out.println("Converting ["+file+"]"); + writeConvertedBytesIntoFile(file, convertedBytes); + pl.onInplaceConversion(file); + } else { + //System.out.println("Not touching ["+file+"]"); + } + } + + private void writeConvertedBytesIntoFile(File file, byte[] convertedBytes) throws IOException { + FileOutputStream fos = new FileOutputStream(file); + fos.write(convertedBytes); + fos.flush(); + fos.close(); + } + + private byte[] convertIntoTempByteArray(byte[] input) throws IOException { + ByteArrayInputStream bais = new ByteArrayInputStream(input); + Reader reader = new InputStreamReader(bais); + BufferedReader breader = new BufferedReader(reader); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + while (true) { + String line = breader.readLine(); + if (line != null) { + String[] replacement = lineConverter.getReplacement(line); + writeReplacement(baos, replacement); + } else { + break; + } + } + return baos.toByteArray(); + } + + private void writeReplacement(OutputStream os, String[] replacement) + throws IOException { + for (int i = 0; i < replacement.length; i++) { + os.write(replacement[i].getBytes()); + os.write(lineTerminator.getBytes()); + } + } +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/Main.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/Main.java index 9e4a06cb..170a0c92 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/Main.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/Main.java @@ -1,50 +1,50 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - - -package org.slf4j.migrator; - -import javax.swing.SwingUtilities; - -import org.slf4j.migrator.internal.MigratorFrame; - -/** - * Main entry point to the migrator. - * - * @author Ceki Gülcü - */ -public class Main { - - public static void main(String[] args) { - System.out.println("Starting SLF4J Migrator"); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - MigratorFrame inst = new MigratorFrame(); - inst.setLocationRelativeTo(null); - inst.setVisible(true); - } - }); - } - -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +package org.slf4j.migrator; + +import javax.swing.SwingUtilities; + +import org.slf4j.migrator.internal.MigratorFrame; + +/** + * Main entry point to the migrator. + * + * @author Ceki Gülcü + */ +public class Main { + + public static void main(String[] args) { + System.out.println("Starting SLF4J Migrator"); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + MigratorFrame inst = new MigratorFrame(); + inst.setLocationRelativeTo(null); + inst.setVisible(true); + } + }); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/Abbreviator.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/Abbreviator.java index d22b6b8b..7746b33b 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/Abbreviator.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/Abbreviator.java @@ -1,66 +1,66 @@ -package org.slf4j.migrator.helper; - -public class Abbreviator { - static final String FILLER = "..."; - - final char folderSeparator; - final int invariantPrefixLength; - final int desiredLength; - - public Abbreviator(int invariantPrefixLength, int desiredLength, - char folderSeparator) { - this.invariantPrefixLength = invariantPrefixLength; - this.desiredLength = desiredLength; - this.folderSeparator = folderSeparator; - } - - public String abbreviate(String filename) { - if (filename.length() <= desiredLength) { - return filename; - } else { - - int firstIndex = filename.indexOf(folderSeparator, invariantPrefixLength); - if (firstIndex == -1) { - // we cant't process this string - return filename; - } - StringBuffer buf = new StringBuffer(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; - } - } - } - - 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; - } -} +package org.slf4j.migrator.helper; + +public class Abbreviator { + static final String FILLER = "..."; + + final char folderSeparator; + final int invariantPrefixLength; + final int desiredLength; + + public Abbreviator(int invariantPrefixLength, int desiredLength, + char folderSeparator) { + this.invariantPrefixLength = invariantPrefixLength; + this.desiredLength = desiredLength; + this.folderSeparator = folderSeparator; + } + + public String abbreviate(String filename) { + if (filename.length() <= desiredLength) { + return filename; + } else { + + int firstIndex = filename.indexOf(folderSeparator, invariantPrefixLength); + if (firstIndex == -1) { + // we cant't process this string + return filename; + } + StringBuffer buf = new StringBuffer(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; + } + } + } + + 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 6f031674..c84f0e05 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/SpringLayoutHelper.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/helper/SpringLayoutHelper.java @@ -1,42 +1,42 @@ -package org.slf4j.migrator.helper; - -import java.awt.Component; - -import javax.swing.SpringLayout; - -public class SpringLayoutHelper { - - - final SpringLayout sl; - final int basicPadding; - - public SpringLayoutHelper(SpringLayout springLayout, int basicPadding) { - sl = springLayout; - this.basicPadding = basicPadding; - } - - public void placeToTheRight(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) { - sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, - SpringLayout.EAST, relativeTo); - - sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, - SpringLayout.NORTH, relativeTo); - } - - public void placeToTheRight(Component relativeTo, Component componentToPlace) { - placeToTheRight(relativeTo, componentToPlace, basicPadding, 0); - } - - public void placeBelow(Component relativeTo, Component componentToPlace) { - placeBelow(relativeTo, componentToPlace, 0, basicPadding); - } - - public void placeBelow(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) { - sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, - SpringLayout.WEST, relativeTo); - - sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, - SpringLayout.SOUTH, relativeTo); - } - -} +package org.slf4j.migrator.helper; + +import java.awt.Component; + +import javax.swing.SpringLayout; + +public class SpringLayoutHelper { + + + final SpringLayout sl; + final int basicPadding; + + public SpringLayoutHelper(SpringLayout springLayout, int basicPadding) { + sl = springLayout; + this.basicPadding = basicPadding; + } + + public void placeToTheRight(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) { + sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, + SpringLayout.EAST, relativeTo); + + sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, + SpringLayout.NORTH, relativeTo); + } + + public void placeToTheRight(Component relativeTo, Component componentToPlace) { + placeToTheRight(relativeTo, componentToPlace, basicPadding, 0); + } + + public void placeBelow(Component relativeTo, Component componentToPlace) { + placeBelow(relativeTo, componentToPlace, 0, basicPadding); + } + + public void placeBelow(Component relativeTo, Component componentToPlace, int horizontalPadding, int verticalPadding) { + sl.putConstraint(SpringLayout.WEST, componentToPlace, horizontalPadding, + SpringLayout.WEST, relativeTo); + + sl.putConstraint(SpringLayout.NORTH, componentToPlace, verticalPadding, + SpringLayout.SOUTH, relativeTo); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ConversionTask.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ConversionTask.java index e16347f0..9e92d285 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ConversionTask.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ConversionTask.java @@ -1,57 +1,57 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.migrator.internal; - -import java.io.File; - -import org.slf4j.migrator.ProjectConverter; - -public class ConversionTask implements Runnable { - - final File folder; - final MigratorFrame frame; - final int conversionType; - - - ConversionTask(File folder, MigratorFrame frame, int conversionType) { - this.folder = folder; - this.frame = frame; - this.conversionType = conversionType; - } - - public void run() { - ProgressListener pl = new ProgressListenerImpl(folder, frame); - pl.onMigrationBegin(); - ProjectConverter converter = new ProjectConverter(conversionType, pl); - converter.convertProject(folder); - } - - public void launch() { - Thread t = new Thread(this); - t.setDaemon(true); - t.start(); - } - -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.migrator.internal; + +import java.io.File; + +import org.slf4j.migrator.ProjectConverter; + +public class ConversionTask implements Runnable { + + final File folder; + final MigratorFrame frame; + final int conversionType; + + + ConversionTask(File folder, MigratorFrame frame, int conversionType) { + this.folder = folder; + this.frame = frame; + this.conversionType = conversionType; + } + + public void run() { + ProgressListener pl = new ProgressListenerImpl(folder, frame); + pl.onMigrationBegin(); + ProjectConverter converter = new ProjectConverter(conversionType, pl); + converter.convertProject(folder); + } + + public void launch() { + Thread t = new Thread(this); + t.setDaemon(true); + t.start(); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListener.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListener.java index 39f96b1d..41b991a9 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListener.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListener.java @@ -1,40 +1,40 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.migrator.internal; - -import java.io.File; - -public interface ProgressListener { - - public void onMigrationBegin(); - public void onDirectory(File file); - public void onFileAddition(File file); - public void onFileScanBegin(); - public void onFileScan(File file); - public void onInplaceConversion(File file); - public void onDone(); - -} - +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.migrator.internal; + +import java.io.File; + +public interface ProgressListener { + + public void onMigrationBegin(); + public void onDirectory(File file); + public void onFileAddition(File file); + public void onFileScanBegin(); + public void onFileScan(File file); + public void onInplaceConversion(File file); + public void onDone(); + +} + diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListenerImpl.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListenerImpl.java index 3048a4b5..878c3322 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListenerImpl.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/internal/ProgressListenerImpl.java @@ -1,126 +1,126 @@ -/* - * Copyright (c) 2004-2008 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.migrator.internal; - -import java.io.File; -import java.io.IOException; - -import org.slf4j.migrator.helper.Abbreviator; - -public class ProgressListenerImpl implements ProgressListener { - - static final int TARGET_FILE_LENGTH = 85; - static final int UPDATE_THRESHOLD = 100; - - int addFileCount = 0; - int scanFileCount = 0; - int inplaceConversionCount = 0; - final MigratorFrame frame; - - Abbreviator abbr; - - long lastUpdate = 0; - - - - public ProgressListenerImpl(File projectFolder, MigratorFrame frame) { - this.frame = frame; - this.abbr = new Abbreviator((int) projectFolder.length(), - TARGET_FILE_LENGTH, File.separatorChar); - } - - public void onMigrationBegin() { - frame.disableInput(); - } - - boolean isTooSoon() { - long now = System.currentTimeMillis(); - if(now-lastUpdate < UPDATE_THRESHOLD) { - return true; - } else { - lastUpdate = now; - return false; - } - } - - public void onDirectory(File file) { - if(isTooSoon()) return; - - String abbreviatedName = getShortName(file); - frame.otherLabel.setText("

Searching folder [" + abbreviatedName - + "]

Found " + addFileCount + " java files to scan."); - } - - public void onDone() { - frame.progressBar.setVisible(false); - frame.otherLabel.setText("Scanned " + addFileCount - + " java files, " + inplaceConversionCount - + " files were modified."); - - frame.migrateButton.setActionCommand(MigratorFrame.EXIT_COMMAND); - frame.migrateButton.setText("Exit"); - frame.migrateButton - .setToolTipText("Click on this button to exit this application."); - frame.migrateButton.setEnabled(true); - - } - - public void onFileAddition(File file) { - addFileCount++; - } - - public void onFileScan(File file) { - - scanFileCount++; - if(isTooSoon()) return; - String abbreviatedName = getShortName(file); - - frame.otherLabel.setText("

Scanning file [" + abbreviatedName - + "]

"); - // File + scanFileCount + " out of "+ addFileCount+" files to scan."+ - // inplaceConversionCount+ " files converted." + - - frame.progressBar.setValue(scanFileCount); - } - - public void onInplaceConversion(File file) { - inplaceConversionCount++; - } - - String getShortName(File file) { - try { - return abbr.abbreviate(file.getCanonicalPath()); - } catch (IOException e) { - return file.toString(); - } - } - - public void onFileScanBegin() { - frame.progressBar.setMaximum(addFileCount); - frame.progressBar.setValue(0); - frame.progressBar.setVisible(true); - } - -} +/* + * Copyright (c) 2004-2008 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.migrator.internal; + +import java.io.File; +import java.io.IOException; + +import org.slf4j.migrator.helper.Abbreviator; + +public class ProgressListenerImpl implements ProgressListener { + + static final int TARGET_FILE_LENGTH = 85; + static final int UPDATE_THRESHOLD = 100; + + int addFileCount = 0; + int scanFileCount = 0; + int inplaceConversionCount = 0; + final MigratorFrame frame; + + Abbreviator abbr; + + long lastUpdate = 0; + + + + public ProgressListenerImpl(File projectFolder, MigratorFrame frame) { + this.frame = frame; + this.abbr = new Abbreviator((int) projectFolder.length(), + TARGET_FILE_LENGTH, File.separatorChar); + } + + public void onMigrationBegin() { + frame.disableInput(); + } + + boolean isTooSoon() { + long now = System.currentTimeMillis(); + if(now-lastUpdate < UPDATE_THRESHOLD) { + return true; + } else { + lastUpdate = now; + return false; + } + } + + public void onDirectory(File file) { + if(isTooSoon()) return; + + String abbreviatedName = getShortName(file); + frame.otherLabel.setText("

Searching folder [" + abbreviatedName + + "]

Found " + addFileCount + " java files to scan."); + } + + public void onDone() { + frame.progressBar.setVisible(false); + frame.otherLabel.setText("Scanned " + addFileCount + + " java files, " + inplaceConversionCount + + " files were modified."); + + frame.migrateButton.setActionCommand(MigratorFrame.EXIT_COMMAND); + frame.migrateButton.setText("Exit"); + frame.migrateButton + .setToolTipText("Click on this button to exit this application."); + frame.migrateButton.setEnabled(true); + + } + + public void onFileAddition(File file) { + addFileCount++; + } + + public void onFileScan(File file) { + + scanFileCount++; + if(isTooSoon()) return; + String abbreviatedName = getShortName(file); + + frame.otherLabel.setText("

Scanning file [" + abbreviatedName + + "]

"); + // File + scanFileCount + " out of "+ addFileCount+" files to scan."+ + // inplaceConversionCount+ " files converted." + + + frame.progressBar.setValue(scanFileCount); + } + + public void onInplaceConversion(File file) { + inplaceConversionCount++; + } + + String getShortName(File file) { + try { + return abbr.abbreviate(file.getCanonicalPath()); + } catch (IOException e) { + return file.toString(); + } + } + + public void onFileScanBegin() { + frame.progressBar.setMaximum(addFileCount); + frame.progressBar.setValue(0); + frame.progressBar.setVisible(true); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/ConversionRule.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/ConversionRule.java index 6b88c36a..cb713209 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/ConversionRule.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/ConversionRule.java @@ -1,51 +1,51 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.migrator.line; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public interface ConversionRule { - - public Pattern getPattern(); - - /** - * Given replacement rules, replace each capturing group in matcher's pattern - * - * @param matcher - * @return String - */ - public String replace(Matcher matcher); - - /** - * Returns a non-null value if there should be an additional line - * following a match of this rule. In most cases this method - * returns null. - * - * @return String - */ - public String getAdditionalLine(); - +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.migrator.line; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public interface ConversionRule { + + public Pattern getPattern(); + + /** + * Given replacement rules, replace each capturing group in matcher's pattern + * + * @param matcher + * @return String + */ + public String replace(Matcher matcher); + + /** + * Returns a non-null value if there should be an additional line + * following a match of this rule. In most cases this method + * returns null. + * + * @return String + */ + public String getAdditionalLine(); + } \ 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 311d0170..a839d784 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/EmptyRuleSet.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/EmptyRuleSet.java @@ -1,15 +1,15 @@ -package org.slf4j.migrator.line; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -public class EmptyRuleSet implements RuleSet { - - List list = new ArrayList(); - - public Iterator iterator() { - return list.iterator(); - } - -} +package org.slf4j.migrator.line; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class EmptyRuleSet implements RuleSet { + + List list = new ArrayList(); + + public Iterator iterator() { + return list.iterator(); + } + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java index 7a115f73..2bf1cb77 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/MultiGroupConversionRule.java @@ -1,95 +1,95 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.migrator.line; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -/** - * This class represents a conversion rule It uses a Pattern and defines for - * each capturing group of this Pattern a replacement text - * - * @author jean-noelcharpin - * - */ -public class MultiGroupConversionRule implements ConversionRule { - - // It is extremely unlikely to encounter more than 10 groups in one of - // our conversion reg-expressions - final private static int MAX_GROUPS = 10; - - private Pattern pattern; - private String[] replacementTable = new String[MAX_GROUPS]; - - public MultiGroupConversionRule(Pattern pattern) { - this.pattern = pattern; - } - - /* (non-Javadoc) - * @see org.slf4j.converter.ConversionRule#getPattern() - */ - public Pattern getPattern() { - return pattern; - } - - public void addReplacement(int groupIndex, String replacement) { - if(groupIndex == 0) { - throw new IllegalArgumentException("regex groups start at 1, not zero"); - } - replacementTable[groupIndex] = replacement; - } - - /* (non-Javadoc) - * @see org.slf4j.converter.ConversionRule#getReplacement(java.lang.Integer) - */ - public String getReplacement(int groupIndex) { - return replacementTable[groupIndex]; - } - - /* (non-Javadoc) - * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher) - */ - public String replace(Matcher matcher) { - StringBuffer replacementBuffer = new StringBuffer(); - String replacementText; - - for (int group = 1; group <= matcher.groupCount(); group++) { - replacementText = getReplacement(group); - if (replacementText != null) { - //System.out.println("replacing group " + group + " : " - // + matcher.group(group) + " with " + replacementText); - replacementBuffer.append(replacementText); - } else { - replacementBuffer.append(matcher.group(group)); - } - } - return replacementBuffer.toString(); - } - - public String getAdditionalLine() { - return null; - } -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.migrator.line; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +/** + * This class represents a conversion rule It uses a Pattern and defines for + * each capturing group of this Pattern a replacement text + * + * @author jean-noelcharpin + * + */ +public class MultiGroupConversionRule implements ConversionRule { + + // It is extremely unlikely to encounter more than 10 groups in one of + // our conversion reg-expressions + final private static int MAX_GROUPS = 10; + + private Pattern pattern; + private String[] replacementTable = new String[MAX_GROUPS]; + + public MultiGroupConversionRule(Pattern pattern) { + this.pattern = pattern; + } + + /* (non-Javadoc) + * @see org.slf4j.converter.ConversionRule#getPattern() + */ + public Pattern getPattern() { + return pattern; + } + + public void addReplacement(int groupIndex, String replacement) { + if(groupIndex == 0) { + throw new IllegalArgumentException("regex groups start at 1, not zero"); + } + replacementTable[groupIndex] = replacement; + } + + /* (non-Javadoc) + * @see org.slf4j.converter.ConversionRule#getReplacement(java.lang.Integer) + */ + public String getReplacement(int groupIndex) { + return replacementTable[groupIndex]; + } + + /* (non-Javadoc) + * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher) + */ + public String replace(Matcher matcher) { + StringBuffer replacementBuffer = new StringBuffer(); + 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 be11f294..083b9631 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/RuleSet.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/RuleSet.java @@ -1,10 +1,10 @@ -package org.slf4j.migrator.line; - -import java.util.Iterator; - - -public interface RuleSet { - - Iterator iterator(); - -} +package org.slf4j.migrator.line; + +import java.util.Iterator; + + +public interface RuleSet { + + Iterator iterator(); + +} diff --git a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/SingleConversionRule.java b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/SingleConversionRule.java index 492a92d7..770f3865 100644 --- a/slf4j-migrator/src/main/java/org/slf4j/migrator/line/SingleConversionRule.java +++ b/slf4j-migrator/src/main/java/org/slf4j/migrator/line/SingleConversionRule.java @@ -1,74 +1,74 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.migrator.line; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -/** - * This class represents a conversion rule It uses a Pattern and defines for - * each capturing group of this Pattern a replacement text - * - * @author jean-noelcharpin - * - */ -public class SingleConversionRule implements ConversionRule { - - final private Pattern pattern; - final private String replacementText ; - final private String additionalLine; - - public SingleConversionRule(Pattern pattern, String replacementText) { - this(pattern, replacementText, null); - } - - public SingleConversionRule(Pattern pattern, String replacementText, String additionalLine) { - this.pattern = pattern; - this.replacementText = replacementText; - this.additionalLine = additionalLine; - } - - /* (non-Javadoc) - * @see org.slf4j.converter.ConversionRule#getPattern() - */ - public Pattern getPattern() { - return pattern; - } - - - - /* (non-Javadoc) - * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher) - */ - public String replace(Matcher matcher) { - return replacementText; - } - - public String getAdditionalLine() { - return additionalLine; - } - -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.migrator.line; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +/** + * This class represents a conversion rule It uses a Pattern and defines for + * each capturing group of this Pattern a replacement text + * + * @author jean-noelcharpin + * + */ +public class SingleConversionRule implements ConversionRule { + + final private Pattern pattern; + final private String replacementText ; + final private String additionalLine; + + public SingleConversionRule(Pattern pattern, String replacementText) { + this(pattern, replacementText, null); + } + + public SingleConversionRule(Pattern pattern, String replacementText, String additionalLine) { + this.pattern = pattern; + this.replacementText = replacementText; + this.additionalLine = additionalLine; + } + + /* (non-Javadoc) + * @see org.slf4j.converter.ConversionRule#getPattern() + */ + public Pattern getPattern() { + return pattern; + } + + + + /* (non-Javadoc) + * @see org.slf4j.converter.ConversionRule#replace(java.util.regex.Matcher) + */ + public String replace(Matcher matcher) { + return replacementText; + } + + public String getAdditionalLine() { + return additionalLine; + } + +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/AllTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/AllTest.java index 32043545..7a0ed900 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/AllTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/AllTest.java @@ -1,41 +1,41 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.migrator; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -public class AllTest extends TestCase { - - public static Test suite() { - TestSuite suite = new TestSuite(); - suite.addTest(org.slf4j.migrator.PackageTest.suite()); - suite.addTest(org.slf4j.migrator.line.PackageTest.suite()); - suite.addTest(org.slf4j.migrator.helper.PackageTest.suite()); - - return suite; - } -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.migrator; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class AllTest extends TestCase { + + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTest(org.slf4j.migrator.PackageTest.suite()); + suite.addTest(org.slf4j.migrator.line.PackageTest.suite()); + suite.addTest(org.slf4j.migrator.helper.PackageTest.suite()); + + return suite; + } +} 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 5c99edda..25acb80c 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/AternativeApproach.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/AternativeApproach.java @@ -1,131 +1,131 @@ -package org.slf4j.migrator; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.slf4j.migrator.line.MultiGroupConversionRule; - -import junit.framework.TestCase; - -public class AternativeApproach extends TestCase { - - /** - * In this test we see that we cans use more simple Pattern to do the - * conversion - * - */ - public void test() { - MultiGroupConversionRule cr2 = new MultiGroupConversionRule(Pattern - .compile("(.*)(Log)")); - cr2.addReplacement(2, "LOGGER"); - - String s = "abcd Log"; - Pattern pat = cr2.getPattern(); - Matcher m = pat.matcher(s); - - assertTrue(m.matches()); - String r = cr2.replace(m); - assertEquals("abcd LOGGER", r); - - System.out.println(r); - } - - /** - * In this test we replace, using the simple Pattern (Log), the full Log - * declaration and 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 s2 = "Logabc "; - m = pat.matcher(s2); - assertTrue(m.find()); - - String s3 = "abcLog"; - m = pat.matcher(s3); - assertTrue(m.find()); - } - - /** - * In this test we use a simple Pattern to replace the log 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()); - } - - /** - * 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 s3 = "abcdLogabcd "; - m = pat.matcher(s3); - assertFalse(m.find()); - - String s4 = "abcdLog"; - m = pat.matcher(s4); - assertFalse(m.find()); - - String s5 = "Log myLog"; - m = pat.matcher(s5); - assertFalse(m.find()); - - Pattern pat2 = Pattern.compile("^Log\\b"); - Matcher m2 = pat2.matcher(s5); - assertTrue(m2.find()); - r = m2.replaceAll("Logger"); - assertEquals("Logger myLog", r); - } - - /** - * In this test we combine two Pattern to achieve the intended conversion - */ - public void test5() { - Pattern pat = Pattern.compile("(\\sLog\\b)"); - String s = "public Log myLog =LogFactory.getFactory().getInstance(myClass.class);"; - Matcher m = pat.matcher(s); - assertTrue(m.find()); - String r = m.replaceAll(" Logger"); - assertEquals("public Logger myLog =LogFactory.getFactory().getInstance(myClass.class);", r); - - Pattern pat2 = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("); - m = pat2.matcher(r); - assertTrue(m.find()); - r = m.replaceAll("LoggerFactory.getLogger("); - assertEquals("public Logger myLog =LoggerFactory.getLogger(myClass.class);", r); - } -} +package org.slf4j.migrator; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.slf4j.migrator.line.MultiGroupConversionRule; + +import junit.framework.TestCase; + +public class AternativeApproach extends TestCase { + + /** + * In this test we see that we cans use more simple Pattern to do the + * conversion + * + */ + public void test() { + MultiGroupConversionRule cr2 = new MultiGroupConversionRule(Pattern + .compile("(.*)(Log)")); + cr2.addReplacement(2, "LOGGER"); + + String s = "abcd Log"; + Pattern pat = cr2.getPattern(); + Matcher m = pat.matcher(s); + + assertTrue(m.matches()); + String r = cr2.replace(m); + assertEquals("abcd LOGGER", r); + + System.out.println(r); + } + + /** + * In this test we replace, using the simple Pattern (Log), the full Log + * declaration and 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 s2 = "Logabc "; + m = pat.matcher(s2); + assertTrue(m.find()); + + String s3 = "abcLog"; + m = pat.matcher(s3); + assertTrue(m.find()); + } + + /** + * In this test we use a simple Pattern to replace the log 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()); + } + + /** + * 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 s3 = "abcdLogabcd "; + m = pat.matcher(s3); + assertFalse(m.find()); + + String s4 = "abcdLog"; + m = pat.matcher(s4); + assertFalse(m.find()); + + String s5 = "Log myLog"; + m = pat.matcher(s5); + assertFalse(m.find()); + + Pattern pat2 = Pattern.compile("^Log\\b"); + Matcher m2 = pat2.matcher(s5); + assertTrue(m2.find()); + r = m2.replaceAll("Logger"); + assertEquals("Logger myLog", r); + } + + /** + * In this test we combine two Pattern to achieve the intended conversion + */ + public void test5() { + Pattern pat = Pattern.compile("(\\sLog\\b)"); + String s = "public Log myLog =LogFactory.getFactory().getInstance(myClass.class);"; + Matcher m = pat.matcher(s); + assertTrue(m.find()); + String r = m.replaceAll(" Logger"); + assertEquals("public Logger myLog =LogFactory.getFactory().getInstance(myClass.class);", r); + + Pattern pat2 = Pattern.compile("LogFactory.getFactory\\(\\).getInstance\\("); + m = pat2.matcher(r); + assertTrue(m.find()); + r = m.replaceAll("LoggerFactory.getLogger("); + assertEquals("public Logger myLog =LoggerFactory.getLogger(myClass.class);", r); + } +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/FileConverterTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/FileConverterTest.java index 7b76bdf8..8a90ef48 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/FileConverterTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/FileConverterTest.java @@ -1,34 +1,34 @@ -package org.slf4j.migrator; - -import java.io.File; -import java.io.IOException; - -import junit.framework.TestCase; - -import org.slf4j.migrator.InplaceFileConverter; -import org.slf4j.migrator.internal.NopProgressListener; -import org.slf4j.migrator.line.EmptyRuleSet; - -public class FileConverterTest extends TestCase { - - public FileConverterTest(String arg0) { - super(arg0); - } - - protected void setUp() throws Exception { - super.setUp(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void test() { - } - - - public void XtestNOP() throws IOException { - InplaceFileConverter fc = new InplaceFileConverter(new EmptyRuleSet(), new NopProgressListener()); - fc.convert(new File("c:/varargs.txt")); - } -} +package org.slf4j.migrator; + +import java.io.File; +import java.io.IOException; + +import junit.framework.TestCase; + +import org.slf4j.migrator.InplaceFileConverter; +import org.slf4j.migrator.internal.NopProgressListener; +import org.slf4j.migrator.line.EmptyRuleSet; + +public class FileConverterTest extends TestCase { + + public FileConverterTest(String arg0) { + super(arg0); + } + + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void test() { + } + + + 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/ProjectConverterTest.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/ProjectConverterTest.java index 47128f9e..e9de7ee4 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/ProjectConverterTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/ProjectConverterTest.java @@ -1,22 +1,22 @@ -package org.slf4j.migrator; - -import java.io.File; - -import org.slf4j.migrator.Constant; -import org.slf4j.migrator.ProjectConverter; -import org.slf4j.migrator.internal.NopProgressListener; - -import junit.framework.TestCase; - -public class ProjectConverterTest extends TestCase { - - 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); - } -} +package org.slf4j.migrator; + +import java.io.File; + +import org.slf4j.migrator.Constant; +import org.slf4j.migrator.ProjectConverter; +import org.slf4j.migrator.internal.NopProgressListener; + +import junit.framework.TestCase; + +public class ProjectConverterTest extends TestCase { + + 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); + } +} 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 d485b576..39e65c4e 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/AbbreviatorTest.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/AbbreviatorTest.java @@ -1,141 +1,141 @@ -package org.slf4j.migrator.helper; - -import org.slf4j.migrator.helper.Abbreviator; - -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"; - - 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); - } - - { - 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 testImpossibleToAbbreviate() { - Abbreviator abb = new Abbreviator(2, 20, FS); - String in = "iczldqwivpgm/mgrmvbjdxrwmqgprdjusth"; - String r = abb.abbreviate(in); - assertEquals(in, 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); - } - } - - 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); - } -} +package org.slf4j.migrator.helper; + +import org.slf4j.migrator.helper.Abbreviator; + +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"; + + 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); + } + + { + 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 testImpossibleToAbbreviate() { + Abbreviator abb = new Abbreviator(2, 20, FS); + String in = "iczldqwivpgm/mgrmvbjdxrwmqgprdjusth"; + String r = abb.abbreviate(in); + assertEquals(in, 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); + } + } + + public void testTheories() { + int MAX_RANDOM_FIXED_LEN = 20; + int MAX_RANDOM_AVG_LEN = 20; + int MAX_RANDOM_MAX_LEN = 100; + for (int i = 0; i < 10000; i++) { + + //System.out.println("Test number " + i); + + // 0 <= fixedLen < MAX_RANDOM_FIXED_LEN + int fixedLen = rh.nextInt(MAX_RANDOM_FIXED_LEN); + // 5 <= averageLen < MAX_RANDOM_AVG_LEN + int averageLen = rh.nextInt(MAX_RANDOM_AVG_LEN) + 3; + // System.out.println("fixedLen="+fixedLen+", averageLen="+averageLen); + + int maxLen = rh.nextInt(MAX_RANDOM_MAX_LEN) + fixedLen; + if (maxLen <= 1) { + continue; + } + // System.out.println("maxLen="+maxLen); + int targetLen = (maxLen / 2) + rh.nextInt(maxLen / 2) + 1; + + if (targetLen > maxLen) { + targetLen = maxLen; + } + String filename = rh.buildRandomFileName(averageLen, maxLen); + + Abbreviator abb = new Abbreviator(fixedLen, targetLen, FS); + String result = abb.abbreviate(filename); + assertTheory0(averageLen, filename, result, fixedLen, targetLen); + assertUsefulness(averageLen, filename, result, fixedLen, targetLen); + assertTheory1(filename, result, fixedLen, targetLen); + assertTheory2(filename, result, fixedLen, targetLen); + } + } + + // result length is smaller than original length + void assertTheory0(int averageLen, String filename, String result, + int fixedLen, int targetLength) { + assertTrue("filename=[" + filename + "] result=[" + result + "]", result + .length() <= filename.length()); + } + + // if conditions allow, result length should be to target length + void assertUsefulness(int averageLen, String filename, String result, + int fixedLen, int targetLength) { + int resLen = result.length(); + + int margin = averageLen * 4; + if (targetLength > fixedLen + margin) { + assertTrue("filename=[" + filename + "], result=[" + result + + "] resultLength=" + resLen + " fixedLength=" + fixedLen + + ", targetLength=" + targetLength + ", avgLen=" + averageLen, result + .length() <= targetLength + averageLen); + } + } + + // result start with prefix found in filename + void assertTheory1(String filename, String result, int fixedLen, + int targetLength) { + String prefix = filename.substring(0, fixedLen); + assertTrue(result.startsWith(prefix)); + } + + // The string /.../ is found in the result once at a position higher + // than fixedLen + void assertTheory2(String filename, String result, int fixedLen, + int targetLength) { + if (filename == result) { + return; + } + int fillerIndex = result.indexOf(Abbreviator.FILLER); + assertTrue(fillerIndex >= fixedLen); + } +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/RandomHelper.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/RandomHelper.java index 7da5faed..7318f74f 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/RandomHelper.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/helper/RandomHelper.java @@ -1,46 +1,46 @@ -package org.slf4j.migrator.helper; - -import java.util.Random; - -public class RandomHelper { - - private Random random = new Random(100); - final char folderSeparator; - - RandomHelper(char folderSeparator) { - this.folderSeparator = folderSeparator; - } - - private String randomString(int len) { - StringBuffer buf = new StringBuffer(); - 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) { - StringBuffer buf = new StringBuffer(); - 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(); - } - -} +package org.slf4j.migrator.helper; + +import java.util.Random; + +public class RandomHelper { + + private Random random = new Random(100); + final char folderSeparator; + + RandomHelper(char folderSeparator) { + this.folderSeparator = folderSeparator; + } + + private String randomString(int len) { + StringBuffer buf = new StringBuffer(); + 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) { + StringBuffer buf = new StringBuffer(); + int MAX_NODE_LENGTH = averageNodeLength * 2; + while (buf.length() < totalLength) { + int remaining = totalLength - buf.length(); + int currentNodeLength; + if (remaining > MAX_NODE_LENGTH) { + currentNodeLength = random.nextInt(MAX_NODE_LENGTH) + 1; + buf.append(randomString(currentNodeLength)); + buf.append('/'); + } else { + currentNodeLength = remaining; + buf.append(randomString(currentNodeLength)); + } + } + return buf.toString(); + } + +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/internal/NopProgressListener.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/internal/NopProgressListener.java index 51a239a6..aa2c3d46 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/internal/NopProgressListener.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/internal/NopProgressListener.java @@ -1,30 +1,30 @@ -package org.slf4j.migrator.internal; - -import java.io.File; - -import org.slf4j.migrator.internal.ProgressListener; - -public class NopProgressListener implements ProgressListener { - - public void onDirectory(File file) { - } - - public void onDone() { - } - - public void onFileAddition(File file) { - } - - public void onFileScan(File file) { - } - - public void onInplaceConversion(File file) { - } - - public void onFileScanBegin() { - } - - public void onMigrationBegin() { - } - -} +package org.slf4j.migrator.internal; + +import java.io.File; + +import org.slf4j.migrator.internal.ProgressListener; + +public class NopProgressListener implements ProgressListener { + + public void onDirectory(File file) { + } + + public void onDone() { + } + + public void onFileAddition(File file) { + } + + public void onFileScan(File file) { + } + + public void onInplaceConversion(File file) { + } + + public void onFileScanBegin() { + } + + public void onMigrationBegin() { + } + +} diff --git a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TriviialMatcher.java b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TriviialMatcher.java index cb4d359e..4621082e 100644 --- a/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TriviialMatcher.java +++ b/slf4j-migrator/src/test/java/org/slf4j/migrator/line/TriviialMatcher.java @@ -1,65 +1,65 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.migrator.line; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.regex.Pattern; - -import org.slf4j.migrator.line.ConversionRule; -import org.slf4j.migrator.line.MultiGroupConversionRule; -import org.slf4j.migrator.line.RuleSet; -import org.slf4j.migrator.line.SingleConversionRule; - -class TrivialMatcher implements RuleSet { - - private ArrayList conversionRuleList; - - public TrivialMatcher() { - //simple rule no capturing group is defined, we use default capturing group which is group zero - SingleConversionRule cr = new SingleConversionRule(Pattern.compile("import org.slf4j.converter"), - "simple replacement with an unique capturing group"); - - //we define 4 differents capturing groups - MultiGroupConversionRule cr1 = new MultiGroupConversionRule(Pattern.compile("(first group)( second group)( third group)( 4th group)")); - //group zero is ignored during treatment - //replacement for the first - cr1.addReplacement(1, "1st group"); - //no replacement for the second group it will remains the same - //empty string for the third group it will be deleted - cr1.addReplacement(3, ""); - //no replacement for the third group it will remains the same - - conversionRuleList = new ArrayList(); - conversionRuleList.add(cr); - conversionRuleList.add(cr1); - } - - public Iterator iterator() { - return conversionRuleList.iterator(); - } - - +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.migrator.line; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.regex.Pattern; + +import org.slf4j.migrator.line.ConversionRule; +import org.slf4j.migrator.line.MultiGroupConversionRule; +import org.slf4j.migrator.line.RuleSet; +import org.slf4j.migrator.line.SingleConversionRule; + +class TrivialMatcher implements RuleSet { + + private ArrayList conversionRuleList; + + public TrivialMatcher() { + //simple rule no capturing group is defined, we use default capturing group which is group zero + SingleConversionRule cr = new SingleConversionRule(Pattern.compile("import org.slf4j.converter"), + "simple replacement with an unique capturing group"); + + //we define 4 differents capturing groups + MultiGroupConversionRule cr1 = new MultiGroupConversionRule(Pattern.compile("(first group)( second group)( third group)( 4th group)")); + //group zero is ignored during treatment + //replacement for the first + cr1.addReplacement(1, "1st group"); + //no replacement for the second group it will remains the same + //empty string for the third group it will be deleted + cr1.addReplacement(3, ""); + //no replacement for the third group it will remains the same + + conversionRuleList = new ArrayList(); + conversionRuleList.add(cr); + conversionRuleList.add(cr1); + } + + public Iterator iterator() { + return conversionRuleList.iterator(); + } + + } \ No newline at end of file diff --git a/slf4j-nop/LICENSE.txt b/slf4j-nop/LICENSE.txt index f6e2f31f..508a2728 100644 --- a/slf4j-nop/LICENSE.txt +++ b/slf4j-nop/LICENSE.txt @@ -1,24 +1,24 @@ -Copyright (c) 2004-2007 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-nop/pom.xml b/slf4j-nop/pom.xml index baddf306..fed1241c 100644 --- a/slf4j-nop/pom.xml +++ b/slf4j-nop/pom.xml @@ -1,52 +1,52 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - slf4j-nop - jar - SLF4J NOP Binding - - http://www.slf4j.org - - The slf4j NOP binding - - - - - org.slf4j - slf4j-api - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - ${parsedVersion.osgiVersion} - ${project.description} - ${project.version} - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + slf4j-nop + jar + SLF4J NOP Binding + + http://www.slf4j.org + + The slf4j NOP binding + + + + + org.slf4j + slf4j-api + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + ${parsedVersion.osgiVersion} + ${project.description} + ${project.version} + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + + + \ No newline at end of file diff --git a/slf4j-nop/src/main/java/org/slf4j/impl/NOPLoggerFactory.java b/slf4j-nop/src/main/java/org/slf4j/impl/NOPLoggerFactory.java index 0374629e..c63331c3 100644 --- a/slf4j-nop/src/main/java/org/slf4j/impl/NOPLoggerFactory.java +++ b/slf4j-nop/src/main/java/org/slf4j/impl/NOPLoggerFactory.java @@ -1,58 +1,58 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.Logger; -import org.slf4j.helpers.NOPLogger; - - -/** - * NOPLoggerFactory is an trivial implementation of {@link - * ILoggerFactory} which always returns the unique instance of - * NOPLogger. - * - * @author Ceki Gülcü - */ -public class NOPLoggerFactory implements ILoggerFactory { - - public NOPLoggerFactory() { - // nothing to do - } - - public Logger getLogger(String name) { - return NOPLogger.NOP_LOGGER; - } - -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.Logger; +import org.slf4j.helpers.NOPLogger; + + +/** + * NOPLoggerFactory is an trivial implementation of {@link + * ILoggerFactory} which always returns the unique instance of + * NOPLogger. + * + * @author Ceki Gülcü + */ +public class NOPLoggerFactory implements ILoggerFactory { + + public NOPLoggerFactory() { + // nothing to do + } + + public Logger getLogger(String name) { + return NOPLogger.NOP_LOGGER; + } + +} diff --git a/slf4j-nop/src/main/java/org/slf4j/impl/StaticLoggerBinder.java b/slf4j-nop/src/main/java/org/slf4j/impl/StaticLoggerBinder.java index 32958713..109e4152 100644 --- a/slf4j-nop/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-nop/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,89 +1,89 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - * - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - - /** - * Declare the version of the SLF4J API this implementation is compiled against. - * The value of this field is 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.5.10"; // !final - - private static final String loggerFactoryClassStr = NOPLoggerFactory.class.getName(); - - /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method - * should always be the same object - */ - private final ILoggerFactory loggerFactory; - - private StaticLoggerBinder() { - loggerFactory = new NOPLoggerFactory(); - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + * + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + + /** + * Declare the version of the SLF4J API this implementation is compiled against. + * The value of this field is 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.5.10"; // !final + + private static final String loggerFactoryClassStr = NOPLoggerFactory.class.getName(); + + /** The ILoggerFactory instance returned by the {@link #getLoggerFactory} method + * should always be the same object + */ + private final ILoggerFactory loggerFactory; + + private StaticLoggerBinder() { + loggerFactory = new NOPLoggerFactory(); + } + + public ILoggerFactory getLoggerFactory() { + return loggerFactory; + } + + public String getLoggerFactoryClassStr() { + return loggerFactoryClassStr; + } +} diff --git a/slf4j-nop/src/main/java/org/slf4j/impl/StaticMDCBinder.java b/slf4j-nop/src/main/java/org/slf4j/impl/StaticMDCBinder.java index 62b9f865..0b9fb17e 100644 --- a/slf4j-nop/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-nop/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,34 +1,34 @@ -package org.slf4j.impl; - -import org.slf4j.helpers.NOPMakerAdapter; -import org.slf4j.spi.MDCAdapter; - - -/** - * This implementation is bound to {@link NOPMakerAdapter}. - * - * @author Ceki Gülcü - */ -public class 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 NOPMakerAdapter(); - } - - public String getMDCAdapterClassStr() { - return NOPMakerAdapter.class.getName(); - } -} +package org.slf4j.impl; + +import org.slf4j.helpers.NOPMakerAdapter; +import org.slf4j.spi.MDCAdapter; + + +/** + * This implementation is bound to {@link NOPMakerAdapter}. + * + * @author Ceki Gülcü + */ +public class 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 NOPMakerAdapter(); + } + + public String getMDCAdapterClassStr() { + return NOPMakerAdapter.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 b37c3640..cb4faa9b 100644 --- a/slf4j-nop/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-nop/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,77 +1,77 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - - -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + + +} diff --git a/slf4j-nop/src/main/resources/META-INF/MANIFEST.MF b/slf4j-nop/src/main/resources/META-INF/MANIFEST.MF index 3623e745..25891ad5 100644 --- a/slf4j-nop/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-nop/src/main/resources/META-INF/MANIFEST.MF @@ -1,9 +1,9 @@ -Implementation-Title: slf4j-nop -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.nop -Bundle-Name: slf4j-nop -Bundle-Vendor: SLF4J.ORG -Bundle-RequiredExecutionEnvironment: J2SE-1.3 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion} +Implementation-Title: slf4j-nop +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.nop +Bundle-Name: slf4j-nop +Bundle-Vendor: SLF4J.ORG +Bundle-RequiredExecutionEnvironment: J2SE-1.3 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion} Fragment-Host: slf4j.api \ No newline at end of file diff --git a/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java b/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java index dc84aa20..dfec4593 100644 --- a/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java @@ -1,129 +1,129 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.CH - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j; - -import junit.framework.TestCase; - - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - * - */ -public class InvocationTest extends TestCase { - - public InvocationTest (String arg0) { - super(arg0); - } - - 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"); - - 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(); - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.CH + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j; + +import junit.framework.TestCase; + + +/** + * Test whether invoking the SLF4J API causes problems or not. + * + * @author Ceki Gulcu + * + */ +public class InvocationTest extends TestCase { + + public InvocationTest (String arg0) { + super(arg0); + } + + 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"); + + 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-osgi-integration-test/pom.xml b/slf4j-osgi-integration-test/pom.xml index b07050f7..8ea99dc7 100644 --- a/slf4j-osgi-integration-test/pom.xml +++ b/slf4j-osgi-integration-test/pom.xml @@ -1,5 +1,5 @@ diff --git a/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/jdk/test/JdkBundleTest.java b/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/jdk/test/JdkBundleTest.java index a146fe1a..f739150f 100644 --- a/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/jdk/test/JdkBundleTest.java +++ b/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/jdk/test/JdkBundleTest.java @@ -1,176 +1,176 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.osgi.integration.jdk.test; - -import java.util.ArrayList; -import java.util.List; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.Constants; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.osgi.integration.IntegrationTestConstants; -import org.slf4j.osgi.test.service.Probe; -import org.springframework.osgi.test.ConfigurableBundleCreatorTests; - -/** - * - * JdkBundleTest starts up an OSGi environment (equinox, - * knopflerfish, or felix according to the profile selected) and installs the - * slf4j.osgi.test.bundle, the slf4j.jdk bundle and the bundles they depend on. - * - * The test classes in this project will be turned into a virtual bundle which is - * also installed and the tests are then run inside the OSGi runtime. - * - * The tests have access to a BundleContext, which we use to test that all bundles have - * been started. - * - * - * @author John Conlon - */ -public class JdkBundleTest extends ConfigurableBundleCreatorTests implements IntegrationTestConstants{ - - - - - - /** - * The manifest to use for the "virtual bundle" created out of the test - * classes and resources in this project - * - * This is actually the boilerplate manifest with one additional - * import-package added. We should provide a simpler customization point for - * such use cases that doesn't require duplication of the entire manifest... - */ - protected String getManifestLocation() { - return "classpath:org/slf4j/osgi/integration/jdk/test/MANIFEST.MF"; - } - - /** - * The location of the packaged OSGi bundles to be installed for this test. - * Values are Spring resource paths. The bundles we want to use are part of - * the same multi-project maven build as this project is. Hence we use the - * localMavenArtifact helper method to find the bundles produced by the - * package phase of the maven build (these tests will run after the - * packaging phase, in the integration-test phase). - * - * JUnit, commons-logging, spring-core and the spring OSGi test bundle are - * automatically included so they do not need to be specified here. - * - * Our test bundles are using package import and export versions to keep - * these other logging bundles from getting mixed up with our test bundles. - */ - protected String[] getBundleLocations() { - return new String[] { - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "aopalliance.osgi", "1.0-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "spring-context", "2.1-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-beans", - "2.1-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "spring-osgi-core", "1.0-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-aop", - "2.1-SNAPSHOT"), - localMavenArtifact(SLF4J_GROUP_ID, API_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, JDK14_BINDING_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, TEST_BUNDLE_ARTIFACT_ID, - SLF4J_VERSION_UNDER_TEST) }; - } - - /** - * The superclass provides us access to the root bundle context via the - * 'getBundleContext' operation. Make sure it is not null. - */ - public void testOSGiStartedOk() { - BundleContext bundleContext = getBundleContext(); - assertNotNull(bundleContext); - - } - - /** - * Makes sure our bundles are in the OSGi runtime and their state is Active. - * - */ - public void testSlf4jNopBundleIntegration() { - Logger log = LoggerFactory.getLogger(JdkBundleTest.class); - assertNotNull(log); - BundleContext context = getBundleContext(); - List symNames = new ArrayList(); - - Bundle[] bundles = context.getBundles(); - log.info("Loaded bundles:"); - for (int i = 0; i < bundles.length; i++) { - Bundle bundle = bundles[i]; - assertEquals("Bundle " + bundle.getSymbolicName() - + " is not active.", Bundle.ACTIVE, bundle.getState()); - symNames.add(bundle.getSymbolicName()); - if (bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR) != null) { - log.info("Symbolic Name:" + bundle.getSymbolicName() - + ", Activator:" - + bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR)); - } else { - log.info("Symbolic Name:" + bundle.getSymbolicName()); - } - } - - assertTrue(symNames.contains(JDK_BINDING_BUNDLE_SYM_NAME)); - assertTrue(symNames.contains(TEST_BUNDLE_SYM_NAME)); - - } - - public void testProbeService(){ - Logger log = LoggerFactory.getLogger(JdkBundleTest.class); - log.debug("Testing probe"); - BundleContext context = getBundleContext(); - ServiceReference ref = context.getServiceReference( Probe.class.getName() ); - assertNotNull( "Service Reference is null", ref ); - Probe probe = ( Probe ) context.getService( ref ); - assertNotNull( "Cannot find the probe service", probe ); - - try { - probe.testCommonslogging(); - fail("Expected exception while testing commons logging."); - } catch (Throwable t){ - log.debug("Failed to execute the probe.testCommonsLogging. "+t); - - } - - context.ungetService( ref ); - - log.debug("Tested probe."); - } - -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.osgi.integration.jdk.test; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.osgi.integration.IntegrationTestConstants; +import org.slf4j.osgi.test.service.Probe; +import org.springframework.osgi.test.ConfigurableBundleCreatorTests; + +/** + * + * JdkBundleTest starts up an OSGi environment (equinox, + * knopflerfish, or felix according to the profile selected) and installs the + * slf4j.osgi.test.bundle, the slf4j.jdk bundle and the bundles they depend on. + * + * The test classes in this project will be turned into a virtual bundle which is + * also installed and the tests are then run inside the OSGi runtime. + * + * The tests have access to a BundleContext, which we use to test that all bundles have + * been started. + * + * + * @author John Conlon + */ +public class JdkBundleTest extends ConfigurableBundleCreatorTests implements IntegrationTestConstants{ + + + + + + /** + * The manifest to use for the "virtual bundle" created out of the test + * classes and resources in this project + * + * This is actually the boilerplate manifest with one additional + * import-package added. We should provide a simpler customization point for + * such use cases that doesn't require duplication of the entire manifest... + */ + protected String getManifestLocation() { + return "classpath:org/slf4j/osgi/integration/jdk/test/MANIFEST.MF"; + } + + /** + * The location of the packaged OSGi bundles to be installed for this test. + * Values are Spring resource paths. The bundles we want to use are part of + * the same multi-project maven build as this project is. Hence we use the + * localMavenArtifact helper method to find the bundles produced by the + * package phase of the maven build (these tests will run after the + * packaging phase, in the integration-test phase). + * + * JUnit, commons-logging, spring-core and the spring OSGi test bundle are + * automatically included so they do not need to be specified here. + * + * Our test bundles are using package import and export versions to keep + * these other logging bundles from getting mixed up with our test bundles. + */ + protected String[] getBundleLocations() { + return new String[] { + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "aopalliance.osgi", "1.0-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "spring-context", "2.1-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-beans", + "2.1-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "spring-osgi-core", "1.0-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-aop", + "2.1-SNAPSHOT"), + localMavenArtifact(SLF4J_GROUP_ID, API_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, JDK14_BINDING_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, TEST_BUNDLE_ARTIFACT_ID, + SLF4J_VERSION_UNDER_TEST) }; + } + + /** + * The superclass provides us access to the root bundle context via the + * 'getBundleContext' operation. Make sure it is not null. + */ + public void testOSGiStartedOk() { + BundleContext bundleContext = getBundleContext(); + assertNotNull(bundleContext); + + } + + /** + * Makes sure our bundles are in the OSGi runtime and their state is Active. + * + */ + public void testSlf4jNopBundleIntegration() { + Logger log = LoggerFactory.getLogger(JdkBundleTest.class); + assertNotNull(log); + BundleContext context = getBundleContext(); + List symNames = new ArrayList(); + + Bundle[] bundles = context.getBundles(); + log.info("Loaded bundles:"); + for (int i = 0; i < bundles.length; i++) { + Bundle bundle = bundles[i]; + assertEquals("Bundle " + bundle.getSymbolicName() + + " is not active.", Bundle.ACTIVE, bundle.getState()); + symNames.add(bundle.getSymbolicName()); + if (bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR) != null) { + log.info("Symbolic Name:" + bundle.getSymbolicName() + + ", Activator:" + + bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR)); + } else { + log.info("Symbolic Name:" + bundle.getSymbolicName()); + } + } + + assertTrue(symNames.contains(JDK_BINDING_BUNDLE_SYM_NAME)); + assertTrue(symNames.contains(TEST_BUNDLE_SYM_NAME)); + + } + + public void testProbeService(){ + Logger log = LoggerFactory.getLogger(JdkBundleTest.class); + log.debug("Testing probe"); + BundleContext context = getBundleContext(); + ServiceReference ref = context.getServiceReference( Probe.class.getName() ); + assertNotNull( "Service Reference is null", ref ); + Probe probe = ( Probe ) context.getService( ref ); + assertNotNull( "Cannot find the probe service", probe ); + + try { + probe.testCommonslogging(); + fail("Expected exception while testing commons logging."); + } catch (Throwable t){ + log.debug("Failed to execute the probe.testCommonsLogging. "+t); + + } + + context.ungetService( ref ); + + log.debug("Tested probe."); + } + +} diff --git a/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/log4j/test/Log4JBundleTest.java b/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/log4j/test/Log4JBundleTest.java index 43a960e6..556335c5 100644 --- a/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/log4j/test/Log4JBundleTest.java +++ b/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/log4j/test/Log4JBundleTest.java @@ -1,181 +1,181 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.osgi.integration.log4j.test; - -import java.util.ArrayList; -import java.util.List; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.Constants; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.osgi.integration.IntegrationTestConstants; -import org.slf4j.osgi.test.service.Probe; -import org.springframework.osgi.test.ConfigurableBundleCreatorTests; - -/** - * - * Log4JBundleTest starts up an OSGi environment (equinox, - * knopflerfish, or felix according to the profile selected) and installs the - * slf4j.osgi.test.bundle, the slf4j.log4j12 bundle and the bundles they depend - * on. - * - * The slf4j.log4j12 will use the log4j bundle associated with the Spring-OSGi - * testing framework. - * - * The test classes in this project will be turned into a virtual bundle which - * is also installed and the tests are then run inside the OSGi runtime. - * - * The tests have access to a BundleContext, which we use to test that all - * bundles have been started. - * - * - * @author John Conlon - */ -public class Log4JBundleTest extends ConfigurableBundleCreatorTests implements IntegrationTestConstants { - - - - - - - /** - * The manifest to use for the "virtual bundle" created out of the test - * classes and resources in this project - * - * This is actually the boilerplate manifest with one additional - * import-package added. We should provide a simpler customization point for - * such use cases that doesn't require duplication of the entire manifest... - */ - protected String getManifestLocation() { - return "classpath:org/slf4j/osgi/integration/log4j/test/MANIFEST.MF"; - } - - /** - * The location of the packaged OSGi bundles to be installed for this test. - * Values are Spring resource paths. The bundles we want to use are part of - * the same multi-project maven build as this project is. Hence we use the - * localMavenArtifact helper method to find the bundles produced by the - * package phase of the maven build (these tests will run after the - * packaging phase, in the integration-test phase). - * - * JUnit, commons-logging, spring-core and the spring OSGi test bundle are - * automatically included so they do not need to be specified here. - * - * Except in the case of slf4j.log4j12 using the log4j bundle associated - * with the Spring-OSGi testing framework our test bundles are using package - * import and export versions to keep these other logging bundles from - * getting mixed up with our test bundles. - */ - protected String[] getBundleLocations() { - return new String[] { - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "aopalliance.osgi", "1.0-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "spring-context", "2.1-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-beans", - "2.1-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "spring-osgi-core", "1.0-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-aop", - "2.1-SNAPSHOT"), - localMavenArtifact(SLF4J_GROUP_ID, API_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, LOG4J12_BINDING_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, TEST_BUNDLE_ARTIFACT_ID, - SLF4J_VERSION_UNDER_TEST) }; - } - - /** - * The superclass provides us access to the root bundle context via the - * 'getBundleContext' operation. Make sure it is not null. - */ - public void testOSGiStartedOk() { - BundleContext bundleContext = getBundleContext(); - assertNotNull(bundleContext); - - } - - /** - * Makes sure our bundles are in the OSGi runtime and their state is Active. - * - */ - public void testSlf4jLog4j12BundleIntegration() { - Logger log = LoggerFactory.getLogger(Log4JBundleTest.class); - assertNotNull(log); - BundleContext context = getBundleContext(); - List symNames = new ArrayList(); - - Bundle[] bundles = context.getBundles(); - log.info("Loaded bundles:"); - for (int i = 0; i < bundles.length; i++) { - Bundle bundle = bundles[i]; - assertEquals("Bundle " + bundle.getSymbolicName() - + " is not active.", Bundle.ACTIVE, bundle.getState()); - symNames.add(bundle.getSymbolicName()); - if (bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR) != null) { - log.info("Symbolic Name:" + bundle.getSymbolicName() - + ", Activator:" - + bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR)); - } else { - log.info("Symbolic Name:" + bundle.getSymbolicName()); - } - } - - assertTrue(symNames.contains(LOG4J_BINDING_BUNDLE_SYM_NAME)); - assertTrue(symNames.contains(TEST_BUNDLE_SYM_NAME)); - - } - - public void testProbeService() { - BundleContext context = getBundleContext(); - ServiceReference ref = context.getServiceReference(Probe.class - .getName()); - assertNotNull("Service Reference is null", ref); - Probe probe = null; - - probe = (Probe) context.getService(ref); - assertNotNull("Cannot find the probe service", probe); - - try { - probe.testCommonslogging(); - fail("The commons logging package should not be found. Instead an exception should be thrown."); - } catch (Throwable t) { - // "Expect.",t); - } - - context.ungetService(ref); - - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.osgi.integration.log4j.test; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.osgi.integration.IntegrationTestConstants; +import org.slf4j.osgi.test.service.Probe; +import org.springframework.osgi.test.ConfigurableBundleCreatorTests; + +/** + * + * Log4JBundleTest starts up an OSGi environment (equinox, + * knopflerfish, or felix according to the profile selected) and installs the + * slf4j.osgi.test.bundle, the slf4j.log4j12 bundle and the bundles they depend + * on. + * + * The slf4j.log4j12 will use the log4j bundle associated with the Spring-OSGi + * testing framework. + * + * The test classes in this project will be turned into a virtual bundle which + * is also installed and the tests are then run inside the OSGi runtime. + * + * The tests have access to a BundleContext, which we use to test that all + * bundles have been started. + * + * + * @author John Conlon + */ +public class Log4JBundleTest extends ConfigurableBundleCreatorTests implements IntegrationTestConstants { + + + + + + + /** + * The manifest to use for the "virtual bundle" created out of the test + * classes and resources in this project + * + * This is actually the boilerplate manifest with one additional + * import-package added. We should provide a simpler customization point for + * such use cases that doesn't require duplication of the entire manifest... + */ + protected String getManifestLocation() { + return "classpath:org/slf4j/osgi/integration/log4j/test/MANIFEST.MF"; + } + + /** + * The location of the packaged OSGi bundles to be installed for this test. + * Values are Spring resource paths. The bundles we want to use are part of + * the same multi-project maven build as this project is. Hence we use the + * localMavenArtifact helper method to find the bundles produced by the + * package phase of the maven build (these tests will run after the + * packaging phase, in the integration-test phase). + * + * JUnit, commons-logging, spring-core and the spring OSGi test bundle are + * automatically included so they do not need to be specified here. + * + * Except in the case of slf4j.log4j12 using the log4j bundle associated + * with the Spring-OSGi testing framework our test bundles are using package + * import and export versions to keep these other logging bundles from + * getting mixed up with our test bundles. + */ + protected String[] getBundleLocations() { + return new String[] { + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "aopalliance.osgi", "1.0-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "spring-context", "2.1-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-beans", + "2.1-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "spring-osgi-core", "1.0-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-aop", + "2.1-SNAPSHOT"), + localMavenArtifact(SLF4J_GROUP_ID, API_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, LOG4J12_BINDING_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, TEST_BUNDLE_ARTIFACT_ID, + SLF4J_VERSION_UNDER_TEST) }; + } + + /** + * The superclass provides us access to the root bundle context via the + * 'getBundleContext' operation. Make sure it is not null. + */ + public void testOSGiStartedOk() { + BundleContext bundleContext = getBundleContext(); + assertNotNull(bundleContext); + + } + + /** + * Makes sure our bundles are in the OSGi runtime and their state is Active. + * + */ + public void testSlf4jLog4j12BundleIntegration() { + Logger log = LoggerFactory.getLogger(Log4JBundleTest.class); + assertNotNull(log); + BundleContext context = getBundleContext(); + List symNames = new ArrayList(); + + Bundle[] bundles = context.getBundles(); + log.info("Loaded bundles:"); + for (int i = 0; i < bundles.length; i++) { + Bundle bundle = bundles[i]; + assertEquals("Bundle " + bundle.getSymbolicName() + + " is not active.", Bundle.ACTIVE, bundle.getState()); + symNames.add(bundle.getSymbolicName()); + if (bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR) != null) { + log.info("Symbolic Name:" + bundle.getSymbolicName() + + ", Activator:" + + bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR)); + } else { + log.info("Symbolic Name:" + bundle.getSymbolicName()); + } + } + + assertTrue(symNames.contains(LOG4J_BINDING_BUNDLE_SYM_NAME)); + assertTrue(symNames.contains(TEST_BUNDLE_SYM_NAME)); + + } + + public void testProbeService() { + BundleContext context = getBundleContext(); + ServiceReference ref = context.getServiceReference(Probe.class + .getName()); + assertNotNull("Service Reference is null", ref); + Probe probe = null; + + probe = (Probe) context.getService(ref); + assertNotNull("Cannot find the probe service", probe); + + try { + probe.testCommonslogging(); + fail("The commons logging package should not be found. Instead an exception should be thrown."); + } catch (Throwable t) { + // "Expect.",t); + } + + context.ungetService(ref); + + } +} diff --git a/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/logservice/test/LogServiceBundleTest.java b/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/logservice/test/LogServiceBundleTest.java index fa6a847e..436c6122 100644 --- a/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/logservice/test/LogServiceBundleTest.java +++ b/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/logservice/test/LogServiceBundleTest.java @@ -1,188 +1,188 @@ -/* - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.osgi.integration.logservice.test; - -import java.util.ArrayList; -import java.util.List; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.Constants; -import org.osgi.framework.ServiceReference; -import org.osgi.service.log.LogService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.osgi.integration.IntegrationTestConstants; -import org.slf4j.osgi.integration.nop.test.NopBundleTest; -import org.springframework.osgi.test.ConfigurableBundleCreatorTests; - -/** - * - * LogServiceBundleTest starts up an OSGi environment (equinox, - * knopflerfish, or felix according to the profile selected) and installs the - * slf4j.osgi.test.bundle, the slf4j.simple bundle and the bundles they depend - * on. - * - * The test classes in this project will be turned into a virtual bundle which - * is also installed and the tests are then run inside the OSGi runtime. - * - * The tests have access to a BundleContext, which we use to test that all - * bundles have been started. - * - * - * @author John Conlon - */ -public class LogServiceBundleTest extends ConfigurableBundleCreatorTests implements IntegrationTestConstants{ - - - - - /** - * The manifest to use for the "virtual bundle" created out of the test - * classes and resources in this project - * - * This is actually the boilerplate manifest with one additional - * import-package added. We should provide a simpler customization point for - * such use cases that doesn't require duplication of the entire manifest... - */ - protected String getManifestLocation() { - return "classpath:org/slf4j/osgi/integration/logservice/test/MANIFEST.MF"; - } - - /** - * The location of the packaged OSGi bundles to be installed for this test. - * Values are Spring resource paths. The bundles we want to use are part of - * the same multi-project maven build as this project is. Hence we use the - * localMavenArtifact helper method to find the bundles produced by the - * package phase of the maven build (these tests will run after the - * packaging phase, in the integration-test phase). - * - * JUnit, commons-logging, spring-core and the spring OSGi test bundle are - * automatically included so they do not need to be specified here. - * - * Our test bundles are using package import and export versions to keep - * these other logging bundles from getting mixed up with our test bundles. - */ - protected String[] getBundleLocations() { - return new String[] { - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "aopalliance.osgi", "1.0-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "spring-context", "2.1-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-beans", - "2.1-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "spring-osgi-core", "1.0-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-aop", - "2.1-SNAPSHOT"), - localMavenArtifact( "org.osgi", "org.osgi.compendium", "4.0" ), - localMavenArtifact(SLF4J_GROUP_ID, API_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, - SIMPLE_BINDING_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, - LOGSERVICE_ADAPTER_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST) }; - } - - /** - * The superclass provides us access to the root bundle context via the - * 'getBundleContext' operation. Make sure it is not null. - */ - public void testOSGiStartedOk() { - BundleContext bundleContext = getBundleContext(); - assertNotNull(bundleContext); - - } - - /** - * Makes sure our bundles are in the OSGi runtime and their state is Active. - * - */ - public void testSlf4jLogServiceBundles() { - Logger log = LoggerFactory.getLogger(LogServiceBundleTest.class); - assertNotNull(log); - BundleContext context = getBundleContext(); - List symNames = new ArrayList(); - - Bundle[] bundles = context.getBundles(); - log.info("Loaded bundles:"); - for (int i = 0; i < bundles.length; i++) { - Bundle bundle = bundles[i]; - assertEquals("Bundle " + bundle.getSymbolicName() - + " is not active.", Bundle.ACTIVE, bundle.getState()); - symNames.add(bundle.getSymbolicName()); - if (bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR) != null) { - log.info("Symbolic Name:" + bundle.getSymbolicName() - + ", Activator:" - + bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR)); - } else { - log.info("Symbolic Name:" + bundle.getSymbolicName()); - } - } - - assertTrue(symNames.contains(SIMPLE_BINDING_BUNDLE_SYM_NAME)); - assertTrue(symNames.contains(LOGSERVICE_ADAPTER_BUNDLE_SYM_NAME)); - - } - - public void testLogService() { - Logger log = LoggerFactory.getLogger(NopBundleTest.class); - log.debug("Testing LogSerivce"); - BundleContext context = getBundleContext(); - ServiceReference ref = context.getServiceReference(LogService.class.getName()); - assertNotNull("Service Reference is null", ref); - LogService logService = null; - - logService = (LogService) context.getService(ref); - assertNotNull("Cannot find the probe service", logService); - - exerciseLogService( logService); - exerciseLogService( logService,ref); - - context.ungetService(ref); - } - - private void exerciseLogService(LogService logService, ServiceReference ref){ - logService.log(ref, LogService.LOG_DEBUG, "Loaded bundles" ); - logService.log(ref, LogService.LOG_INFO, "Found LogService. " ); - logService.log(ref, LogService.LOG_WARNING, "Found LogService. " ); - logService.log(ref, LogService.LOG_ERROR, "Found LogService. ", new Exception("just a test.") ); - } - - private void exerciseLogService(LogService logService){ - logService.log(LogService.LOG_DEBUG, "Loaded bundles" ); - logService.log(LogService.LOG_INFO, "Found LogService. " ); - logService.log(LogService.LOG_WARNING, "Found LogService. " ); - logService.log(LogService.LOG_ERROR, "Found LogService. ", new Exception("just a test.") ); - } - -} +/* + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.osgi.integration.logservice.test; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceReference; +import org.osgi.service.log.LogService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.osgi.integration.IntegrationTestConstants; +import org.slf4j.osgi.integration.nop.test.NopBundleTest; +import org.springframework.osgi.test.ConfigurableBundleCreatorTests; + +/** + * + * LogServiceBundleTest starts up an OSGi environment (equinox, + * knopflerfish, or felix according to the profile selected) and installs the + * slf4j.osgi.test.bundle, the slf4j.simple bundle and the bundles they depend + * on. + * + * The test classes in this project will be turned into a virtual bundle which + * is also installed and the tests are then run inside the OSGi runtime. + * + * The tests have access to a BundleContext, which we use to test that all + * bundles have been started. + * + * + * @author John Conlon + */ +public class LogServiceBundleTest extends ConfigurableBundleCreatorTests implements IntegrationTestConstants{ + + + + + /** + * The manifest to use for the "virtual bundle" created out of the test + * classes and resources in this project + * + * This is actually the boilerplate manifest with one additional + * import-package added. We should provide a simpler customization point for + * such use cases that doesn't require duplication of the entire manifest... + */ + protected String getManifestLocation() { + return "classpath:org/slf4j/osgi/integration/logservice/test/MANIFEST.MF"; + } + + /** + * The location of the packaged OSGi bundles to be installed for this test. + * Values are Spring resource paths. The bundles we want to use are part of + * the same multi-project maven build as this project is. Hence we use the + * localMavenArtifact helper method to find the bundles produced by the + * package phase of the maven build (these tests will run after the + * packaging phase, in the integration-test phase). + * + * JUnit, commons-logging, spring-core and the spring OSGi test bundle are + * automatically included so they do not need to be specified here. + * + * Our test bundles are using package import and export versions to keep + * these other logging bundles from getting mixed up with our test bundles. + */ + protected String[] getBundleLocations() { + return new String[] { + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "aopalliance.osgi", "1.0-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "spring-context", "2.1-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-beans", + "2.1-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "spring-osgi-core", "1.0-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-aop", + "2.1-SNAPSHOT"), + localMavenArtifact( "org.osgi", "org.osgi.compendium", "4.0" ), + localMavenArtifact(SLF4J_GROUP_ID, API_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, + SIMPLE_BINDING_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, + LOGSERVICE_ADAPTER_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST) }; + } + + /** + * The superclass provides us access to the root bundle context via the + * 'getBundleContext' operation. Make sure it is not null. + */ + public void testOSGiStartedOk() { + BundleContext bundleContext = getBundleContext(); + assertNotNull(bundleContext); + + } + + /** + * Makes sure our bundles are in the OSGi runtime and their state is Active. + * + */ + public void testSlf4jLogServiceBundles() { + Logger log = LoggerFactory.getLogger(LogServiceBundleTest.class); + assertNotNull(log); + BundleContext context = getBundleContext(); + List symNames = new ArrayList(); + + Bundle[] bundles = context.getBundles(); + log.info("Loaded bundles:"); + for (int i = 0; i < bundles.length; i++) { + Bundle bundle = bundles[i]; + assertEquals("Bundle " + bundle.getSymbolicName() + + " is not active.", Bundle.ACTIVE, bundle.getState()); + symNames.add(bundle.getSymbolicName()); + if (bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR) != null) { + log.info("Symbolic Name:" + bundle.getSymbolicName() + + ", Activator:" + + bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR)); + } else { + log.info("Symbolic Name:" + bundle.getSymbolicName()); + } + } + + assertTrue(symNames.contains(SIMPLE_BINDING_BUNDLE_SYM_NAME)); + assertTrue(symNames.contains(LOGSERVICE_ADAPTER_BUNDLE_SYM_NAME)); + + } + + public void testLogService() { + Logger log = LoggerFactory.getLogger(NopBundleTest.class); + log.debug("Testing LogSerivce"); + BundleContext context = getBundleContext(); + ServiceReference ref = context.getServiceReference(LogService.class.getName()); + assertNotNull("Service Reference is null", ref); + LogService logService = null; + + logService = (LogService) context.getService(ref); + assertNotNull("Cannot find the probe service", logService); + + exerciseLogService( logService); + exerciseLogService( logService,ref); + + context.ungetService(ref); + } + + private void exerciseLogService(LogService logService, ServiceReference ref){ + logService.log(ref, LogService.LOG_DEBUG, "Loaded bundles" ); + logService.log(ref, LogService.LOG_INFO, "Found LogService. " ); + logService.log(ref, LogService.LOG_WARNING, "Found LogService. " ); + logService.log(ref, LogService.LOG_ERROR, "Found LogService. ", new Exception("just a test.") ); + } + + private void exerciseLogService(LogService logService){ + logService.log(LogService.LOG_DEBUG, "Loaded bundles" ); + logService.log(LogService.LOG_INFO, "Found LogService. " ); + logService.log(LogService.LOG_WARNING, "Found LogService. " ); + logService.log(LogService.LOG_ERROR, "Found LogService. ", new Exception("just a test.") ); + } + +} diff --git a/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/nop/test/NopBundleTest.java b/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/nop/test/NopBundleTest.java index d9956615..d9394aff 100644 --- a/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/nop/test/NopBundleTest.java +++ b/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/nop/test/NopBundleTest.java @@ -1,174 +1,174 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.osgi.integration.nop.test; - -import java.util.ArrayList; -import java.util.List; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.Constants; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.osgi.integration.IntegrationTestConstants; -import org.slf4j.osgi.test.service.Probe; -import org.springframework.osgi.test.ConfigurableBundleCreatorTests; - -/** - * - * JdkBundleTest starts up an OSGi environment (equinox, - * knopflerfish, or felix according to the profile selected) and installs the - * slf4j.osgi.test.bundle, the slf4j.nop bundle and the bundles they depend on. - * - * The test classes in this project will be turned into a virtual bundle which is - * also installed and the tests are then run inside the OSGi runtime. - * - * The tests have access to a BundleContext, which we use to test that all bundles have - * been started. - * - * - * @author John Conlon - */ -public class NopBundleTest extends ConfigurableBundleCreatorTests implements IntegrationTestConstants{ - - - - /** - * The manifest to use for the "virtual bundle" created out of the test - * classes and resources in this project - * - * This is actually the boilerplate manifest with one additional - * import-package added. We should provide a simpler customization point for - * such use cases that doesn't require duplication of the entire manifest... - */ - protected String getManifestLocation() { - return "classpath:org/slf4j/osgi/integration/nop/test/MANIFEST.MF"; - } - - /** - * The location of the packaged OSGi bundles to be installed for this test. - * Values are Spring resource paths. The bundles we want to use are part of - * the same multi-project maven build as this project is. Hence we use the - * localMavenArtifact helper method to find the bundles produced by the - * package phase of the maven build (these tests will run after the - * packaging phase, in the integration-test phase). - * - * JUnit, commons-logging, spring-core and the spring OSGi test bundle are - * automatically included so they do not need to be specified here. - * - * Our test bundles are using package import and export versions to keep - * these other logging bundles from getting mixed up with our test bundles. - */ - protected String[] getBundleLocations() { - return new String[] { - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "aopalliance.osgi", "1.0-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "spring-context", "2.1-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-beans", - "2.1-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "spring-osgi-core", "1.0-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-aop", - "2.1-SNAPSHOT"), - localMavenArtifact(SLF4J_GROUP_ID, API_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, NOP_BINDING_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, TEST_BUNDLE_ARTIFACT_ID, - SLF4J_VERSION_UNDER_TEST) }; - } - - /** - * The superclass provides us access to the root bundle context via the - * 'getBundleContext' operation. Make sure it is not null. - */ - public void testOSGiStartedOk() { - BundleContext bundleContext = getBundleContext(); - assertNotNull(bundleContext); - - } - - /** - * Makes sure our bundles are in the OSGi runtime and their state is Active. - * - */ - public void testSlf4jNopBundleIntegration() { - Logger log = LoggerFactory.getLogger(NopBundleTest.class); - assertNotNull(log); - BundleContext context = getBundleContext(); - List symNames = new ArrayList(); - - Bundle[] bundles = context.getBundles(); - log.info("Loaded bundles:"); - for (int i = 0; i < bundles.length; i++) { - Bundle bundle = bundles[i]; - assertEquals("Bundle " + bundle.getSymbolicName() - + " is not active.", Bundle.ACTIVE, bundle.getState()); - symNames.add(bundle.getSymbolicName()); - if (bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR) != null) { - log.info("Symbolic Name:" + bundle.getSymbolicName() - + ", Activator:" - + bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR)); - } else { - log.info("Symbolic Name:" + bundle.getSymbolicName()); - } - } - - assertTrue("Could not find "+NOP_BINDING_BUNDLE_SYM_NAME, symNames.contains(NOP_BINDING_BUNDLE_SYM_NAME)); - assertTrue(symNames.contains(TEST_BUNDLE_SYM_NAME)); - - } - - public void testProbeService(){ - Logger log = LoggerFactory.getLogger(NopBundleTest.class); - log.debug("Testing probe"); - BundleContext context = getBundleContext(); - ServiceReference ref = context.getServiceReference( Probe.class.getName() ); - assertNotNull( "Service Reference is null", ref ); - Probe probe = ( Probe ) context.getService( ref ); - assertNotNull( "Cannot find the probe service", probe ); - - try { - probe.testCommonslogging(); - fail("Expected exception while testing commons logging."); - } catch (Throwable t){ - log.debug("Failed to execute the probe.testCommonsLogging. "+t); - - } - - context.ungetService( ref ); - - log.debug("Tested probe."); - } - -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.osgi.integration.nop.test; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.osgi.integration.IntegrationTestConstants; +import org.slf4j.osgi.test.service.Probe; +import org.springframework.osgi.test.ConfigurableBundleCreatorTests; + +/** + * + * JdkBundleTest starts up an OSGi environment (equinox, + * knopflerfish, or felix according to the profile selected) and installs the + * slf4j.osgi.test.bundle, the slf4j.nop bundle and the bundles they depend on. + * + * The test classes in this project will be turned into a virtual bundle which is + * also installed and the tests are then run inside the OSGi runtime. + * + * The tests have access to a BundleContext, which we use to test that all bundles have + * been started. + * + * + * @author John Conlon + */ +public class NopBundleTest extends ConfigurableBundleCreatorTests implements IntegrationTestConstants{ + + + + /** + * The manifest to use for the "virtual bundle" created out of the test + * classes and resources in this project + * + * This is actually the boilerplate manifest with one additional + * import-package added. We should provide a simpler customization point for + * such use cases that doesn't require duplication of the entire manifest... + */ + protected String getManifestLocation() { + return "classpath:org/slf4j/osgi/integration/nop/test/MANIFEST.MF"; + } + + /** + * The location of the packaged OSGi bundles to be installed for this test. + * Values are Spring resource paths. The bundles we want to use are part of + * the same multi-project maven build as this project is. Hence we use the + * localMavenArtifact helper method to find the bundles produced by the + * package phase of the maven build (these tests will run after the + * packaging phase, in the integration-test phase). + * + * JUnit, commons-logging, spring-core and the spring OSGi test bundle are + * automatically included so they do not need to be specified here. + * + * Our test bundles are using package import and export versions to keep + * these other logging bundles from getting mixed up with our test bundles. + */ + protected String[] getBundleLocations() { + return new String[] { + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "aopalliance.osgi", "1.0-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "spring-context", "2.1-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-beans", + "2.1-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "spring-osgi-core", "1.0-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-aop", + "2.1-SNAPSHOT"), + localMavenArtifact(SLF4J_GROUP_ID, API_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, NOP_BINDING_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, TEST_BUNDLE_ARTIFACT_ID, + SLF4J_VERSION_UNDER_TEST) }; + } + + /** + * The superclass provides us access to the root bundle context via the + * 'getBundleContext' operation. Make sure it is not null. + */ + public void testOSGiStartedOk() { + BundleContext bundleContext = getBundleContext(); + assertNotNull(bundleContext); + + } + + /** + * Makes sure our bundles are in the OSGi runtime and their state is Active. + * + */ + public void testSlf4jNopBundleIntegration() { + Logger log = LoggerFactory.getLogger(NopBundleTest.class); + assertNotNull(log); + BundleContext context = getBundleContext(); + List symNames = new ArrayList(); + + Bundle[] bundles = context.getBundles(); + log.info("Loaded bundles:"); + for (int i = 0; i < bundles.length; i++) { + Bundle bundle = bundles[i]; + assertEquals("Bundle " + bundle.getSymbolicName() + + " is not active.", Bundle.ACTIVE, bundle.getState()); + symNames.add(bundle.getSymbolicName()); + if (bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR) != null) { + log.info("Symbolic Name:" + bundle.getSymbolicName() + + ", Activator:" + + bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR)); + } else { + log.info("Symbolic Name:" + bundle.getSymbolicName()); + } + } + + assertTrue("Could not find "+NOP_BINDING_BUNDLE_SYM_NAME, symNames.contains(NOP_BINDING_BUNDLE_SYM_NAME)); + assertTrue(symNames.contains(TEST_BUNDLE_SYM_NAME)); + + } + + public void testProbeService(){ + Logger log = LoggerFactory.getLogger(NopBundleTest.class); + log.debug("Testing probe"); + BundleContext context = getBundleContext(); + ServiceReference ref = context.getServiceReference( Probe.class.getName() ); + assertNotNull( "Service Reference is null", ref ); + Probe probe = ( Probe ) context.getService( ref ); + assertNotNull( "Cannot find the probe service", probe ); + + try { + probe.testCommonslogging(); + fail("Expected exception while testing commons logging."); + } catch (Throwable t){ + log.debug("Failed to execute the probe.testCommonsLogging. "+t); + + } + + context.ungetService( ref ); + + log.debug("Tested probe."); + } + +} diff --git a/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/simple/test/SimpleBundleTest.java b/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/simple/test/SimpleBundleTest.java index 22bcee95..29052ec4 100644 --- a/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/simple/test/SimpleBundleTest.java +++ b/slf4j-osgi-integration-test/src/test/java/org/slf4j/osgi/integration/simple/test/SimpleBundleTest.java @@ -1,177 +1,177 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.osgi.integration.simple.test; - -import java.util.ArrayList; -import java.util.List; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.Constants; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.osgi.integration.IntegrationTestConstants; -import org.slf4j.osgi.integration.nop.test.NopBundleTest; -import org.slf4j.osgi.test.service.Probe; -import org.springframework.osgi.test.ConfigurableBundleCreatorTests; - -/** - * - * LogServiceBundleTest starts up an OSGi environment (equinox, - * knopflerfish, or felix according to the profile selected) and installs the - * slf4j.osgi.test.bundle, the slf4j.simple bundle and the bundles they depend - * on. - * - * The test classes in this project will be turned into a virtual bundle which - * is also installed and the tests are then run inside the OSGi runtime. - * - * The tests have access to a BundleContext, which we use to test that all - * bundles have been started. - * - * - * @author John Conlon - */ -public class SimpleBundleTest extends ConfigurableBundleCreatorTests implements IntegrationTestConstants{ - - - - - /** - * The manifest to use for the "virtual bundle" created out of the test - * classes and resources in this project - * - * This is actually the boilerplate manifest with one additional - * import-package added. We should provide a simpler customization point for - * such use cases that doesn't require duplication of the entire manifest... - */ - protected String getManifestLocation() { - return "classpath:org/slf4j/osgi/integration/simple/test/MANIFEST.MF"; - } - - /** - * The location of the packaged OSGi bundles to be installed for this test. - * Values are Spring resource paths. The bundles we want to use are part of - * the same multi-project maven build as this project is. Hence we use the - * localMavenArtifact helper method to find the bundles produced by the - * package phase of the maven build (these tests will run after the - * packaging phase, in the integration-test phase). - * - * JUnit, commons-logging, spring-core and the spring OSGi test bundle are - * automatically included so they do not need to be specified here. - * - * Our test bundles are using package import and export versions to keep - * these other logging bundles from getting mixed up with our test bundles. - */ - protected String[] getBundleLocations() { - return new String[] { - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "aopalliance.osgi", "1.0-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "spring-context", "2.1-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-beans", - "2.1-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, - "spring-osgi-core", "1.0-SNAPSHOT"), - localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-aop", - "2.1-SNAPSHOT"), - localMavenArtifact(SLF4J_GROUP_ID, API_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, SIMPLE_BINDING_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, JCL104_ADAPTER_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), - localMavenArtifact(SLF4J_GROUP_ID, TEST_BUNDLE_ARTIFACT_ID, - SLF4J_VERSION_UNDER_TEST) }; - } - - /** - * The superclass provides us access to the root bundle context via the - * 'getBundleContext' operation. Make sure it is not null. - */ - public void testOSGiStartedOk() { - BundleContext bundleContext = getBundleContext(); - assertNotNull(bundleContext); - - } - - /** - * Makes sure our bundles are in the OSGi runtime and their state is Active. - * - */ - public void testSlf4jNopBundles() { - Logger log = LoggerFactory.getLogger(SimpleBundleTest.class); - assertNotNull(log); - BundleContext context = getBundleContext(); - List symNames = new ArrayList(); - - Bundle[] bundles = context.getBundles(); - log.info("Loaded bundles:"); - for (int i = 0; i < bundles.length; i++) { - Bundle bundle = bundles[i]; - assertEquals("Bundle " + bundle.getSymbolicName() - + " is not active.", Bundle.ACTIVE, bundle.getState()); - symNames.add(bundle.getSymbolicName()); - if (bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR) != null) { - log.info("Symbolic Name:" + bundle.getSymbolicName() - + ", Activator:" - + bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR)); - } else { - log.info("Symbolic Name:" + bundle.getSymbolicName()); - } - } - - assertTrue(symNames.contains(SIMPLE_BINDING_BUNDLE_SYM_NAME)); - assertTrue(symNames.contains(TEST_BUNDLE_SYM_NAME)); - assertTrue(symNames.contains(JCL_ADAPTER_BUNDLE_SYM_NAME)); - - } - - public void testProbeService() { - Logger log = LoggerFactory.getLogger(NopBundleTest.class); - log.debug("Testing probe"); - BundleContext context = getBundleContext(); - ServiceReference ref = context.getServiceReference(Probe.class.getName()); - assertNotNull("Service Reference is null", ref); - Probe probe = null; - - probe = (Probe) context.getService(ref); - assertNotNull("Cannot find the probe service", probe); - - try { - probe.testCommonslogging(); - - } catch (Throwable t) { - fail("Failed to execute the probe.testCommonsLogging. "+t); - } - context.ungetService(ref); - } - -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.osgi.integration.simple.test; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.osgi.integration.IntegrationTestConstants; +import org.slf4j.osgi.integration.nop.test.NopBundleTest; +import org.slf4j.osgi.test.service.Probe; +import org.springframework.osgi.test.ConfigurableBundleCreatorTests; + +/** + * + * LogServiceBundleTest starts up an OSGi environment (equinox, + * knopflerfish, or felix according to the profile selected) and installs the + * slf4j.osgi.test.bundle, the slf4j.simple bundle and the bundles they depend + * on. + * + * The test classes in this project will be turned into a virtual bundle which + * is also installed and the tests are then run inside the OSGi runtime. + * + * The tests have access to a BundleContext, which we use to test that all + * bundles have been started. + * + * + * @author John Conlon + */ +public class SimpleBundleTest extends ConfigurableBundleCreatorTests implements IntegrationTestConstants{ + + + + + /** + * The manifest to use for the "virtual bundle" created out of the test + * classes and resources in this project + * + * This is actually the boilerplate manifest with one additional + * import-package added. We should provide a simpler customization point for + * such use cases that doesn't require duplication of the entire manifest... + */ + protected String getManifestLocation() { + return "classpath:org/slf4j/osgi/integration/simple/test/MANIFEST.MF"; + } + + /** + * The location of the packaged OSGi bundles to be installed for this test. + * Values are Spring resource paths. The bundles we want to use are part of + * the same multi-project maven build as this project is. Hence we use the + * localMavenArtifact helper method to find the bundles produced by the + * package phase of the maven build (these tests will run after the + * packaging phase, in the integration-test phase). + * + * JUnit, commons-logging, spring-core and the spring OSGi test bundle are + * automatically included so they do not need to be specified here. + * + * Our test bundles are using package import and export versions to keep + * these other logging bundles from getting mixed up with our test bundles. + */ + protected String[] getBundleLocations() { + return new String[] { + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "aopalliance.osgi", "1.0-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "spring-context", "2.1-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-beans", + "2.1-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, + "spring-osgi-core", "1.0-SNAPSHOT"), + localMavenArtifact(SPRINGFRAMEWORK_OSGI_GROUP_NAME, "spring-aop", + "2.1-SNAPSHOT"), + localMavenArtifact(SLF4J_GROUP_ID, API_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, SIMPLE_BINDING_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, JCL104_ADAPTER_BUNDLE_ARTIFACT_ID, SLF4J_VERSION_UNDER_TEST), + localMavenArtifact(SLF4J_GROUP_ID, TEST_BUNDLE_ARTIFACT_ID, + SLF4J_VERSION_UNDER_TEST) }; + } + + /** + * The superclass provides us access to the root bundle context via the + * 'getBundleContext' operation. Make sure it is not null. + */ + public void testOSGiStartedOk() { + BundleContext bundleContext = getBundleContext(); + assertNotNull(bundleContext); + + } + + /** + * Makes sure our bundles are in the OSGi runtime and their state is Active. + * + */ + public void testSlf4jNopBundles() { + Logger log = LoggerFactory.getLogger(SimpleBundleTest.class); + assertNotNull(log); + BundleContext context = getBundleContext(); + List symNames = new ArrayList(); + + Bundle[] bundles = context.getBundles(); + log.info("Loaded bundles:"); + for (int i = 0; i < bundles.length; i++) { + Bundle bundle = bundles[i]; + assertEquals("Bundle " + bundle.getSymbolicName() + + " is not active.", Bundle.ACTIVE, bundle.getState()); + symNames.add(bundle.getSymbolicName()); + if (bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR) != null) { + log.info("Symbolic Name:" + bundle.getSymbolicName() + + ", Activator:" + + bundle.getHeaders().get(Constants.BUNDLE_ACTIVATOR)); + } else { + log.info("Symbolic Name:" + bundle.getSymbolicName()); + } + } + + assertTrue(symNames.contains(SIMPLE_BINDING_BUNDLE_SYM_NAME)); + assertTrue(symNames.contains(TEST_BUNDLE_SYM_NAME)); + assertTrue(symNames.contains(JCL_ADAPTER_BUNDLE_SYM_NAME)); + + } + + public void testProbeService() { + Logger log = LoggerFactory.getLogger(NopBundleTest.class); + log.debug("Testing probe"); + BundleContext context = getBundleContext(); + ServiceReference ref = context.getServiceReference(Probe.class.getName()); + assertNotNull("Service Reference is null", ref); + Probe probe = null; + + probe = (Probe) context.getService(ref); + assertNotNull("Cannot find the probe service", probe); + + try { + probe.testCommonslogging(); + + } catch (Throwable t) { + fail("Failed to execute the probe.testCommonsLogging. "+t); + } + context.ungetService(ref); + } + +} diff --git a/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/jdk/test/MANIFEST.MF b/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/jdk/test/MANIFEST.MF index a0bf3b82..e5f850be 100644 --- a/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/jdk/test/MANIFEST.MF +++ b/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/jdk/test/MANIFEST.MF @@ -1,14 +1,14 @@ -Manifest-Version: 1.0 -Bundle-Name: simple-service-integration-tests -Bundle-SymbolicName: org.slf4j.osgi.integration.jdk.test -Bundle-Vendor: SLF4J ORG -Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator -Import-Package: junit.framework, - org.osgi.framework;specification-version="1.3.0", - org.springframework.core.io;specification-version="2.1.0", - org.springframework.osgi.test, - org.slf4j, - org.slf4j.osgi.test.service - - - +Manifest-Version: 1.0 +Bundle-Name: simple-service-integration-tests +Bundle-SymbolicName: org.slf4j.osgi.integration.jdk.test +Bundle-Vendor: SLF4J ORG +Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator +Import-Package: junit.framework, + org.osgi.framework;specification-version="1.3.0", + org.springframework.core.io;specification-version="2.1.0", + org.springframework.osgi.test, + org.slf4j, + org.slf4j.osgi.test.service + + + diff --git a/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/log4j/test/MANIFEST.MF b/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/log4j/test/MANIFEST.MF index 1c2ca153..cb1bd92d 100644 --- a/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/log4j/test/MANIFEST.MF +++ b/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/log4j/test/MANIFEST.MF @@ -1,14 +1,14 @@ -Manifest-Version: 1.0 -Bundle-Name: simple-service-integration-tests -Bundle-SymbolicName: org.slf4j.osgi.integration.log4j.test -Bundle-Vendor: SLF4J ORG -Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator -Import-Package: junit.framework, - org.osgi.framework;specification-version="1.3.0", - org.springframework.core.io;specification-version="2.1.0", - org.springframework.osgi.test, - org.slf4j, - org.slf4j.osgi.test.service - - - +Manifest-Version: 1.0 +Bundle-Name: simple-service-integration-tests +Bundle-SymbolicName: org.slf4j.osgi.integration.log4j.test +Bundle-Vendor: SLF4J ORG +Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator +Import-Package: junit.framework, + org.osgi.framework;specification-version="1.3.0", + org.springframework.core.io;specification-version="2.1.0", + org.springframework.osgi.test, + org.slf4j, + org.slf4j.osgi.test.service + + + diff --git a/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/logservice/test/MANIFEST.MF b/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/logservice/test/MANIFEST.MF index 22255fcc..a2742be8 100644 --- a/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/logservice/test/MANIFEST.MF +++ b/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/logservice/test/MANIFEST.MF @@ -1,15 +1,15 @@ -Manifest-Version: 1.0 -Bundle-Name: simple-service-integration-tests -Bundle-SymbolicName: org.slf4j.osgi.integration.logservice.test -Bundle-Version: 1.3.0 -Bundle-Vendor: SLF4J ORG -Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator -Import-Package: junit.framework, - org.osgi.framework;specification-version="1.3.0", - org.springframework.core.io;specification-version="2.1.0", - org.springframework.osgi.test, - org.slf4j, - org.osgi.service.log - - - +Manifest-Version: 1.0 +Bundle-Name: simple-service-integration-tests +Bundle-SymbolicName: org.slf4j.osgi.integration.logservice.test +Bundle-Version: 1.3.0 +Bundle-Vendor: SLF4J ORG +Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator +Import-Package: junit.framework, + org.osgi.framework;specification-version="1.3.0", + org.springframework.core.io;specification-version="2.1.0", + org.springframework.osgi.test, + org.slf4j, + org.osgi.service.log + + + diff --git a/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/nop/test/MANIFEST.MF b/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/nop/test/MANIFEST.MF index eebfd6bd..9be5535e 100644 --- a/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/nop/test/MANIFEST.MF +++ b/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/nop/test/MANIFEST.MF @@ -1,14 +1,14 @@ -Manifest-Version: 1.0 -Bundle-Name: simple-service-integration-tests -Bundle-SymbolicName: org.slf4j.osgi.integration.nop.test -Bundle-Vendor: SLF4J ORG -Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator -Import-Package: junit.framework, - org.osgi.framework;specification-version="1.3.0", - org.springframework.core.io;specification-version="2.1.0", - org.springframework.osgi.test, - org.slf4j, - org.slf4j.osgi.test.service - - - +Manifest-Version: 1.0 +Bundle-Name: simple-service-integration-tests +Bundle-SymbolicName: org.slf4j.osgi.integration.nop.test +Bundle-Vendor: SLF4J ORG +Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator +Import-Package: junit.framework, + org.osgi.framework;specification-version="1.3.0", + org.springframework.core.io;specification-version="2.1.0", + org.springframework.osgi.test, + org.slf4j, + org.slf4j.osgi.test.service + + + diff --git a/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/simple/test/MANIFEST.MF b/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/simple/test/MANIFEST.MF index 2f03e1a8..987f81f6 100644 --- a/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/simple/test/MANIFEST.MF +++ b/slf4j-osgi-integration-test/src/test/resources/org/slf4j/osgi/integration/simple/test/MANIFEST.MF @@ -1,14 +1,14 @@ -Manifest-Version: 1.0 -Bundle-Name: simple-service-integration-tests -Bundle-SymbolicName: org.slf4j.osgi.integration.simple.test -Bundle-Vendor: SLF4J ORG -Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator -Import-Package: junit.framework, - org.osgi.framework;specification-version="1.3.0", - org.springframework.core.io;specification-version="2.1.0", - org.springframework.osgi.test, - org.slf4j, - org.slf4j.osgi.test.service - - - +Manifest-Version: 1.0 +Bundle-Name: simple-service-integration-tests +Bundle-SymbolicName: org.slf4j.osgi.integration.simple.test +Bundle-Vendor: SLF4J ORG +Bundle-Activator: org.springframework.osgi.test.JUnitTestActivator +Import-Package: junit.framework, + org.osgi.framework;specification-version="1.3.0", + org.springframework.core.io;specification-version="2.1.0", + org.springframework.osgi.test, + org.slf4j, + org.slf4j.osgi.test.service + + + diff --git a/slf4j-simple/LICENSE.txt b/slf4j-simple/LICENSE.txt index f6e2f31f..508a2728 100644 --- a/slf4j-simple/LICENSE.txt +++ b/slf4j-simple/LICENSE.txt @@ -1,24 +1,24 @@ -Copyright (c) 2004-2007 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-simple/pom.xml b/slf4j-simple/pom.xml index 5b5d66bc..cb5c89c0 100644 --- a/slf4j-simple/pom.xml +++ b/slf4j-simple/pom.xml @@ -1,48 +1,48 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - slf4j-simple - jar - SLF4J Simple Binding - - http://www.slf4j.org - SLF4J Simple binding - - - - org.slf4j - slf4j-api - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - ${parsedVersion.osgiVersion} - ${project.description} - ${project.version} - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + slf4j-simple + jar + SLF4J Simple Binding + + http://www.slf4j.org + SLF4J Simple binding + + + + org.slf4j + slf4j-api + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + ${parsedVersion.osgiVersion} + ${project.description} + ${project.version} + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + + + + \ No newline at end of file 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 955c5854..810d02cf 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLogger.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLogger.java @@ -1,377 +1,377 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import org.slf4j.helpers.MarkerIgnoringBase; -import org.slf4j.helpers.MessageFormatter; - -/** - * A simple (and direct) implementation that logs messages of level - * INFO or higher on the console (System.err). - * - *

The output includes the relative time in milliseconds, thread - * name, the level, logger name, and the message followed by the line - * separator for the host. In log4j terms it amounts to the "%r [%t] - * %level %logger - %m%n" pattern.

- * - *

Sample output follows.

-
-176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
-225 [main] INFO examples.SortAlgo - Entered the sort method.
-304 [main] INFO examples.SortAlgo - Dump of integer array:
-317 [main] INFO examples.SortAlgo - Element [0] = 0
-331 [main] INFO examples.SortAlgo - Element [1] = 1
-343 [main] INFO examples.Sort - The next log statement should be an error message.
-346 [main] ERROR examples.SortAlgo - Tried to dump an uninitialized array.
-        at org.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
-        at org.log4j.examples.Sort.main(Sort.java:64)
-467 [main] INFO  examples.Sort - Exiting main method.
-
- * - * @author Ceki Gülcü - */ -public class SimpleLogger extends MarkerIgnoringBase { - - private static final long serialVersionUID = -6560244151660620173L; - - /** - * Mark the time when this class gets loaded into memory. - */ - private static long startTime = System.currentTimeMillis(); - public static final String LINE_SEPARATOR = - System.getProperty("line.separator"); - private static String INFO_STR = "INFO"; - private static String WARN_STR = "WARN"; - private static String ERROR_STR = "ERROR"; - - /** - * Package access allows only {@link SimpleLoggerFactory} to instantiate - * SimpleLogger instances. - */ - SimpleLogger(String name) { - this.name = name; - } - - /** - * Always returns false. - * @return always false - */ - public boolean isTraceEnabled() { - return false; - } - - /** - * A NOP implementation, as this logger is permanently disabled for - * the TRACE level. - */ - public void trace(String msg) { - // NOP - } - - /** - * A NOP implementation, as this logger is permanently disabled for - * the TRACE level. - */ - public void trace(String format, Object param1) { - // NOP - } - - - /** - * A NOP implementation, as this logger is permanently disabled for - * the TRACE level. - */ - public void trace(String format, Object param1, Object param2) { - // NOP - } - - public void trace(String format, Object[] argArray) { - // NOP - } - - /** - * A NOP implementation, as this logger is permanently disabled for - * the TRACE level. - */ - public void trace(String msg, Throwable t) { - // NOP - } - - - /** - * Always returns false. - * @return always false - */ - public boolean isDebugEnabled() { - return false; - } - - /** - * A NOP implementation, as this logger is permanently disabled for - * the DEBUG level. - */ - public void debug(String msg) { - // NOP - } - - /** - * A NOP implementation, as this logger is permanently disabled for - * the DEBUG level. - */ - public void debug(String format, Object param1) { - // NOP - } - - - /** - * A NOP implementation, as this logger is permanently disabled for - * the DEBUG level. - */ - public void debug(String format, Object param1, Object param2) { - // NOP - } - - public void debug(String format, Object[] argArray) { - // NOP - } - - /** - * A NOP implementation, as this logger is permanently disabled for - * the DEBUG level. - */ - public void debug(String msg, Throwable t) { - // NOP - } - - /** - * This is our internal implementation for logging regular (non-parameterized) - * log messages. - * - * @param level - * @param message - * @param t - */ - private void log(String level, String message, Throwable t) { - StringBuffer buf = new StringBuffer(); - - long millis = System.currentTimeMillis(); - buf.append(millis - startTime); - - buf.append(" ["); - buf.append(Thread.currentThread().getName()); - buf.append("] "); - - buf.append(level); - buf.append(" "); - - buf.append(name); - buf.append(" - "); - - buf.append(message); - - buf.append(LINE_SEPARATOR); - - System.err.print(buf.toString()); - if (t != null) { - t.printStackTrace(System.err); - } - System.err.flush(); - } - - /** - * For formatted messages, first substitute arguments and then log. - * - * @param level - * @param format - * @param param1 - * @param param2 - */ - private void formatAndLog( - String level, String format, Object arg1, Object arg2) { - String message = MessageFormatter.format(format, arg1, arg2); - log(level, message, null); - } - - /** - * For formatted messages, first substitute arguments and then log. - * - * @param level - * @param format - * @param argArray - */ - private void formatAndLog(String level, String format, Object[] argArray) { - String message = MessageFormatter.arrayFormat(format, argArray); - log(level, message, null); - } - - /** - * Always returns true. - */ - public boolean isInfoEnabled() { - return true; - } - - /** - * A simple implementation which always logs messages of level INFO according - * to the format outlined above. - */ - public void info(String msg) { - log(INFO_STR, 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(INFO_STR, 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(INFO_STR, 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(INFO_STR, format, argArray); - } - - - /** - * Log a message of level INFO, including an exception. - */ - public void info(String msg, Throwable t) { - log(INFO_STR, msg, t); - } - - /** - * Always returns true. - */ - public boolean isWarnEnabled() { - return true; - } - - /** - * A simple implementation which always logs messages of level WARN according - * to the format outlined above. - */ - public void warn(String msg) { - log(WARN_STR, 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(WARN_STR, 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(WARN_STR, 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(WARN_STR, format, argArray); - } - - /** - * Log a message of level WARN, including an exception. - */ - public void warn(String msg, Throwable t) { - log(WARN_STR, msg, t); - } - - /** - * Always returns true. - */ - public boolean isErrorEnabled() { - return true; - } - - /** - * A simple implementation which always logs messages of level ERROR according - * to the format outlined above. - */ - public void error(String msg) { - log(ERROR_STR, 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(ERROR_STR, 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(ERROR_STR, 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(ERROR_STR, format, argArray); - } - - - /** - * Log a message of level ERROR, including an exception. - */ - public void error(String msg, Throwable t) { - log(ERROR_STR, msg, t); - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import org.slf4j.helpers.MarkerIgnoringBase; +import org.slf4j.helpers.MessageFormatter; + +/** + * A simple (and direct) implementation that logs messages of level + * INFO or higher on the console (System.err). + * + *

The output includes the relative time in milliseconds, thread + * name, the level, logger name, and the message followed by the line + * separator for the host. In log4j terms it amounts to the "%r [%t] + * %level %logger - %m%n" pattern.

+ * + *

Sample output follows.

+
+176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
+225 [main] INFO examples.SortAlgo - Entered the sort method.
+304 [main] INFO examples.SortAlgo - Dump of integer array:
+317 [main] INFO examples.SortAlgo - Element [0] = 0
+331 [main] INFO examples.SortAlgo - Element [1] = 1
+343 [main] INFO examples.Sort - The next log statement should be an error message.
+346 [main] ERROR examples.SortAlgo - Tried to dump an uninitialized array.
+        at org.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
+        at org.log4j.examples.Sort.main(Sort.java:64)
+467 [main] INFO  examples.Sort - Exiting main method.
+
+ * + * @author Ceki Gülcü + */ +public class SimpleLogger extends MarkerIgnoringBase { + + private static final long serialVersionUID = -6560244151660620173L; + + /** + * Mark the time when this class gets loaded into memory. + */ + private static long startTime = System.currentTimeMillis(); + public static final String LINE_SEPARATOR = + System.getProperty("line.separator"); + private static String INFO_STR = "INFO"; + private static String WARN_STR = "WARN"; + private static String ERROR_STR = "ERROR"; + + /** + * Package access allows only {@link SimpleLoggerFactory} to instantiate + * SimpleLogger instances. + */ + SimpleLogger(String name) { + this.name = name; + } + + /** + * Always returns false. + * @return always false + */ + public boolean isTraceEnabled() { + return false; + } + + /** + * A NOP implementation, as this logger is permanently disabled for + * the TRACE level. + */ + public void trace(String msg) { + // NOP + } + + /** + * A NOP implementation, as this logger is permanently disabled for + * the TRACE level. + */ + public void trace(String format, Object param1) { + // NOP + } + + + /** + * A NOP implementation, as this logger is permanently disabled for + * the TRACE level. + */ + public void trace(String format, Object param1, Object param2) { + // NOP + } + + public void trace(String format, Object[] argArray) { + // NOP + } + + /** + * A NOP implementation, as this logger is permanently disabled for + * the TRACE level. + */ + public void trace(String msg, Throwable t) { + // NOP + } + + + /** + * Always returns false. + * @return always false + */ + public boolean isDebugEnabled() { + return false; + } + + /** + * A NOP implementation, as this logger is permanently disabled for + * the DEBUG level. + */ + public void debug(String msg) { + // NOP + } + + /** + * A NOP implementation, as this logger is permanently disabled for + * the DEBUG level. + */ + public void debug(String format, Object param1) { + // NOP + } + + + /** + * A NOP implementation, as this logger is permanently disabled for + * the DEBUG level. + */ + public void debug(String format, Object param1, Object param2) { + // NOP + } + + public void debug(String format, Object[] argArray) { + // NOP + } + + /** + * A NOP implementation, as this logger is permanently disabled for + * the DEBUG level. + */ + public void debug(String msg, Throwable t) { + // NOP + } + + /** + * This is our internal implementation for logging regular (non-parameterized) + * log messages. + * + * @param level + * @param message + * @param t + */ + private void log(String level, String message, Throwable t) { + StringBuffer buf = new StringBuffer(); + + long millis = System.currentTimeMillis(); + buf.append(millis - startTime); + + buf.append(" ["); + buf.append(Thread.currentThread().getName()); + buf.append("] "); + + buf.append(level); + buf.append(" "); + + buf.append(name); + buf.append(" - "); + + buf.append(message); + + buf.append(LINE_SEPARATOR); + + System.err.print(buf.toString()); + if (t != null) { + t.printStackTrace(System.err); + } + System.err.flush(); + } + + /** + * For formatted messages, first substitute arguments and then log. + * + * @param level + * @param format + * @param param1 + * @param param2 + */ + private void formatAndLog( + String level, String format, Object arg1, Object arg2) { + String message = MessageFormatter.format(format, arg1, arg2); + log(level, message, null); + } + + /** + * For formatted messages, first substitute arguments and then log. + * + * @param level + * @param format + * @param argArray + */ + private void formatAndLog(String level, String format, Object[] argArray) { + String message = MessageFormatter.arrayFormat(format, argArray); + log(level, message, null); + } + + /** + * Always returns true. + */ + public boolean isInfoEnabled() { + return true; + } + + /** + * A simple implementation which always logs messages of level INFO according + * to the format outlined above. + */ + public void info(String msg) { + log(INFO_STR, 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(INFO_STR, 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(INFO_STR, 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(INFO_STR, format, argArray); + } + + + /** + * Log a message of level INFO, including an exception. + */ + public void info(String msg, Throwable t) { + log(INFO_STR, msg, t); + } + + /** + * Always returns true. + */ + public boolean isWarnEnabled() { + return true; + } + + /** + * A simple implementation which always logs messages of level WARN according + * to the format outlined above. + */ + public void warn(String msg) { + log(WARN_STR, 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(WARN_STR, 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(WARN_STR, 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(WARN_STR, format, argArray); + } + + /** + * Log a message of level WARN, including an exception. + */ + public void warn(String msg, Throwable t) { + log(WARN_STR, msg, t); + } + + /** + * Always returns true. + */ + public boolean isErrorEnabled() { + return true; + } + + /** + * A simple implementation which always logs messages of level ERROR according + * to the format outlined above. + */ + public void error(String msg) { + log(ERROR_STR, 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(ERROR_STR, 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(ERROR_STR, 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(ERROR_STR, format, argArray); + } + + + /** + * Log a message of level ERROR, including an exception. + */ + public void error(String msg, Throwable t) { + log(ERROR_STR, 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 6414a542..5525b9ce 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerFactory.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/SimpleLoggerFactory.java @@ -1,73 +1,73 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.ch - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j.impl; - -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.ILoggerFactory; - -/** - * An implementation of {@link ILoggerFactory} which always returns - * {@link SimpleLogger} instances. - * - * @author Ceki Gülcü - */ -public class SimpleLoggerFactory implements ILoggerFactory { - - final static SimpleLoggerFactory INSTANCE = new SimpleLoggerFactory(); - - Map loggerMap; - - public SimpleLoggerFactory() { - loggerMap = new HashMap(); - } - - /** - * Return an appropriate {@link SimpleLogger} instance by name. - */ - public Logger getLogger(String name) { - Logger slogger = null; - // protect against concurrent access of the loggerMap - synchronized (this) { - slogger = (Logger) loggerMap.get(name); - if (slogger == null) { - slogger = new SimpleLogger(name); - loggerMap.put(name, slogger); - } - } - return slogger; - } -} +/* + * Copyright (c) 2004-2005 SLF4J.ORG + * Copyright (c) 2004-2005 QOS.ch + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.ILoggerFactory; + +/** + * An implementation of {@link ILoggerFactory} which always returns + * {@link SimpleLogger} instances. + * + * @author Ceki Gülcü + */ +public class SimpleLoggerFactory implements ILoggerFactory { + + final static SimpleLoggerFactory INSTANCE = new SimpleLoggerFactory(); + + Map loggerMap; + + public SimpleLoggerFactory() { + loggerMap = new HashMap(); + } + + /** + * Return an appropriate {@link SimpleLogger} instance by name. + */ + public Logger getLogger(String name) { + Logger slogger = null; + // protect against concurrent access of the loggerMap + synchronized (this) { + slogger = (Logger) loggerMap.get(name); + if (slogger == null) { + slogger = new SimpleLogger(name); + loggerMap.put(name, slogger); + } + } + return slogger; + } +} 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 87914bec..5bc87a45 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/StaticLoggerBinder.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/StaticLoggerBinder.java @@ -1,82 +1,82 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.impl; - -import org.slf4j.ILoggerFactory; -import org.slf4j.LoggerFactory; -import org.slf4j.spi.LoggerFactoryBinder; - -/** - * The binding of {@link LoggerFactory} class with an actual instance of - * {@link ILoggerFactory} is performed using information returned by this class. - * - * - * @author Ceki Gülcü - */ -public class StaticLoggerBinder implements LoggerFactoryBinder { - - /** - * The unique instance of this class. - * - */ - private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); - - /** - * Return the singleton of this class. - * - * @return the StaticLoggerBinder singleton - */ - public static final StaticLoggerBinder getSingleton() { - return SINGLETON; - } - - - /** - * Declare the version of the SLF4J API this implementation is compiled - * against. The value of this field is 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.5.10"; // !final - - private static final String loggerFactoryClassStr = SimpleLoggerFactory.class.getName(); - - /** - * The ILoggerFactory instance returned by the {@link #getLoggerFactory} - * method should always be the same object - */ - private final ILoggerFactory loggerFactory; - - private StaticLoggerBinder() { - loggerFactory = new SimpleLoggerFactory(); - } - - public ILoggerFactory getLoggerFactory() { - return loggerFactory; - } - - public String getLoggerFactoryClassStr() { - return loggerFactoryClassStr; - } -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.impl; + +import org.slf4j.ILoggerFactory; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggerFactoryBinder; + +/** + * The binding of {@link LoggerFactory} class with an actual instance of + * {@link ILoggerFactory} is performed using information returned by this class. + * + * + * @author Ceki Gülcü + */ +public class StaticLoggerBinder implements LoggerFactoryBinder { + + /** + * The unique instance of this class. + * + */ + private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); + + /** + * Return the singleton of this class. + * + * @return the StaticLoggerBinder singleton + */ + public static final StaticLoggerBinder getSingleton() { + return SINGLETON; + } + + + /** + * Declare the version of the SLF4J API this implementation is compiled + * against. The value of this field is 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.5.10"; // !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 a397bce7..a06185e3 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/StaticMDCBinder.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/StaticMDCBinder.java @@ -1,58 +1,58 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.slf4j.impl; - -import org.slf4j.helpers.NOPMakerAdapter; -import org.slf4j.spi.MDCAdapter; - - -/** - * This implementation is bound to {@link NOPMakerAdapter}. - * - * @author Ceki Gülcü - */ -public class 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 NOPMakerAdapter(); - } - - public String getMDCAdapterClassStr() { - return NOPMakerAdapter.class.getName(); - } -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package org.slf4j.impl; + +import org.slf4j.helpers.NOPMakerAdapter; +import org.slf4j.spi.MDCAdapter; + + +/** + * This implementation is bound to {@link NOPMakerAdapter}. + * + * @author Ceki Gülcü + */ +public class 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 NOPMakerAdapter(); + } + + public String getMDCAdapterClassStr() { + return NOPMakerAdapter.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 6017ea9c..64976686 100644 --- a/slf4j-simple/src/main/java/org/slf4j/impl/StaticMarkerBinder.java +++ b/slf4j-simple/src/main/java/org/slf4j/impl/StaticMarkerBinder.java @@ -1,69 +1,69 @@ -/* - * Copyright (c) 2004-2007 QOS.ch - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - - -package org.slf4j.impl; - -import org.slf4j.IMarkerFactory; -import org.slf4j.MarkerFactory; -import org.slf4j.helpers.BasicMarkerFactory; -import org.slf4j.spi.MarkerFactoryBinder; - -/** - * - * The binding of {@link MarkerFactory} class with an actual instance of - * {@link IMarkerFactory} is performed using information returned by this class. - * - * @author Ceki Gülcü - */ -public class StaticMarkerBinder implements MarkerFactoryBinder { - - /** - * The unique instance of this class. - */ - public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); - - final IMarkerFactory markerFactory = new BasicMarkerFactory(); - - private StaticMarkerBinder() { - } - - /** - * Currently this method always returns an instance of - * {@link BasicMarkerFactory}. - */ - public IMarkerFactory getMarkerFactory() { - return markerFactory; - } - - /** - * Currently, this method returns the class name of - * {@link BasicMarkerFactory}. - */ - public String getMarkerFactoryClassStr() { - return BasicMarkerFactory.class.getName(); - } - - -} +/* + * Copyright (c) 2004-2007 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +package org.slf4j.impl; + +import org.slf4j.IMarkerFactory; +import org.slf4j.MarkerFactory; +import org.slf4j.helpers.BasicMarkerFactory; +import org.slf4j.spi.MarkerFactoryBinder; + +/** + * + * The binding of {@link MarkerFactory} class with an actual instance of + * {@link IMarkerFactory} is performed using information returned by this class. + * + * @author Ceki Gülcü + */ +public class StaticMarkerBinder implements MarkerFactoryBinder { + + /** + * The unique instance of this class. + */ + public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); + + final IMarkerFactory markerFactory = new BasicMarkerFactory(); + + private StaticMarkerBinder() { + } + + /** + * Currently this method always returns an instance of + * {@link BasicMarkerFactory}. + */ + public IMarkerFactory getMarkerFactory() { + return markerFactory; + } + + /** + * Currently, this method returns the class name of + * {@link BasicMarkerFactory}. + */ + public String getMarkerFactoryClassStr() { + return BasicMarkerFactory.class.getName(); + } + + +} diff --git a/slf4j-simple/src/main/resources/META-INF/MANIFEST.MF b/slf4j-simple/src/main/resources/META-INF/MANIFEST.MF index b2aa0c02..54c78bd6 100644 --- a/slf4j-simple/src/main/resources/META-INF/MANIFEST.MF +++ b/slf4j-simple/src/main/resources/META-INF/MANIFEST.MF @@ -1,10 +1,10 @@ -Implementation-Title: slf4j-simple -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: slf4j.simple -Bundle-Name: slf4j-simple -Bundle-Vendor: SLF4J.ORG -Require-Bundle: slf4j.api -Bundle-RequiredExecutionEnvironment: J2SE-1.3 -Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} -Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion} +Implementation-Title: slf4j-simple +Bundle-ManifestVersion: 2 +Bundle-SymbolicName: slf4j.simple +Bundle-Name: slf4j-simple +Bundle-Vendor: SLF4J.ORG +Require-Bundle: slf4j.api +Bundle-RequiredExecutionEnvironment: J2SE-1.3 +Export-Package: org.slf4j.impl;version=${parsedVersion.osgiVersion} +Import-Package: org.slf4j;version=${parsedVersion.osgiVersion}, org.slf4j.spi;version=${parsedVersion.osgiVersion}, org.slf4j.helpers;version=${parsedVersion.osgiVersion} Fragment-Host: slf4j.api \ No newline at end of file diff --git a/slf4j-simple/src/test/java/org/slf4j/InvocationTest.java b/slf4j-simple/src/test/java/org/slf4j/InvocationTest.java index c445ec40..e11b3379 100644 --- a/slf4j-simple/src/test/java/org/slf4j/InvocationTest.java +++ b/slf4j-simple/src/test/java/org/slf4j/InvocationTest.java @@ -1,142 +1,142 @@ -/* - * Copyright (c) 2004-2007 QOS.CH - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package org.slf4j; - -import java.io.PrintStream; - -import junit.framework.TestCase; - - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - * - */ -public class InvocationTest extends TestCase { - - PrintStream old = System.err; - - public InvocationTest (String arg0) { - super(arg0); - } - - protected void setUp() throws Exception { - super.setUp(); - System.setErr(new SilentPrintStream(old)); - } - - 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(); - } -} +/* + * Copyright (c) 2004-2007 QOS.CH + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons + * to whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT + * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY + * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER + * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF + * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, use + * or other dealings in this Software without prior written authorization + * of the copyright holder. + * + */ + +package org.slf4j; + +import java.io.PrintStream; + +import junit.framework.TestCase; + + +/** + * Test whether invoking the SLF4J API causes problems or not. + * + * @author Ceki Gulcu + * + */ +public class InvocationTest extends TestCase { + + PrintStream old = System.err; + + public InvocationTest (String arg0) { + super(arg0); + } + + protected void setUp() throws Exception { + super.setUp(); + System.setErr(new SilentPrintStream(old)); + } + + 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 0070c7ef..617fc239 100644 --- a/slf4j-simple/src/test/java/org/slf4j/SilentPrintStream.java +++ b/slf4j-simple/src/test/java/org/slf4j/SilentPrintStream.java @@ -1,22 +1,22 @@ -package org.slf4j; - -import java.io.PrintStream; - -public class SilentPrintStream extends PrintStream { - - PrintStream other; - - public SilentPrintStream(PrintStream ps) { - super(ps); - other = ps; - } - - public void print(String s) { - } - - public void println(String s) { - } - - public void println(Object x) { - } -} +package org.slf4j; + +import java.io.PrintStream; + +public class SilentPrintStream extends PrintStream { + + PrintStream other; + + public SilentPrintStream(PrintStream ps) { + super(ps); + other = ps; + } + + public void print(String s) { + } + + public void println(String s) { + } + + public void println(Object x) { + } +} diff --git a/slf4j-site/LICENSE.txt b/slf4j-site/LICENSE.txt index f6e2f31f..508a2728 100644 --- a/slf4j-site/LICENSE.txt +++ b/slf4j-site/LICENSE.txt @@ -1,24 +1,24 @@ -Copyright (c) 2004-2007 QOS.ch -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - - +Copyright (c) 2004-2007 QOS.ch +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + diff --git a/slf4j-site/pom.xml b/slf4j-site/pom.xml index e96eb39f..c17dacdc 100644 --- a/slf4j-site/pom.xml +++ b/slf4j-site/pom.xml @@ -1,60 +1,60 @@ - - - - org.slf4j - slf4j-parent - 1.5.10 - - - 4.0.0 - - org.slf4j - slf4j-site - ${parent.version} - jar - SLF4J Site - - http://www.slf4j.org - - - - - src/site/pages - - ../../../target/site - true - - - - - - - - - org.apache.maven.plugins - maven-site-plugin - - ${project.parent.basedir}/target/site - - - - org.apache.maven.plugins - - maven-project-info-reports-plugin - - - - - - - - - - - + + + + org.slf4j + slf4j-parent + 1.5.10 + + + 4.0.0 + + org.slf4j + slf4j-site + ${parent.version} + jar + SLF4J Site + + http://www.slf4j.org + + + + + src/site/pages + + ../../../target/site + true + + + + + + + + + org.apache.maven.plugins + maven-site-plugin + + ${project.parent.basedir}/target/site + + + + org.apache.maven.plugins + + maven-project-info-reports-plugin + + + + + + + + + + + \ No newline at end of file diff --git a/slf4j-site/src/site/pages/bug-reporting.html b/slf4j-site/src/site/pages/bug-reporting.html index 1f14692c..64cce0de 100644 --- a/slf4j-site/src/site/pages/bug-reporting.html +++ b/slf4j-site/src/site/pages/bug-reporting.html @@ -1,97 +1,97 @@ - - - - - - SLF4J Bug reporting - - - - - - -
- -
-
- - -

Before you report a bug

- -

The SLF4J community consists of those who use SLF4J and its - implementations, help answer questions on discussions lists, - contribute documentation and patches, and those who develop and - maintain the code for SLF4J and its implementations. Almost all - those who assist on a day to day basis resolving bug reports do - this for a wide variety of reasons, and almost all of them do this - on their own time. -

- -

Many bugs reported end up not being a bug in SLF4J, but are due - to misconfiguration, problems caused by installed applications, - the operating system, etc. -

- -

Before reporting a bug please make every effort to resolve the - problem yourself. Just reporting a bug will not fix it. A good - bug report includes a detailed description of the problem and a - succinct test case which can reproduce the problem. -

- -

Review the documentation

- -

Review the documentation for the version of component you are - using. The problem you are having may already be addressed in the - docs. -

- -

Search the mailing list archives

- -

It is very likely you are not the first to run into a problem. - Others may have already found a solution. Our various mailing lists are likely to have - discussed this problem before. -

- -

Search Bugzilla

- -

Please search the bug database to see if the bug you are seeing - has already been reported. The bug may have already been fixed - and is available in a later version. If someone else has reported - the same bug, you could add supporting information to help - reproduce and resolve the bug. -

- - -

Reporting with Bugzilla

- -

Onlly after you have exhausted the aforementioned steps, should - you file a formal report in bugzilla. -

- -

Please make sure you provide as much information as - possible. Its very hard to fix a bug if the person looking into - the problem can't reproduce it. -

- - - - - - - - -
- - + + + + + + SLF4J Bug reporting + + + + + + +
+ +
+
+ + +

Before you report a bug

+ +

The SLF4J community consists of those who use SLF4J and its + implementations, help answer questions on discussions lists, + contribute documentation and patches, and those who develop and + maintain the code for SLF4J and its implementations. Almost all + those who assist on a day to day basis resolving bug reports do + this for a wide variety of reasons, and almost all of them do this + on their own time. +

+ +

Many bugs reported end up not being a bug in SLF4J, but are due + to misconfiguration, problems caused by installed applications, + the operating system, etc. +

+ +

Before reporting a bug please make every effort to resolve the + problem yourself. Just reporting a bug will not fix it. A good + bug report includes a detailed description of the problem and a + succinct test case which can reproduce the problem. +

+ +

Review the documentation

+ +

Review the documentation for the version of component you are + using. The problem you are having may already be addressed in the + docs. +

+ +

Search the mailing list archives

+ +

It is very likely you are not the first to run into a problem. + Others may have already found a solution. Our various mailing lists are likely to have + discussed this problem before. +

+ +

Search Bugzilla

+ +

Please search the bug database to see if the bug you are seeing + has already been reported. The bug may have already been fixed + and is available in a later version. If someone else has reported + the same bug, you could add supporting information to help + reproduce and resolve the bug. +

+ + +

Reporting with Bugzilla

+ +

Onlly after you have exhausted the aforementioned steps, should + you file a formal report in bugzilla. +

+ +

Please make sure you provide as much information as + possible. Its very hard to fix a bug if the person looking into + the problem can't reproduce it. +

+ + + + + + + + +
+ + diff --git a/slf4j-site/src/site/pages/changes/changes-1.3.txt b/slf4j-site/src/site/pages/changes/changes-1.3.txt index 4e9a7112..40797650 100644 --- a/slf4j-site/src/site/pages/changes/changes-1.3.txt +++ b/slf4j-site/src/site/pages/changes/changes-1.3.txt @@ -1,45 +1,45 @@ - -Changes in SLF4J 1.3.0 with respect to 1.2 as reported by the clirr -tool. - -slf4j-api -========= - -INFO: 6000: org.slf4j.Logger: Added public field ROOT_LOGGER_NAME -INFO: 8000: org.slf4j.LoggerFactory: Class org.slf4j.LoggerFactory added -INFO: 8000: org.slf4j.MarkerFactory: Class org.slf4j.MarkerFactory added -INFO: 8000: org.slf4j.helpers.BasicMarker: Class org.slf4j.helpers.BasicMarker added -INFO: 8000: org.slf4j.helpers.BasicMarkerFactory: Class org.slf4j.helpers.BasicMarkerFactory added -INFO: 8000: org.slf4j.helpers.MarkerIgnoringBase: Class org.slf4j.helpers.MarkerIgnoringBase added -INFO: 8000: org.slf4j.helpers.MessageFormatter: Class org.slf4j.helpers.MessageFormatter added -INFO: 8000: org.slf4j.helpers.Util: Class org.slf4j.helpers.Util added -ERROR: 8001: org.slf4j.impl.BasicMarker: Class org.slf4j.impl.BasicMarker removed -ERROR: 8001: org.slf4j.impl.BasicMarkerFactory: Class org.slf4j.impl.BasicMarkerFactory removed -ERROR: 8001: org.slf4j.impl.MarkerIgnoringBase: Class org.slf4j.impl.MarkerIgnoringBase removed -ERROR: 8001: org.slf4j.impl.MessageFormatter: Class org.slf4j.impl.MessageFormatter removed -ERROR: 8001: org.slf4j.impl.Util: Class org.slf4j.impl.Util removed -INFO: 8000: org.slf4j.spi.LocationAwareLogger: Class org.slf4j.spi.LocationAwareLogger added - -slf4j-nop -========= - -ERROR: 8001: org.slf4j.LoggerFactory: Class org.slf4j.LoggerFactory removed -ERROR: 8001: org.slf4j.MarkerFactory: Class org.slf4j.MarkerFactory removed - -slf4j-simple -============ - -ERROR: 8001: org.slf4j.LoggerFactory: Class org.slf4j.LoggerFactory removed -ERROR: 8001: org.slf4j.MarkerFactory: Class org.slf4j.MarkerFactory removed - -slf4j-log4j12 -============= - -ERROR: 8001: org.slf4j.LoggerFactory: Class org.slf4j.LoggerFactory removed -ERROR: 8001: org.slf4j.MarkerFactory: Class org.slf4j.MarkerFactory removed - -slf4j-jdk14 -=========== - -ERROR: 8001: org.slf4j.LoggerFactory: Class org.slf4j.LoggerFactory removed + +Changes in SLF4J 1.3.0 with respect to 1.2 as reported by the clirr +tool. + +slf4j-api +========= + +INFO: 6000: org.slf4j.Logger: Added public field ROOT_LOGGER_NAME +INFO: 8000: org.slf4j.LoggerFactory: Class org.slf4j.LoggerFactory added +INFO: 8000: org.slf4j.MarkerFactory: Class org.slf4j.MarkerFactory added +INFO: 8000: org.slf4j.helpers.BasicMarker: Class org.slf4j.helpers.BasicMarker added +INFO: 8000: org.slf4j.helpers.BasicMarkerFactory: Class org.slf4j.helpers.BasicMarkerFactory added +INFO: 8000: org.slf4j.helpers.MarkerIgnoringBase: Class org.slf4j.helpers.MarkerIgnoringBase added +INFO: 8000: org.slf4j.helpers.MessageFormatter: Class org.slf4j.helpers.MessageFormatter added +INFO: 8000: org.slf4j.helpers.Util: Class org.slf4j.helpers.Util added +ERROR: 8001: org.slf4j.impl.BasicMarker: Class org.slf4j.impl.BasicMarker removed +ERROR: 8001: org.slf4j.impl.BasicMarkerFactory: Class org.slf4j.impl.BasicMarkerFactory removed +ERROR: 8001: org.slf4j.impl.MarkerIgnoringBase: Class org.slf4j.impl.MarkerIgnoringBase removed +ERROR: 8001: org.slf4j.impl.MessageFormatter: Class org.slf4j.impl.MessageFormatter removed +ERROR: 8001: org.slf4j.impl.Util: Class org.slf4j.impl.Util removed +INFO: 8000: org.slf4j.spi.LocationAwareLogger: Class org.slf4j.spi.LocationAwareLogger added + +slf4j-nop +========= + +ERROR: 8001: org.slf4j.LoggerFactory: Class org.slf4j.LoggerFactory removed +ERROR: 8001: org.slf4j.MarkerFactory: Class org.slf4j.MarkerFactory removed + +slf4j-simple +============ + +ERROR: 8001: org.slf4j.LoggerFactory: Class org.slf4j.LoggerFactory removed +ERROR: 8001: org.slf4j.MarkerFactory: Class org.slf4j.MarkerFactory removed + +slf4j-log4j12 +============= + +ERROR: 8001: org.slf4j.LoggerFactory: Class org.slf4j.LoggerFactory removed +ERROR: 8001: org.slf4j.MarkerFactory: Class org.slf4j.MarkerFactory removed + +slf4j-jdk14 +=========== + +ERROR: 8001: org.slf4j.LoggerFactory: Class org.slf4j.LoggerFactory removed ERROR: 8001: org.slf4j.MarkerFactory: Class org.slf4j.MarkerFactory removed \ No newline at end of file diff --git a/slf4j-site/src/site/pages/codes.html b/slf4j-site/src/site/pages/codes.html index e84ba220..2c72e029 100644 --- a/slf4j-site/src/site/pages/codes.html +++ b/slf4j-site/src/site/pages/codes.html @@ -1,281 +1,281 @@ - - - - -SLF4J Error Codes - - - - - - -
- -
- -
- -
-

SLF4J warning or error messages and their meanings

- -
- - -

- - The method - o.a.commons.logging.impl.SLF4FLogFactory#release - was invoked. - -

- -

Given the structure of the commons-logging API, in particular - as implemented by SLF4J, the - o.a.commons.logging.impl.SLF4FLogFactory#release() - method should never be called. However, depending on the - deployment of commons-logging.jar files in your servlet - container, release() method may be unexpectedly - invoked by a copy of - org.apache.commons.logging.LogFactory class shipping - with commons-logging.jar. -

- -

This is a relatively common occurrence with recent versions of - Tomcat, especially if you place jcl-over-slf4j.jar in - WEB-INF/lib directory of your web-application instead of - $TOMCAT_HOME/common/lib, where $TOMCAT_HOME stands for - the directory where Tomcat is installed. In order to fully benefit - from the stability offered by jcl-over-slf4j.jar, we - recommend that you place jcl-over-slf4j.jar in - $TOMCAT_HOME/common/lib without placing a copy in your - web-applications. -

- -

Please also see bug - #22.

- - - -

- - Operation [suchAndSuch] is not supported in jcl-over-slf4j. - -

- -

An UnsuportedOperationException is thrown whenever - one of the protected methods introduced in JCL 1.1 are - invoked. These methods are invoked by LogFactory - implementations shipping with - commons-logging.jar. However, the LogFactory - implemented by jcl-over-slf4j.jar, namely - SLF4FLogFactory, does not call any of these methods. -

- -

If you observe this problem, then it is highly probable that you - have a copy of commons-logging.jar in your class path - overriding the classes shipping with - jcl-over-slf4j.jar. Note that this issue is very similar - in nature to the warning issued when the - "o.a.commons.logging.impl.SLF4FLogFactory.release()" method is - invoked, discussed in the previous item. -

- - - -

- - Failed to load class - org.slf4j.impl.StaticLoggerBinder - -

- -

This error is reported when the - org.slf4j.impl.StaticLoggerBinder class could not be - loaded into memory. This happens when no appropriate SLF4J - binding could be found on the class path. Placing one (and only - one) of slf4j-nop.jar, slf4j-simple.jar, - slf4j-log4j12.jar, slf4j-jdk14.jar or - logback-classic.jar on the class path should solve the - problem. -

- -

You can download SLF4J bindings from the project download page.

- - - - - - -

- Multiple - bindings were found on the class path -

- - -

SLF4J API is desinged to bind with one and only one underlying - logging framework at a time. If more than one binding is present - on the class path, SLF4J will emit a warning, listing the location - of those bindings. When this happens, select the one and only one - binding you wish to use, and remove the other bindings. -

- -

For example, if you have both - slf4j-simple-${version}.jar and - slf4j-nop-${version}.jar on the class path and you wish - to use the nop (no-operation) binding, then remove - slf4j-simple-${version}.jar from the class parh.

- - - -

- Logging factory implementation - cannot be null -

- -

This error is reported when the LoggerFactory - class could not find an appropriate binding. Placing one (and only - one) of slf4j-nop.jar, slf4j-simple.jar, - slf4j-log4j12.jar, slf4j-jdk14.jar or - logback-classic.jar on the class path should prove to be - an effective remedy. -

- - -

- Failed to load class - "org.slf4j.impl.StaticMDCBinder" - -

- -

This error indicates that appropriate SLF4J binding could not - be found on the class path. Placing one (and only one) of - slf4j-nop.jar, slf4j-simple.jar, - slf4j-log4j12.jar, slf4j-jdk14.jar or - logback-classic.jar on the class path should solve the - problem. -

- -

- MDCAdapter cannot be null - -

- -

This error is reported when org.slf4j.MDC class - has not been initialized correctly. Same cause and remedy as the - previously listed item. -

- - -

SLF4J versions - 1.4.0 and later requires log4j 1.2.12 or later

- -

The trace level was added to log4j in version 1.2.12 released - on August 29, 2005. The trace level was added to the SLF4J API in - version 1.4.0 on May 16th, 2007. Thus, starting with SLF4J 1.4.0, - the log4j binding for SLF4J requires log4j version 1.2.12 or - above. -

- -

However, as reported in bug 68, in - some environments it may be difficult to upgrade the log4j - version. To accommodate such circumstances, SLF4J's - Log4jLoggerAdapter will map the TRACE level as - DEBUG.

- - - -

slf4j-api - version does not match that of the binding

- -

Mixing mixing different versions of slf4j artifacts can cause - problems. For example, if you are using slf4j-api-1.5.5.jar, then - you should also use slf4j-simple-1.5.5.jar, using - slf4j-simple-1.4.2.jar will not work. -

- -

In general, you should make sure that the slf4j-api version - matches that of the slf4j binding. -

- -

At initialization time, if SLF4J suspects that there may be a - mismatch problem, it emits a warning about the said mismatch. -

- -

For the exact details of the version mismatch detection - mechanism, please refer to the relevant entry in the FAQ. -

- -

Substitute - loggers were created during the default configuration phase of the - underlying logging system

- -

Highly configurable logging systems such as logback and log4j - may create components which invoke loggers during their own - initialization. See issue lbcore-47 for a - typical occurrence. However, since the binding process with SLF4J - has not yet completed (because the underlying logging system was - not yet completely loaded into memory), it is not possible to - honor such logger creation requests, resulting in a - NullPointerException.

- -

To avoid this chicken-and-egg problem, SLF4J substitutes a - no-operation logger factory during this initialization - phase. However, the substitute loggers returned during this phase - are not operational. They are nop implementations. -

- -

If any substitute logger had to be created, SLF4J will emit a - warning listing such nop loggers. This warning is intended to let - you know that you should not expect any logging output from these - loggers. -

- -

The only way to obtain output from the listed loggers, is to - isolate the components invoking these loggers and to exclude them - from the default configuration. Both logback and log4j allow - multi-step configuration. It follows that the problematic - components should be configured in a second step separate from - default configuration. -

- -

If you are not interested in the output from any of the - substitute loggers, then no action is required on your part.

- - - -
- - + + + + +SLF4J Error Codes + + + + + + +
+ +
+ +
+ +
+

SLF4J warning or error messages and their meanings

+ +
+ + +

+ + The method + o.a.commons.logging.impl.SLF4FLogFactory#release + was invoked. + +

+ +

Given the structure of the commons-logging API, in particular + as implemented by SLF4J, the + o.a.commons.logging.impl.SLF4FLogFactory#release() + method should never be called. However, depending on the + deployment of commons-logging.jar files in your servlet + container, release() method may be unexpectedly + invoked by a copy of + org.apache.commons.logging.LogFactory class shipping + with commons-logging.jar. +

+ +

This is a relatively common occurrence with recent versions of + Tomcat, especially if you place jcl-over-slf4j.jar in + WEB-INF/lib directory of your web-application instead of + $TOMCAT_HOME/common/lib, where $TOMCAT_HOME stands for + the directory where Tomcat is installed. In order to fully benefit + from the stability offered by jcl-over-slf4j.jar, we + recommend that you place jcl-over-slf4j.jar in + $TOMCAT_HOME/common/lib without placing a copy in your + web-applications. +

+ +

Please also see bug + #22.

+ + + +

+ + Operation [suchAndSuch] is not supported in jcl-over-slf4j. + +

+ +

An UnsuportedOperationException is thrown whenever + one of the protected methods introduced in JCL 1.1 are + invoked. These methods are invoked by LogFactory + implementations shipping with + commons-logging.jar. However, the LogFactory + implemented by jcl-over-slf4j.jar, namely + SLF4FLogFactory, does not call any of these methods. +

+ +

If you observe this problem, then it is highly probable that you + have a copy of commons-logging.jar in your class path + overriding the classes shipping with + jcl-over-slf4j.jar. Note that this issue is very similar + in nature to the warning issued when the + "o.a.commons.logging.impl.SLF4FLogFactory.release()" method is + invoked, discussed in the previous item. +

+ + + +

+ + Failed to load class + org.slf4j.impl.StaticLoggerBinder + +

+ +

This error is reported when the + org.slf4j.impl.StaticLoggerBinder class could not be + loaded into memory. This happens when no appropriate SLF4J + binding could be found on the class path. Placing one (and only + one) of slf4j-nop.jar, slf4j-simple.jar, + slf4j-log4j12.jar, slf4j-jdk14.jar or + logback-classic.jar on the class path should solve the + problem. +

+ +

You can download SLF4J bindings from the project download page.

+ + + + + + +

+ Multiple + bindings were found on the class path +

+ + +

SLF4J API is desinged to bind with one and only one underlying + logging framework at a time. If more than one binding is present + on the class path, SLF4J will emit a warning, listing the location + of those bindings. When this happens, select the one and only one + binding you wish to use, and remove the other bindings. +

+ +

For example, if you have both + slf4j-simple-${version}.jar and + slf4j-nop-${version}.jar on the class path and you wish + to use the nop (no-operation) binding, then remove + slf4j-simple-${version}.jar from the class parh.

+ + + +

+ Logging factory implementation + cannot be null +

+ +

This error is reported when the LoggerFactory + class could not find an appropriate binding. Placing one (and only + one) of slf4j-nop.jar, slf4j-simple.jar, + slf4j-log4j12.jar, slf4j-jdk14.jar or + logback-classic.jar on the class path should prove to be + an effective remedy. +

+ + +

+ Failed to load class + "org.slf4j.impl.StaticMDCBinder" + +

+ +

This error indicates that appropriate SLF4J binding could not + be found on the class path. Placing one (and only one) of + slf4j-nop.jar, slf4j-simple.jar, + slf4j-log4j12.jar, slf4j-jdk14.jar or + logback-classic.jar on the class path should solve the + problem. +

+ +

+ MDCAdapter cannot be null + +

+ +

This error is reported when org.slf4j.MDC class + has not been initialized correctly. Same cause and remedy as the + previously listed item. +

+ + +

SLF4J versions + 1.4.0 and later requires log4j 1.2.12 or later

+ +

The trace level was added to log4j in version 1.2.12 released + on August 29, 2005. The trace level was added to the SLF4J API in + version 1.4.0 on May 16th, 2007. Thus, starting with SLF4J 1.4.0, + the log4j binding for SLF4J requires log4j version 1.2.12 or + above. +

+ +

However, as reported in bug 68, in + some environments it may be difficult to upgrade the log4j + version. To accommodate such circumstances, SLF4J's + Log4jLoggerAdapter will map the TRACE level as + DEBUG.

+ + + +

slf4j-api + version does not match that of the binding

+ +

Mixing mixing different versions of slf4j artifacts can cause + problems. For example, if you are using slf4j-api-1.5.5.jar, then + you should also use slf4j-simple-1.5.5.jar, using + slf4j-simple-1.4.2.jar will not work. +

+ +

In general, you should make sure that the slf4j-api version + matches that of the slf4j binding. +

+ +

At initialization time, if SLF4J suspects that there may be a + mismatch problem, it emits a warning about the said mismatch. +

+ +

For the exact details of the version mismatch detection + mechanism, please refer to the relevant entry in the FAQ. +

+ +

Substitute + loggers were created during the default configuration phase of the + underlying logging system

+ +

Highly configurable logging systems such as logback and log4j + may create components which invoke loggers during their own + initialization. See issue lbcore-47 for a + typical occurrence. However, since the binding process with SLF4J + has not yet completed (because the underlying logging system was + not yet completely loaded into memory), it is not possible to + honor such logger creation requests, resulting in a + NullPointerException.

+ +

To avoid this chicken-and-egg problem, SLF4J substitutes a + no-operation logger factory during this initialization + phase. However, the substitute loggers returned during this phase + are not operational. They are nop implementations. +

+ +

If any substitute logger had to be created, SLF4J will emit a + warning listing such nop loggers. This warning is intended to let + you know that you should not expect any logging output from these + loggers. +

+ +

The only way to obtain output from the listed loggers, is to + isolate the components invoking these loggers and to exclude them + from the default configuration. Both logback and log4j allow + multi-step configuration. It follows that the problematic + components should be configured in a second step separate from + default configuration. +

+ +

If you are not interested in the output from any of the + substitute loggers, then no action is required on your part.

+ + + +
+ + \ No newline at end of file diff --git a/slf4j-site/src/site/pages/compatibility.html b/slf4j-site/src/site/pages/compatibility.html index cc3f6b54..1af10ea4 100644 --- a/slf4j-site/src/site/pages/compatibility.html +++ b/slf4j-site/src/site/pages/compatibility.html @@ -1,269 +1,269 @@ - - - - - -Compatibility report - - - - - - -
- -
- -
- - -

Compatibility report

- -

Given the very large user base of SLF4J, we take backward - compatibility very seriously. As such, changes that may cause - incompatibility problems are listed in this page. Moreover, since - slf4j-api.jar is the main entry point into SLF4J, that is the module - that will be covered in most detail. -

- -

Please note that in many cases incompatibility problems are - caused by mixing different versions of slf4j artifacts. For example, - if you are using slf4j-api-1.5.4.jar you should also use - slf4j-simple-1.5.4.jar, using slf4j-simple-1.4.2.jar will not - work. The same goes for all other SLF4J artifacts. -

- -

The list is computed using clirr. If you have reasons - to suspect incompatible changes not mentioned here, please kindly - contact the slf4j developers list.

- -

Version 1.5.7 compared to 1.5.6

- -

No breaking changes to report.

- -

Version 1.5.6 compared to 1.5.5

- - - - - - - - - - - - - - - -
SeverityDescriptionClassMethod / Field
ErrorThe number of parameters of SubstituteLoggerFactory - constructor has changedorg.slf4j.helpers.SubstituteLoggerFactorypublic SubstituteLoggerFactory(java.util.List)
- -

 

- -

The SubstituteLoggerFactory class is used internally - by the LoggerFactory class. Changes to the constructor of - SubstituteLoggerFactory should have stricly no affect on users. -

- -

Version 1.5.5 compared to 1.5.4

- -

No breaking changes to report.

- -

Version 1.5.4 compared to 1.5.3

- -

slf4j-api module, list of breaking changes:

- - - - - - - - - - - - - - - - - - - - - - -
SeverityDescriptionClassMethod / Field
ErrorMethod 'hasReferences()' has been added to an interfaceorg.slf4j.Markerpublic boolean hasReferences()
InfoMethod 'hasChildren()' was deprecatedorg.slf4j.Markerpublic boolean hasChildren()
- -

 

- -

The hasChildren() and other documentation in the - Marker interface was misleading users to think in terms of parent - child relationship for markers. However, as bug 100 - illustrates, associating markers as parents and children is not very - helpful. It is much better to think of markers in terms of abstract - graphs. As such, we now say that a marker contains (zero or more) - references to other markers. -

- -

This breaking change is justified because it corrects a - conceptual error in the design. Previously, it was all too easy for - developers to get confused and incorrectly link markers - together.

- -

Version 1.5.3 compared to 1.5.2

- -

slf4j-api module, list of breaking changes:

- - - - - - - - - - - - - - - -
SeverityDescriptionClassMethod / Field
ErrorAdded final modifier to classorg.slf4j.helpers.MessageFormatter
- -

Declaring MessageFormatter class as final should not - affect users, unless they extend this class. However, since this - class is intended to be used internally, very few users should be - affected. -

- -

Version 1.5.2 compared to 1.5.1

- -

No breaking changes to report.

- -

Version 1.5.1 compared to 1.5.0

- - -

slf4j-api module, list of breaking changes:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeverityDescriptionClassMethod / Field
ErrorMethod 'getCopyOfContextMap()' has been added to an - interface - org.slf4j.spi.MDCAdapterpublic java.util.Map getCopyOfContextMap()
ErrorMethod 'setContextMap(Map)' has been added to an - interface - org.slf4j.spi.MDCAdapterpublic void setContextMap(java.util.Map)
ErrorMethod 'getDetachedMarker(String)' has been added to an - interface - org.slf4j.IMarkerFactorypublic org.slf4j.Marker getDetachedMarker(java.lang.String)
InfoMethod 'equals(Object)' has been added to an - interface - org.slf4j.Markerpublic boolean equals(java.lang.Object)
infoMethod 'hashCode()' has been added to an - interface - org.slf4j.Markerpublic int hashCode()
- -

The addition of the getCopyOfContextMap() method in - the MDCAdapter class should only impact users who have - their own implementation of the said interface. Except for bindings - that ship with SLF4J and for logback-classic, which will be - naturally upgraded, there are no known other implementations of - MDCAdapter. In a rare but still possible scenario, if - the user mixes different versions for slf4j-api.jar, say version - 1.5.1. and an SLF4J binding, say slf4j-log4j12.jar version 1.5.0, - then a java.lang.AbstractMethodError will be thrown, - but only if the client code calls the newly added method. In short, although generally speaking the - addition of a method to an interface is a breaking change, we are - confident that no users will be impacted in this particular - case. -

- -

Similar reasoning applies to the setContextMap(Map) - method.

- -

The addition of getDetachedMarker(String) method in - the org.slf4j.IMarkerFactory should not impact users as - the only (known) implementation of this interface ships with SLF4J - itself. -

- -

The equals() and hashCode() methods - were added to the org.slf4j.Marker interface for - documentation purposes. Given that all objects implicitly implement - these methods, their addition should theoretically not break - existing code.

- - -

Other modules

- -

No breaking changes to report.

- - - -

Version 1.5.0 compared to - 1.4.3

- -

No breaking changes to report.

- - -

Version 1.4.3 compared to - 1.4.2

-

No breaking changes to report.

- - -

Version 1.4.2 compared to 1.4.1

-

No breaking changes to report.

- - -

Version 1.4.1 compared to - 1.4.0

-

No breaking changes to report.

- + + + + + +Compatibility report + + + + + + +
+ +
+ +
+ + +

Compatibility report

+ +

Given the very large user base of SLF4J, we take backward + compatibility very seriously. As such, changes that may cause + incompatibility problems are listed in this page. Moreover, since + slf4j-api.jar is the main entry point into SLF4J, that is the module + that will be covered in most detail. +

+ +

Please note that in many cases incompatibility problems are + caused by mixing different versions of slf4j artifacts. For example, + if you are using slf4j-api-1.5.4.jar you should also use + slf4j-simple-1.5.4.jar, using slf4j-simple-1.4.2.jar will not + work. The same goes for all other SLF4J artifacts. +

+ +

The list is computed using clirr. If you have reasons + to suspect incompatible changes not mentioned here, please kindly + contact the slf4j developers list.

+ +

Version 1.5.7 compared to 1.5.6

+ +

No breaking changes to report.

+ +

Version 1.5.6 compared to 1.5.5

+ + + + + + + + + + + + + + + +
SeverityDescriptionClassMethod / Field
ErrorThe number of parameters of SubstituteLoggerFactory + constructor has changedorg.slf4j.helpers.SubstituteLoggerFactorypublic SubstituteLoggerFactory(java.util.List)
+ +

 

+ +

The SubstituteLoggerFactory class is used internally + by the LoggerFactory class. Changes to the constructor of + SubstituteLoggerFactory should have stricly no affect on users. +

+ +

Version 1.5.5 compared to 1.5.4

+ +

No breaking changes to report.

+ +

Version 1.5.4 compared to 1.5.3

+ +

slf4j-api module, list of breaking changes:

+ + + + + + + + + + + + + + + + + + + + + + +
SeverityDescriptionClassMethod / Field
ErrorMethod 'hasReferences()' has been added to an interfaceorg.slf4j.Markerpublic boolean hasReferences()
InfoMethod 'hasChildren()' was deprecatedorg.slf4j.Markerpublic boolean hasChildren()
+ +

 

+ +

The hasChildren() and other documentation in the + Marker interface was misleading users to think in terms of parent + child relationship for markers. However, as bug 100 + illustrates, associating markers as parents and children is not very + helpful. It is much better to think of markers in terms of abstract + graphs. As such, we now say that a marker contains (zero or more) + references to other markers. +

+ +

This breaking change is justified because it corrects a + conceptual error in the design. Previously, it was all too easy for + developers to get confused and incorrectly link markers + together.

+ +

Version 1.5.3 compared to 1.5.2

+ +

slf4j-api module, list of breaking changes:

+ + + + + + + + + + + + + + + +
SeverityDescriptionClassMethod / Field
ErrorAdded final modifier to classorg.slf4j.helpers.MessageFormatter
+ +

Declaring MessageFormatter class as final should not + affect users, unless they extend this class. However, since this + class is intended to be used internally, very few users should be + affected. +

+ +

Version 1.5.2 compared to 1.5.1

+ +

No breaking changes to report.

+ +

Version 1.5.1 compared to 1.5.0

+ + +

slf4j-api module, list of breaking changes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SeverityDescriptionClassMethod / Field
ErrorMethod 'getCopyOfContextMap()' has been added to an + interface + org.slf4j.spi.MDCAdapterpublic java.util.Map getCopyOfContextMap()
ErrorMethod 'setContextMap(Map)' has been added to an + interface + org.slf4j.spi.MDCAdapterpublic void setContextMap(java.util.Map)
ErrorMethod 'getDetachedMarker(String)' has been added to an + interface + org.slf4j.IMarkerFactorypublic org.slf4j.Marker getDetachedMarker(java.lang.String)
InfoMethod 'equals(Object)' has been added to an + interface + org.slf4j.Markerpublic boolean equals(java.lang.Object)
infoMethod 'hashCode()' has been added to an + interface + org.slf4j.Markerpublic int hashCode()
+ +

The addition of the getCopyOfContextMap() method in + the MDCAdapter class should only impact users who have + their own implementation of the said interface. Except for bindings + that ship with SLF4J and for logback-classic, which will be + naturally upgraded, there are no known other implementations of + MDCAdapter. In a rare but still possible scenario, if + the user mixes different versions for slf4j-api.jar, say version + 1.5.1. and an SLF4J binding, say slf4j-log4j12.jar version 1.5.0, + then a java.lang.AbstractMethodError will be thrown, + but only if the client code calls the newly added method. In short, although generally speaking the + addition of a method to an interface is a breaking change, we are + confident that no users will be impacted in this particular + case. +

+ +

Similar reasoning applies to the setContextMap(Map) + method.

+ +

The addition of getDetachedMarker(String) method in + the org.slf4j.IMarkerFactory should not impact users as + the only (known) implementation of this interface ships with SLF4J + itself. +

+ +

The equals() and hashCode() methods + were added to the org.slf4j.Marker interface for + documentation purposes. Given that all objects implicitly implement + these methods, their addition should theoretically not break + existing code.

+ + +

Other modules

+ +

No breaking changes to report.

+ + + +

Version 1.5.0 compared to + 1.4.3

+ +

No breaking changes to report.

+ + +

Version 1.4.3 compared to + 1.4.2

+

No breaking changes to report.

+ + +

Version 1.4.2 compared to 1.4.1

+

No breaking changes to report.

+ + +

Version 1.4.1 compared to + 1.4.0

+

No breaking changes to report.

+
\ No newline at end of file diff --git a/slf4j-site/src/site/pages/css/prettify.css b/slf4j-site/src/site/pages/css/prettify.css index 35cad277..65cfc419 100644 --- a/slf4j-site/src/site/pages/css/prettify.css +++ b/slf4j-site/src/site/pages/css/prettify.css @@ -1,28 +1,28 @@ -.str{color:#080} -.kwd{color:#008} -.com{color:#800} -.typ{color:#606} -.lit{color:#066} -.pun{color:#660} -.pln{color:#000} -.tag{color:#008} -.atn{color:#606} -.atv{color:#080} -.dec{color:#606} - -pre.prettyprint{ - padding:2px; -} -@media print{.str{color:#060} - -.kwd{ - color:#006;font-weight:bold} - .com{color:#600;font-style:italic -} -.typ{color:#404;font-weight:bold} -.lit{color:#044} -.pun{color:#440} -.pln{color:#000} -.tag{color:#006;font-weight:bold} -.atn{color:#404} +.str{color:#080} +.kwd{color:#008} +.com{color:#800} +.typ{color:#606} +.lit{color:#066} +.pun{color:#660} +.pln{color:#000} +.tag{color:#008} +.atn{color:#606} +.atv{color:#080} +.dec{color:#606} + +pre.prettyprint{ + padding:2px; +} +@media print{.str{color:#060} + +.kwd{ + color:#006;font-weight:bold} + .com{color:#600;font-style:italic +} +.typ{color:#404;font-weight:bold} +.lit{color:#044} +.pun{color:#440} +.pln{color:#000} +.tag{color:#006;font-weight:bold} +.atn{color:#404} .atv{color:#060}} \ No newline at end of file diff --git a/slf4j-site/src/site/pages/css/site.css b/slf4j-site/src/site/pages/css/site.css index 36d1f007..9208a75a 100644 --- a/slf4j-site/src/site/pages/css/site.css +++ b/slf4j-site/src/site/pages/css/site.css @@ -1,297 +1,297 @@ -html { - padding:0px; - margin:0px; -} - -body { - background-color: #fff; - font-family: Verdana, Arial, SunSans-Regular, Sans-Serif; - color: #000; - padding:0px; - margin:0px; - font-size: small; -} - -p, h2, pre { - margin: 0px; - padding-top: 5px; - padding-bottom: 5px; - /*padding-left: 1ex;*/ - /*padding: 5px 20px 5px 20px; */ -} - -p.rm { - padding-top: 0px; - padding-bottom: 0px; -} - -a { - color: #0000CC; - /*font-size: smaller;*/ - background-color:transparent; - text-decoration: none; -} - -#content a:hover { - text-decoration: underline; -} - -.source { - border-top: 1px solid #DDDDDD; - border-bottom: 1px solid #DDDDDD; - background:#eee; - font-family: Courier, "MS Courier New", Prestige, Everson Monocourrier, monospace; - padding-bottom: 0.5ex; - padding-top: 0.5ex; - padding-left: 1ex; - - margin-left: 0ex; - margin-top: 0.5ex; - margin-bottom: 0.5ex; - white-space: pre; -} - -pre { - background-color:transparent; - font-family: Courier, Monaco, Monospace; -} - -.alignright { - margin-top: 0; - text-align: right; - font-size: 10px; -} - -h1, h2, h3, h4 { - color: #333; -} - -h2 { - padding-top:10px; - background-color: transparent; - font-weight: 900; - font-size: x-large; -} - -h3 { - padding-top:10px; - background-color: transparent; - font-weight: normal; - font-size: large; -} - -h4 { - padding-top:5px; - background-color: transparent; - font-weight: normal; - font-size: large; -} - -table.footer { - width: 100%; -} - -.footer { - text-align: right; - color: #564b47; - background-color: #fff; - padding:0px; - border-top: 1px solid #CCCCCC; - margin-top: 3ex; - font-size: smaller; -} - - -strong { - /*font-size: 13px;*/ - font-weight: bold; -} - -/* positioning-layers static and absolute */ - -#breadcrumbs { - padding: 3px 10px 3px 10px; - margin: 0px 4px 0px 4px; - font-size: small; - border: 1px solid #CCCCCC; - /*border-bottom: 1px solid #aaa; - /* background-color: #ccc; lime; - border-color: #663300;*/ - background-color: #ffd0a0; - /*max-width: 77em;*/ -} - -#left { - position: absolute; - left: 0px; - width: 15em; - margin: 4px 0px 0px 4px; - padding: 0px; - font-size: 80%; - background-color: #ffffff; -} - -.menuGroup { - border: 1px solid #cccccc; - background-color: #ffffff; - color: #564b47; - border: 1px solid #cccccc; -} - -.menuGroup a { - display: block; - width: 95.5%; - margin: 0px; - padding: 2px; - border: solid 1px #FFFFFF; - color: #0066cc; - text-decoration: none; -} - -.menuGroup a:hover { - border: solid 1px #FFFFFF; - background-color: #3333CC; - color: #ffffff; -} - -.pub { - text-align: center; -} - - -p.menu_header { - margin: 0px; - padding: 2px; - font-weight: normal; - background-color: #ffd0a0; - border-top: solid 1px #CCCCCC; - border-bottom: solid 1px #CCCCCC; -} - -#content { - margin: 0px 12em 0px 16em; - padding: 0px; - background-color: #ffffff; -} - - -#content img { - border:none; - margin-left: auto; - margin-right: auto; - display: block; -} - -.author { - text-align: left; - font-weight: bold; -} - -.definition { - padding-left: 5px; - padding-right: 5px; - margin: 5px 50px 5px 50px; - text-align: justify; - background-color: #E6E64C; -} - -.deftitle { - font-weight: bold; -} - -.big { - font-size: 130%; -} - -.green { - color: green; -} -.blue { - color: blue; -} - -.red { - color: red; -} - -.bold { - font-weight: bold; -} - -.redBold { - color: red; - font-weight: bold; -} -.greenBold { - color: green; - font-weight: bold; -} - -code { - font-family: Courier, monospace; -} - - -.option { - border: 1px solid black; - font-family: Arial, sans-serif; -} - -.highlight { - width: 300px; - float: right; - display: inline; - font-weight: bolder; - border:1px solid #000; - background:#FFCC99; - padding-top: 0px; - padding-left: 1ex; - padding-right: 1ex; - margin-left: 3em; - margin-right: 3em; -} - - -/* ========== body table ============ */ -table.bodyTable { - padding: 0px; - margin-left: -2px; - margin-right: -2px; -} - -table.bodyTable th { - color: white; - background-color: #bbb; - font-weight: bold; -} - - -table.bodyTable td { - padding-left: 0.5ex; - padding-bottom: 0.5ex; -} - - -/* apply to tr elements of tables which are both bodytable and dark */ -table[class="bodyTable dark"] tr { - background-color: #ddd; -} - -/* apply to tr elements of tables which are both bodytable and dark */ -table[class="bodyTable properties"] tr { - vertical-align: top; -} - -table.bodyTable tr.a { - background-color: #ddd; -} - -table.bodyTable tr.b { - background-color: #eee; -} - -table.bodyTable tr.alt { - background-color: #eee; -} - -/* EOF =============== bodyTable =============== */ +html { + padding:0px; + margin:0px; +} + +body { + background-color: #fff; + font-family: Verdana, Arial, SunSans-Regular, Sans-Serif; + color: #000; + padding:0px; + margin:0px; + font-size: small; +} + +p, h2, pre { + margin: 0px; + padding-top: 5px; + padding-bottom: 5px; + /*padding-left: 1ex;*/ + /*padding: 5px 20px 5px 20px; */ +} + +p.rm { + padding-top: 0px; + padding-bottom: 0px; +} + +a { + color: #0000CC; + /*font-size: smaller;*/ + background-color:transparent; + text-decoration: none; +} + +#content a:hover { + text-decoration: underline; +} + +.source { + border-top: 1px solid #DDDDDD; + border-bottom: 1px solid #DDDDDD; + background:#eee; + font-family: Courier, "MS Courier New", Prestige, Everson Monocourrier, monospace; + padding-bottom: 0.5ex; + padding-top: 0.5ex; + padding-left: 1ex; + + margin-left: 0ex; + margin-top: 0.5ex; + margin-bottom: 0.5ex; + white-space: pre; +} + +pre { + background-color:transparent; + font-family: Courier, Monaco, Monospace; +} + +.alignright { + margin-top: 0; + text-align: right; + font-size: 10px; +} + +h1, h2, h3, h4 { + color: #333; +} + +h2 { + padding-top:10px; + background-color: transparent; + font-weight: 900; + font-size: x-large; +} + +h3 { + padding-top:10px; + background-color: transparent; + font-weight: normal; + font-size: large; +} + +h4 { + padding-top:5px; + background-color: transparent; + font-weight: normal; + font-size: large; +} + +table.footer { + width: 100%; +} + +.footer { + text-align: right; + color: #564b47; + background-color: #fff; + padding:0px; + border-top: 1px solid #CCCCCC; + margin-top: 3ex; + font-size: smaller; +} + + +strong { + /*font-size: 13px;*/ + font-weight: bold; +} + +/* positioning-layers static and absolute */ + +#breadcrumbs { + padding: 3px 10px 3px 10px; + margin: 0px 4px 0px 4px; + font-size: small; + border: 1px solid #CCCCCC; + /*border-bottom: 1px solid #aaa; + /* background-color: #ccc; lime; + border-color: #663300;*/ + background-color: #ffd0a0; + /*max-width: 77em;*/ +} + +#left { + position: absolute; + left: 0px; + width: 15em; + margin: 4px 0px 0px 4px; + padding: 0px; + font-size: 80%; + background-color: #ffffff; +} + +.menuGroup { + border: 1px solid #cccccc; + background-color: #ffffff; + color: #564b47; + border: 1px solid #cccccc; +} + +.menuGroup a { + display: block; + width: 95.5%; + margin: 0px; + padding: 2px; + border: solid 1px #FFFFFF; + color: #0066cc; + text-decoration: none; +} + +.menuGroup a:hover { + border: solid 1px #FFFFFF; + background-color: #3333CC; + color: #ffffff; +} + +.pub { + text-align: center; +} + + +p.menu_header { + margin: 0px; + padding: 2px; + font-weight: normal; + background-color: #ffd0a0; + border-top: solid 1px #CCCCCC; + border-bottom: solid 1px #CCCCCC; +} + +#content { + margin: 0px 12em 0px 16em; + padding: 0px; + background-color: #ffffff; +} + + +#content img { + border:none; + margin-left: auto; + margin-right: auto; + display: block; +} + +.author { + text-align: left; + font-weight: bold; +} + +.definition { + padding-left: 5px; + padding-right: 5px; + margin: 5px 50px 5px 50px; + text-align: justify; + background-color: #E6E64C; +} + +.deftitle { + font-weight: bold; +} + +.big { + font-size: 130%; +} + +.green { + color: green; +} +.blue { + color: blue; +} + +.red { + color: red; +} + +.bold { + font-weight: bold; +} + +.redBold { + color: red; + font-weight: bold; +} +.greenBold { + color: green; + font-weight: bold; +} + +code { + font-family: Courier, monospace; +} + + +.option { + border: 1px solid black; + font-family: Arial, sans-serif; +} + +.highlight { + width: 300px; + float: right; + display: inline; + font-weight: bolder; + border:1px solid #000; + background:#FFCC99; + padding-top: 0px; + padding-left: 1ex; + padding-right: 1ex; + margin-left: 3em; + margin-right: 3em; +} + + +/* ========== body table ============ */ +table.bodyTable { + padding: 0px; + margin-left: -2px; + margin-right: -2px; +} + +table.bodyTable th { + color: white; + background-color: #bbb; + font-weight: bold; +} + + +table.bodyTable td { + padding-left: 0.5ex; + padding-bottom: 0.5ex; +} + + +/* apply to tr elements of tables which are both bodytable and dark */ +table[class="bodyTable dark"] tr { + background-color: #ddd; +} + +/* apply to tr elements of tables which are both bodytable and dark */ +table[class="bodyTable properties"] tr { + vertical-align: top; +} + +table.bodyTable tr.a { + background-color: #ddd; +} + +table.bodyTable tr.b { + background-color: #eee; +} + +table.bodyTable tr.alt { + background-color: #eee; +} + +/* EOF =============== bodyTable =============== */ diff --git a/slf4j-site/src/site/pages/docs.html b/slf4j-site/src/site/pages/docs.html index c7d4eb96..c9f26661 100644 --- a/slf4j-site/src/site/pages/docs.html +++ b/slf4j-site/src/site/pages/docs.html @@ -1,136 +1,136 @@ - - - - - - SLF4J Documentation - - - - - - -
- - -
-
- -

Documentation

- -

Given the small size of SLF4J, its documentation is not very - lengthy.

- - - -

Articles

- - - - - -

In french

- - - -

Conferences

- - - - - - - - - - -
- Jazoon, June 22-25, 2009 Zurich
- - Jazoon 2009 - -
- Devoxx, November 16-20, 2009 Antwerp
- - Devoxx 2009 - -
- - - - - -
- - + + + + + + SLF4J Documentation + + + + + + +
+ + +
+
+ +

Documentation

+ +

Given the small size of SLF4J, its documentation is not very + lengthy.

+ + + +

Articles

+ + + + + +

In french

+ + + +

Conferences

+ + + + + + + + + + +
+ Jazoon, June 22-25, 2009 Zurich
+ + Jazoon 2009 + +
+ Devoxx, November 16-20, 2009 Antwerp
+ + Devoxx 2009 + +
+ + + + + +
+ + diff --git a/slf4j-site/src/site/pages/faq.html b/slf4j-site/src/site/pages/faq.html index 55cf6da0..7e1223c4 100644 --- a/slf4j-site/src/site/pages/faq.html +++ b/slf4j-site/src/site/pages/faq.html @@ -1,1341 +1,1341 @@ - - - - - - SLF4J FAQ - - - - - - - - - -
- -
- -
- -

Frequently Asked Questions about SLF4J

- -

Generalities

- -
    -
  1. What is SLF4J?
  2. - -
  3. When should SLF4J be used?
  4. - -
  5. Is SLF4J yet another loggingfacade?
  6. - -
  7. If SLF4J fixes JCL, then why - wasn't the fix made in JCL instead of creating a new project? - -
  8. - -
  9. When using SLF4J, do I have to - recompile my application to switch to a different logging - system? - -
  10. - -
  11. What are SLF4J's requirements?
  12. - -
  13. Are SLF4J versions backward - compatible?
  14. - -
  15. I am getting - IllegalAccessError exceptions when using SLF4J. Why - is that?
  16. - - -
  17. - Why is SLF4J licensed under X11 type - license instead of the Apache Software License? - -
  18. - -
  19. - Where can I get a particular - SLF4J binding? - -
  20. - -
  21. - Should my library attempt to - configure logging? - -
  22. - -
  23. - What about Maven 2 transitive - dependencies? - -
  24. - -
  25. - How do I exclude commons-logging as a - Maven dependency? - -
  26. -
- - - About the SLF4J API - -
    - -
  1. - Why don't the printing methods - in the Logger interface accept message of type Object, but only - messages of type String? - -
  2. - -
  3. - - Can I log an exception without an accompanying message? - -
  4. - - -
  5. - What is the fastest way of - (not) logging? - -
  6. - -
  7. - How can I log the string contents - of a single (possibly complex) object? - -
  8. - - -
  9. Why doesn't the - org.slf4j.Logger interface have methods for the - FATAL level?
  10. - -
  11. Why was the TRACE level introduced only in - SLF4J version 1.4.0?
  12. - -
  13. Does the SLF4J logging API support I18N - (internationalization)?
  14. - - -
  15. Is it possible to retrieve loggers - without going through the static methods in - LoggerFactory?
  16. - - -
- - - - Implementing the SLF4J API - -
    - -
  1. How do I make my logging - framework SLF4J compatible?
  2. - -
  3. How can my logging system add - support for the Marker interface?
  4. - -
  5. How does SLF4J's version check - mechanism work?
  6. - - -
- - - General questions about logging - - -
    - -
  1. Should Logger members of a class - be declared as static?
  2. - - -
  3. Is there a recommended idiom - for declaring a loggers in a class?
  4. - -
- -

Generalities

- -
-
What is SLF4J?
-
-

SLF4J is a simple facade for logging systems allowing the - end-user to plug-in the desired logging system at deployment - time. -

- -
-
- -
When should SLF4J be used? -
- -
-

In short, libraries and other embedded components should - consider SLF4J for their logging needs because libraries - cannot afford to impose their choice of logging system on the - end-user. On the other hand, it does not necessarily make - sense for stand-alone applications to use SLF4J. Stand-alone - applications can invoke the logging system of their choice - directly. -

- -

SLF4J is only a facade, meaning that it does not provide a - complete logging solution. Operations such as configuring - appenders or setting logging levels cannot be performed with - SLF4J. Thus, at some point in time, any non-trivial - application will need to directly invoke the underlying - logging system. In other words, complete independence from the - API underlying logging system is not possible for a - stand-alone application. Nevertheless, SLF4J reduces the - impact of this dependence to near-painless levels. -

- -

Suppose that your CRM application uses log4j for its - logging. However, one of your important clients request that - logging be performed through JDK 1.4 logging. If your - application is riddled with thousands of direct log4j calls, - migration to JDK 1.4 would be a relatively lengthy and - error-prone process. Even worse, you would potentially need to - maintain two versions of your CRM software. Had you been - invoking SLF4J API instead of log4j, the migration could be - completed in a matter of minutes by replacing one jar file with - another. -

- -

SLF4J lets component developers to defer the choice of the - logging system to the end-user but eventually a choice needs - to be made. -

- -
- -
- -
- - Is SLF4J yet another logging facade? -
- -
-

SLF4J is conceptually very similar to JCL. As such, it can - be thought of as yet another logging facade. However, SLF4J is - much simpler in design and arguably more robust. In a - nutshell, SLF4J avoid the class loader issues that plague JCL. -

- -
- -
-
- - If SLF4J fixes JCL, then why wasn't the fix made in JCL - instead of creating a new project? - -
- -
-

This is a very good question. First, SLF4J static binding - approach is very simple, perhaps even laughably so. It was - not easy to convince developers of the validity of that - approach. It is only after SLF4J was released and started to - become accepted did it gain respectability in the relevant - community. -

- -

Second, SLF4J offers two enhancements which tend to be - underestimated. Parameterized log messages solve an important - problem associated with logging performance, in a pragmatic - way. Marker objects, which are supported by the - org.slf4j.Logger interface, pave the way for - adoption of advanced logging systems and still leave the door - open to switching back to more traditional logging systems if - need be. -

- -
-
- -
- When - using SLF4J, do I have to recompile my application to switch - to a different logging system? -
- -
-

No, you do not need to recompile your application. You can - switch to a different logging system by removing the previous - SLF4J binding and replacing it with the binding of your choice. -

- -

For example, if you were using the NOP implementation and - would like to switch to log4j version 1.2, simply replace - slf4j-nop.jar with slf4j-log4j12.jar on - your class path but do not forget to add log4j-1.2.x.jar as - well. Want to switch to JDK 1.4 logging? Just replace - slf4j-log4j12.jar with slf4j-jdk14.jar. -

- -
-
-
- What are SLF4J's - requirements? -
- -
- -

In principle, SLF4J requires JDK 1.3 or above, in - particular slf4j-api is compatible with JDK 1.3. However, - the underlying logging system might have a higher - requirement. For instance, the slf4j-jdk14 binding - requires JDK 1.4. Logback requires JDK 1.5. -

- -

 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
BindingRequirements
slf4j-nopJDK 1.3
slf4j-simpleJDK 1.3
slf4j-log4j12JDK 1.3, plus any other library - dependencies required by the log4j appenders in use
slf4j-jdk14JDK 1.4 or above
logback-classicJDK 1.5 or above, plus any other library dependencies - required by the logback appenders in use
- -
-
- - - -
Are SLF4J - versions backward compatible? -
- -
-

With rare theoretical exceptions, SLF4J versions are backward - compatible. This means than you can upgrade from SLF4J version - 1.0 to any later version without problems.

- -

However, while the SLF4J API is very stable from the client's - perspective, SLF4J bindings such as slf4j-simple or - slf4j-log4j12 may require a specific version of slf4j-api. Mixing different versions of slf4j artifacts can - be problematic and is strongly discouraged. For - instance, if you are using slf4j-api-1.5.6.jar, then you should - also use slf4j-simple-1.5.6.jar, using slf4j-simple-1.4.2.jar - will not work. -

- -

At initialization time, if SLF4J suspects that there may be a - version mismatch problem, it emits a warning about the said - mismatch. For the exact details of the version mismatch - detection mechanism, please refer to the relevant entry in this FAQ. -

- -
-
- - - -
I am getting - IllegalAccessError exceptions when using SLF4J. Why - is that? -
- -
- -

Here are the exception details.

- -
Exception in thread "main" java.lang.IllegalAccessError: tried to access field
-org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory
-   at org.slf4j.LoggerFactory.<clinit>(LoggerFactory.java:60)
- -

This error is caused by the static initilizer of the - LoggerFactory class attempting to directly access - the SINGLETON field of - org.slf4j.impl.StaticLoggerBinder. While this was - allowed in SLF4J 1.5.5 and earlier, in 1.5.6 and later the - SINGLETON field has been marked as private access. -

- - -

If you get the exception shown above, then you are using an - older version of slf4j-api, e.g. 1.4.3, with a new version of a - slf4j binding, e.g. 1.5.6. Typically, this occurs when your - Maven pom.ml file incoprporates hibernate 3.3.0 which - declares a dependency on slf4j-api version 1.4.2. If your - pom.xml declares a dependency on an slf4j binding, say - slf4j-log4j12 version 1.5.6, then you will get illegal access - errors. -

- -

To see which version of slfj4-api is pulled in by Maven, use - the maven dependency plugin as follows.

- -

mvn dependency:tree

- -

If you are usig Eclipse, please do not rely on the dependency - tree shown by m2eclipse.

- -

In your pom.xml file, excplicitly declaring a - dependecy on slf4j-api matching the version of the declared - binding will make the problem go away. -

- -
-
- - - - -
- - Why is SLF4J licensed under X11 type license instead of the - Apache Software License? - -
- -
-

SLF4J is licensed under a permissive X11 type license - instead of the ASL or the LGPL - because the X11 license is deemed by both the Apache Software - Foundation as well as the Free Software Foundation as - compatible with their respective licenses. -

- -
-
- - -
- - Where can I get a particular SLF4J binding? - -
- -
- -

SLF4J bindings for SimpleLogger, - NOPLogger, Log4jLoggerAdapter - and JDK14LoggerAdapter - are contained within the files slf4j-nop.jar, - slf4j-simple.jar, slf4j-log4j12.jar, and - slf4j-jdk14.jar. These files ship with the official SLF4J distribution. Please - note that all bindings depend on slf4j-api.jar. -

- -

The binding for logback-classic ships with the logback - distribution. However, as with all other bindings, the - logback-classic binding requires slf4j-api.jar. -

- -
-
- -
- Should my library attempt to configure logging? -
- -
-

Embedded components such as libraries do not need and - should not configure the underlying logging system. They - invoke SLF4J to log but should let the end-user configure the - logging environment. When embedded components try to configure - logging on their own, they often override the end-user's - wishes. At the end of the day, it is the end-user who has to - read the logs and process them. She should be the person to - decide how she wants her logging configured. -

- -
-
- -
What about Maven2 - transitive dependencies? -
- -
-

As an author of a library built with Maven2, you might - want to test your application using a binding, say - slf4j-log4j12 or logback-classic, without forcing log4j or - logback-classic as a dependency upon your users. As of SLF4J - version 1.3, this quite easy to accomplish. But first, since - your library's code depends on the SLF4J API you will need to - declare slf4j-api as a compile-time (default scope) - dependency. -

-
<dependency>
-  <groupId>org.slf4j</groupId>
-  <artifactId>slf4j-api</artifactId>
-  <version>${project.version}</version>
-</dependency>
- -

Limiting the transitivity of the SLF4J binding used in your - tests can be accomplished by declaring the scope of the - SLF4J-binding dependency as "test". Here is an example:

- -
<dependency>
-  <groupId>org.slf4j</groupId>
-  <artifactId>slf4j-log4j12</artifactId>
-  <version>${project.version}</version>
-  <scope>test</scope>
-</dependency>
- -

Thus, as far as your users are concerned you are exporting - slf4j-api as a transitive dependency of your library, but not - any SLF4J-binding or an underlying logging system. -

- -
- -
- - -
- How do I exclude commons-logging as a - Maven dependency? - -
- -
-

A large number of Maven projects declare commons-logging - as a dependency. Thus, if you wish to migrate to SLF4J or use - jcl-over-slf4j, you would need to declare a commons-logging - exclusion in all of your dependencies which transitively - depend on commons-logging. This can be an error prone - process. To alleviate the pain, Erik van Oosten has developed - a clever - hack around this problem. -

-
- - -
- - -

About the SLF4J API

- -
- -
Why - don't the printing methods in the Logger interface accept - message of type Object, but only messages of type String? -
- -
- -

In SLF4J 1.0beta4, the printing methods such as debug(), - info(), warn(), error() in the Logger interface were - modified so as to accept only messages of type String - instead of Object. -

- -

Thus, the set of printing methods for the DEBUG level - became:

- -
debug(String msg); 
-debug(String format, Object arg); 
-debug(String format, Object arg1, Object arg2);           
-debug(String msg, Throwable t);
- -

Previously, the first argument in the above methods was of - type Object.

- -

This change enforces the notion that logging systems are - about decorating and handling messages of type String, and not - any arbitrary type (Object). -

- -

Just as importantly, the new set of method signatures offer - a clearer differentiation between the overloaded methods - whereas previously the choice of the invoked method due to - Java overloading rules were not always easy to follow.

- -

It was also easy to make mistakes. For example, previously - it was legal to write:

- -
logger.debug(new Exception("some error"));
- -

Unfortunately, the above call did not print the stack trace - of the exception. Thus, a potentially crucial piece of - information could be lost. When the first parameter is - restricted to be of type String, then only the method -

- -
debug(String msg, Throwable t);
- -

can be used to log exceptions. Note that this method - ensures that every logged exception is accompanied with a - descriptive message.

- -
-
- -
- - Can I log an exception without an accompanying message? - -
-
-

In short, no.

- -

If e is an Exception, and you - would like to log an exception at the ERROR level, you must - add an accompanying message. For example,

- -
logger.error("some accompanying message", e);
- -

You might legitimately argue that not all exceptions have a - meaningful message to accompany them. Moreover, a good exception - should already contain a self explanatory description. The - accompanying message may therefore be considered redundant. -

- - -

While these are valid arguments, there are three opposing - arguments also worth considering. First, on many, albeit not - all occasions, the accompanying message can convey useful - information nicely complementing the description contained - in the exception. Frequently, at the point where the - exception is logged, the developer has access to more - contextual information than at the point where the exception - is thrown. Second, it is not difficult to imagine more or - less generic messages, e.g. "Exception caught", "Exception - follows", that can be used as the first argument for - error(String msg, Throwable t) invocations. - Third, most log output formats display the message on a - line, followed by the exception on a separate line. Thus, - the message line would look inconsistent without a message. -

- -

In short, if the user were allowed to log an exception - without an accompanying message, it would be the job of the - logging system to invent a message. This is actually what - the throwing(String - sourceClass, String sourceMethod, Throwable thrown) - method in java.util.logging package does. (It decides on its - own that accompanying message is the string "THROW".) -

- -

It may initially appear strange to require an accompanying - message to log an exception. Nevertheless, this is common - practice in all log4j derived systems such as - java.util.logging, logkit, etc. and of course log4j itself. It - seems that the current consensus considers requiring an - accompanying message as a good a thing (TM). -

- -
-
- - - -
- - What is the fastest way of (not) logging? -
-
- -

SLF4J supports an advanced feature called parameterized - logging which can significantly boost logging performance for - disabled logging statement.

- -

For some Logger logger, writing,

-
logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
- -

incurs the cost of constructing the message parameter, that - is converting both integer i and - entry[i] to a String, and concatenating - intermediate strings. This, regardless of whether the message - will be logged or not. -

- -

One possible way to avoid the cost of parameter - construction is by surrounding the log statement with a - test. Here is an example.

- -
if(logger.isDebugEnabled()) {
-  logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
-}
- - -

This way you will not incur the cost of parameter - construction if debugging is disabled for - logger. On the other hand, if the logger is - enabled for the DEBUG level, you will incur the cost of - evaluating whether the logger is enabled or not, twice: once in - debugEnabled and once in debug. This - is an insignificant overhead because evaluating a logger takes - less than 1% of the time it takes to actually log a statement. -

- -

Better yet, use parameterized messages

- -

There exists a very convenient alternative based on message - formats. Assuming entry is an object, you can write: -

- - -
Object entry = new SomeObject();
-logger.debug("The entry is {}.", entry);
- -

After evaluating whether to log or not, and only if the - decision is affirmative, will the logger implementation format - the message and replace the '{}' pair with the string value of - entry. In other words, this form does not incur - the cost of parameter construction in case the log statement is - disabled. -

- -

The following two lines will yield the exact same - output. However, the second form will outperform the first - form by a factor of at least 30, in case of a - disabled logging statement. -

- -
logger.debug("The new entry is "+entry+".");
-logger.debug("The new entry is {}.", entry);
- - -

A two argument variant is also available. For example, you - can write:

- - -
logger.debug("The new entry is {}. It replaces {}.", entry, oldEntry);
- -

If three or more arguments need to be passed, you can make - use of the Object[] variant. For example, you can - write:

- -
logger.debug("Value {} was inserted between {} and {}.", new Object[] {newVal, below, above});
- - - -

Array type arguments, including multi-dimensional arrays, - are also supported.

- -

SLF4J uses its own message formatting implementation which - differs from that of the Java platform. This is justified by - the fact that SLF4J's implementation performs about 10 times - faster but at the cost of being non-standard and less - flexible. -

- -

Escaping the "{}" pair

- -

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

- -

SLF4J only cares about the formatting anchor, that - is the '{' character immediately followed by '}'. Thus, in - case your message contains the '{' or the '}' character, you - do not have to do anything special unless the '}' character - immediately follows '}'. For example, -

- -
logger.debug("Set {1,2} differs from {}", "3");
- -

which will print as "Set {1,2} differs from 3".

- -

You could have even written,

-
logger.debug("Set {1,2} differs from {{}}", "3");
-

which would have printed as "Set {1,2} differs from {3}".

- -

In the extremely rare case where the the "{}" pair occurs - naturally within your text and you wish to disable the special - meaning of the formatting anchor, then you need to escape the - '{' character with '\', that is the backslash character. Only - the '{' character should be escaped. There is no need to - escape the '}' character. For example, -

- -
logger.debug("Set \\{} differs from {}", "3");
- -

will print as "Set {} differs from 3". Note that within - Java code, the backslash cracacter needs to be written as - '\\'.

- -

In the rare case where the "\{}" occurs naturally in the - message, you can double escape the formatting anchor so that - it retains its original meaning. For example,

- - -
logger.debug("File name is C:\\\\{}.", "file.zip");
-

will print as "File name is C:\file.zip".

- -
- -
- - -
How can - I log the string contents of a single (possibly complex) - object? - -
- -
-

In relatively rare cases where the message to be logged - is the string form of an object, then the parameterized - printing method of the appropriate level can be - used. Assuming complexObject is an object of - certain complexity, for a log statement of level DEBUG, you - can write: -

- -
logger.debug("{}", complexObject);
- - -

The logging system will invoke - complexObject.toString() method only after it - has ascertained that the log statement was - enabled. Otherwise, the cost of - complexObject.toString() conversion will be - advantageously avoided. -

- -
- -
- - - - -
- Why doesn't the - org.slf4j.Logger interface have methods for the FATAL - level? -
- -
-

From the stand point of a logging system, the distinction - between a fatal error and an error is usually not very - useful. Most programmers exit the application when a fatal - error is encountered. However, a logging library cannot (and - should not) decide on its own to terminate an - application. The initiative to exit the application must be - left to the developer. -

- - -

Thus, the most the FATAL level can do is to - highlight a given error as the cause for - application to crash. However, errors are by definition - exceptional events that merit attention. If a given - situation causes errors to be logged, the causes should be - attended to as soon as possible. However, if the "error" is - actually a normal situation which cannot be prevented but - merits being aware of, then it should be marked as WARN, not - ERROR. -

- -

Assuming the ERROR level designates exceptional situations - meriting close attention, we are inclined to believe that the - FATAL level is superfluous. -

- - -
-
- -
- Why was the TRACE level introduced only in - SLF4J version 1.4.0? - -
- -
- -

The addition of the TRACE level has been frequently and - hotly debated request. By studying various projects, we - observed that the TRACE level was used to disable logging - output from certain classes without needing to - configure logging for those classes. Indeed, the TRACE level - is by default disabled in log4j and logback as well most other - logging systems. The same result can be achieved by adding the - appropriate directives in configuration files. -

- -

Thus, in many of cases the TRACE level carried the same - semantic meaning as DEBUG. In such cases, the TRACE level - merely saves a few configuration directives. In other, more - interesting occasions, where TRACE carries a different meaning - than DEBUG, Marker - objects can be put to use to convey the desired - meaning. However, if you can't be bothered with markers and - wish to use a logging level lower than DEBUG, the TRACE level - can get the job done. -

- -

Note that while the cost of evaluating a disabled log - request is in the order of a few nanoseconds, the - use of the TRACE level (or any other level for that matter) is - discouraged in tight loops where the log request might be - evaluated millions of times. If the log request is enabled, - then it will overwhelm the target destination with massive - output. If the request is disabled, it will waste resources. -

- -

In short, although we still discourage the use of the TRACE - level because alternatives exist or because in many cases log - requests of level TRACE are wasteful, given that people kept - asking for it, we decided to bow to popular demand. -

-
- -
- -
- Does the SLF4J logging API support - I18N (internationalization)? - -
- -
-

Yes, as of version 1.5.9, SLF4J ships with a package called - org.slf4j.cal10n which adds localized/internationalized logging - support as a thin layer built upon the CAL10N API.

- -
-
- -
Is it - possible to retrieve loggers without going through the static - methods in LoggerFactory? -
- -
- -

Yes. LoggerFactory is essentially a wrapper - around an ILoggerFactory - instance. The ILoggerFactory instance in use is - determined according to the static binding conventions of the - SLF4J framework. See the getSingleton() - method in LoggerFactory for details. -

- -

However, nothing prevents you from using your own - ILoggerFactory instance. Note that you can also - obtain a reference to the ILoggerFactory that the - LoggerFactory class is using by invoking the - LoggerFactory.getILoggerFactory() method. -

- -

Thus, if SLF4J binding conventions do not fit your needs, or - if you need additional flexibility, then do consider using the - ILoggerFactory interface as an alternative to - inventing your own logging API.

-
- - - -
- - - - -

Implementing the SLF4J API

- -
-
How do - I make my logging framework SLF4J compatible? - -
- - -
- -

Adding supporting for the SLF4J is surprisingly - easy. Essentially, you coping an existing binding and tailoring - it a little (as explained below) does the trick. -

- -

Assuming your logging system has notion of a - logger, called say MyLogger, you need to provide - an adapter for MyLogger to - org.slf4j.Logger interface. Refer to slf4j-jcl, - slf4j-jdk14, and slf4j-log4j12 modules for examples of - adapters. -

- -

Once you have written an appropriate adapter, say - MyLoggerAdapter, you need to provide a factory - class implementing the org.slf4j.ILoggerFactory - interface. This factory should return instances - MyLoggerAdapter. Let MyLoggerFactory - be the name of your factory class. -

- -

Once you have the adapter, namely - MyLoggerAdapter, and a factory, namely - MyLoggerFactory, the last remaining step is to - modify the StaticLoggerBinder class so that it - returns an new instance of MyLoggerFactory. You - will also need to modify the - loggerFactoryClassStr variable. -

- -

For Marker or MDC support, you could use the one of the - existing NOP implementations. -

- -

In summary, to create an SLF4J binding for your logging - system, follow these steps:

- -
    -
  1. start with a copy of an existing module,
  2. -
  3. create an adapter between your logging system and - org.slf4j.Logger interface -
  4. -
  5. create a factory for the adapter created in the previous step,
  6. -
  7. modify StaticLoggerBinder class to use the - factory you created in the previous step
  8. -
- -
-
-
- How - can my logging system add support for the Marker - interface? - -
-
- -

Markers constitute a revolutionary concept which is - supported by logback but not other existing logging - systems. Consequently, SLF4J conforming logging systems are - allowed to ignore marker data passed by the user. -

- -

However, even though marker data may be ignored, the user - must still be allowed to specify marker data. Otherwise, users - would not be able to switch between logging systems that - support markers and those that do not. -

- -

The MarkerIgnoringBase class can serve as a - base for adapters or native implementations of logging - systems lacking marker support. In - MarkerIgnoringBase, methods taking marker data - simply invoke the corresponding method without the Marker - argument, discarding any Marker data passed as - argument. Your SLF4J adapters can extend - MarkerIgnoringBase to quickly implement the - methods in org.slf4j.Logger which take a - Marker as the first argument. -

- -
-
- -
How does - SLF4J's version check mechanism work? -
- -
-

The version check performed by SLF4J API during its - initialization is an elective process. Conforming SLF4J - implementations may choose not to participate, in - which case, no version check will be performed. -

- -

However, if an SLF4J implementation decides to participate, - than it needs to declare a variable called - REQUESTED_API_VERSION within its copy of the - StaticLoggerBinder class. The value of this - variable should be equal to the version of the slf4j-api.jar - it is compiled with. If the implementation is upgraded to a - newer version of slf4j-api, than you also need to update the - value of REQUESTED_API_VERSION. -

- -

For each version, SLF4J API maintains a list of compatible - versions. SLF4J will emit a version mismatch warning only if - the requested version is not found in the compatibility - list. So even if your SLF4J binding has a different release - schedule than SLF4J, assuming you update the SLF4J version you - use every 6 to 12 months, you can still participate in the - version check without incurring a mismatch warning. For - example, logback has a different release schedule but still - participates in version checks.

- -

As of SLF4J 1.5.5, all bindings shipped within the - SLF4J distribution, e.g. slf4j-logj12, slf4j-simple and - slf4j-jdk14, declare the REQUESTED_API_VERSION field with a - value equal to their SLF4J version. It follows that, for - example if slf4j-simple-1.5.6.jar is mixed with - slf4j-api-1.5.5.jar, then a version mismatch warning will be - issued. Note that SLF4J versions prior to 1.5.5 did not have a - version check mechanism. Only slf4j-api-1.5.5.jar and later - can emit version mismatch warnings. (Actually, version 1.5.4 - offered a check policy which was much too restrictive and - inconsistent with the size of our user base. Consequently, - SLF4J version 1.5.5 was released just a day after 1.5.4.) -

- -

Given its large installed user base and several external - implementations, it would have been unwise to expect all SLF4J - implementations to closely follow SLF4J's release schedule, let - alone align their release schedules with SLF4J. Hence, the - elective version check policy. -

- -
- -
- -

General questions about logging

- - -
-
Should Logger - members of a class be declared as static? -
-
- -

We used to recommend that loggers members be - declared as instance variables instead of static. After further - analysis, we no longer recommend one approach over the - other. -

- -

Here is a summary of the pros and cons of each approach. -

- - - - - - - - - - - - - - - - - - - - - - -
Advantages for declaring loggers as staticDisadvantages for declaring loggers as static
-
    -
  1. common and well-established idiom
  2. -
  3. less CPU overhead: loggers are retrieved and - assigned only once, at hosting class - initialization
  4. -
  5. less memory overhead: logger declaration will - consume one reference per class
  6. -
-
-
    -
  1. For libraries shared between applications, not - possible to take advantage of repository selectors. It - should be noted that if the SLF4J binding and the - underlying API ships with each application (not shared - between applications), then each application will still - have its own logging environment. -
  2. -
  3. not IOC-friendly
  4. -
-
Advantages for declaring loggers as instance variablesDisadvantages for declaring loggers as - instance variables
-
    -
  1. Possible to take advantage of repository selectors - even for libraries shared between applications. However, - repository selectors only work if the underlying logging - system is logback-classic. Repository selectors do not - work for the SLF4J+log4j combination. -
  2. -
  3. IOC-friendly
  4. -
-
-
    -
  1. Less common idiom than declaring loggers as static - variables
  2. - -
  3. higher CPU overhead: loggers are retrieved and - assigned for each instance of the hosting class
  4. - -
  5. higher memory overhead: logger declaration will - consume one reference per instance of the hosting class
  6. -
-
- - -

Explanation

- -

Static logger members cost a single variable reference for - all instances of the class whereas an instance logger member - will cost a variable reference for every instance of the - class. For simple classes instantiated thousands of times - there might be a noticeable difference. -

- -

However, more recent logging systems, e.g log4j or logback, - support a distinct logger context for each application running - in the application server. Thus, even if a single copy of - log4j.jar or logback-classic.jar is deployed - in the server, the logging system will be able to differentiate - between applications and offer a distinct logging environment - for each application. -

- -

More specifically, each time a logger is retrieved by - invoking LoggerFactory.getLogger() method, the - underlying logging system will return an instance appropriate - for the current application. Please note that within the - same application retrieving a logger by a given name - will always return the same logger. For a given name, a - different logger will be returned only for different - applications. -

- -

If the logger is static, then it will only be retrieved once - when the hosting class is loaded into memory. If the hosting - class is used in only in one application, there is not much to - be concerned about. However, if the hosting class is shared - between several applications, then all instances of the shared - class will log into the context of the application which - happened to first load the shared class into memory - hardly the - behavior expected by the user. -

- -

Unfortunately, for non-native implementations of the SLF4J - API, namely with slf4j-log4j12, log4j's repository selector will - not be able to do its job properly because slf4j-log4j12, a - non-native SLF4J binding, will store logger instances in a map, - short-circuiting context-dependent logger retrieval. For native - SLF4J implementations, such as logback-classic, repository - selectors will work as expected. -

- -

The Apache Commons wiki contains an informative - article covering the same question.

- -

Logger serialization

- -

Contrary to static variables, instance variables are - serialized by default. As of SLF4J version 1.5.3, logger - instances survive serialization. Thus, serialization of the host - class no longer requires any special action, even when loggers - are declared as instance variables. In previous versions, logger - instances needed to be declared as transient in the - host class.

- -

Summary

- -

In summary, declaring logger members as static variables - requires less CPU time and have a slightly smaller memory - footprint. On the other hand, declaring logger members as - instance variables requires more CPU time and have a slighlty - higher memory overhead. However, instance variables make it - possible to create a distinct logger environment for each - application, even for loggers declared in shared - libraries. Perhaps more important than previously mentioned - considerations, instance variables are IOC-friendly whereas - static variables are not. -

- -

See also related - discussion in the commons-logging wiki. -

- -
-
- -
-
Is there a recommended idiom for - declaring a logger in a class? -
- -
-

The following is the recommended logger declaration - idiom. For reasons explained - above, it is left to the user to determine whether loggers - are declared as static variables or not.

- -
package some.package;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-      
-public class MyClass {
-  final (static) Logger logger = LoggerFactory.getLogger(MyClass.class);
-  ... etc
-}
- -

Unfortunately, give that the name of the hosting class is - part of the logger declaration, the above logger declaration - idiom is not is not resistant to cut-and-pasting - between classes. -

-
-
- - -
- - + + + + + + SLF4J FAQ + + + + + + + + + +
+ +
+ +
+ +

Frequently Asked Questions about SLF4J

+ +

Generalities

+ +
    +
  1. What is SLF4J?
  2. + +
  3. When should SLF4J be used?
  4. + +
  5. Is SLF4J yet another loggingfacade?
  6. + +
  7. If SLF4J fixes JCL, then why + wasn't the fix made in JCL instead of creating a new project? + +
  8. + +
  9. When using SLF4J, do I have to + recompile my application to switch to a different logging + system? + +
  10. + +
  11. What are SLF4J's requirements?
  12. + +
  13. Are SLF4J versions backward + compatible?
  14. + +
  15. I am getting + IllegalAccessError exceptions when using SLF4J. Why + is that?
  16. + + +
  17. + Why is SLF4J licensed under X11 type + license instead of the Apache Software License? + +
  18. + +
  19. + Where can I get a particular + SLF4J binding? + +
  20. + +
  21. + Should my library attempt to + configure logging? + +
  22. + +
  23. + What about Maven 2 transitive + dependencies? + +
  24. + +
  25. + How do I exclude commons-logging as a + Maven dependency? + +
  26. +
+ + + About the SLF4J API + +
    + +
  1. + Why don't the printing methods + in the Logger interface accept message of type Object, but only + messages of type String? + +
  2. + +
  3. + + Can I log an exception without an accompanying message? + +
  4. + + +
  5. + What is the fastest way of + (not) logging? + +
  6. + +
  7. + How can I log the string contents + of a single (possibly complex) object? + +
  8. + + +
  9. Why doesn't the + org.slf4j.Logger interface have methods for the + FATAL level?
  10. + +
  11. Why was the TRACE level introduced only in + SLF4J version 1.4.0?
  12. + +
  13. Does the SLF4J logging API support I18N + (internationalization)?
  14. + + +
  15. Is it possible to retrieve loggers + without going through the static methods in + LoggerFactory?
  16. + + +
+ + + + Implementing the SLF4J API + +
    + +
  1. How do I make my logging + framework SLF4J compatible?
  2. + +
  3. How can my logging system add + support for the Marker interface?
  4. + +
  5. How does SLF4J's version check + mechanism work?
  6. + + +
+ + + General questions about logging + + +
    + +
  1. Should Logger members of a class + be declared as static?
  2. + + +
  3. Is there a recommended idiom + for declaring a loggers in a class?
  4. + +
+ +

Generalities

+ +
+
What is SLF4J?
+
+

SLF4J is a simple facade for logging systems allowing the + end-user to plug-in the desired logging system at deployment + time. +

+ +
+
+ +
When should SLF4J be used? +
+ +
+

In short, libraries and other embedded components should + consider SLF4J for their logging needs because libraries + cannot afford to impose their choice of logging system on the + end-user. On the other hand, it does not necessarily make + sense for stand-alone applications to use SLF4J. Stand-alone + applications can invoke the logging system of their choice + directly. +

+ +

SLF4J is only a facade, meaning that it does not provide a + complete logging solution. Operations such as configuring + appenders or setting logging levels cannot be performed with + SLF4J. Thus, at some point in time, any non-trivial + application will need to directly invoke the underlying + logging system. In other words, complete independence from the + API underlying logging system is not possible for a + stand-alone application. Nevertheless, SLF4J reduces the + impact of this dependence to near-painless levels. +

+ +

Suppose that your CRM application uses log4j for its + logging. However, one of your important clients request that + logging be performed through JDK 1.4 logging. If your + application is riddled with thousands of direct log4j calls, + migration to JDK 1.4 would be a relatively lengthy and + error-prone process. Even worse, you would potentially need to + maintain two versions of your CRM software. Had you been + invoking SLF4J API instead of log4j, the migration could be + completed in a matter of minutes by replacing one jar file with + another. +

+ +

SLF4J lets component developers to defer the choice of the + logging system to the end-user but eventually a choice needs + to be made. +

+ +
+ +
+ +
+ + Is SLF4J yet another logging facade? +
+ +
+

SLF4J is conceptually very similar to JCL. As such, it can + be thought of as yet another logging facade. However, SLF4J is + much simpler in design and arguably more robust. In a + nutshell, SLF4J avoid the class loader issues that plague JCL. +

+ +
+ +
+
+ + If SLF4J fixes JCL, then why wasn't the fix made in JCL + instead of creating a new project? + +
+ +
+

This is a very good question. First, SLF4J static binding + approach is very simple, perhaps even laughably so. It was + not easy to convince developers of the validity of that + approach. It is only after SLF4J was released and started to + become accepted did it gain respectability in the relevant + community. +

+ +

Second, SLF4J offers two enhancements which tend to be + underestimated. Parameterized log messages solve an important + problem associated with logging performance, in a pragmatic + way. Marker objects, which are supported by the + org.slf4j.Logger interface, pave the way for + adoption of advanced logging systems and still leave the door + open to switching back to more traditional logging systems if + need be. +

+ +
+
+ +
+ When + using SLF4J, do I have to recompile my application to switch + to a different logging system? +
+ +
+

No, you do not need to recompile your application. You can + switch to a different logging system by removing the previous + SLF4J binding and replacing it with the binding of your choice. +

+ +

For example, if you were using the NOP implementation and + would like to switch to log4j version 1.2, simply replace + slf4j-nop.jar with slf4j-log4j12.jar on + your class path but do not forget to add log4j-1.2.x.jar as + well. Want to switch to JDK 1.4 logging? Just replace + slf4j-log4j12.jar with slf4j-jdk14.jar. +

+ +
+
+
+ What are SLF4J's + requirements? +
+ +
+ +

In principle, SLF4J requires JDK 1.3 or above, in + particular slf4j-api is compatible with JDK 1.3. However, + the underlying logging system might have a higher + requirement. For instance, the slf4j-jdk14 binding + requires JDK 1.4. Logback requires JDK 1.5. +

+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BindingRequirements
slf4j-nopJDK 1.3
slf4j-simpleJDK 1.3
slf4j-log4j12JDK 1.3, plus any other library + dependencies required by the log4j appenders in use
slf4j-jdk14JDK 1.4 or above
logback-classicJDK 1.5 or above, plus any other library dependencies + required by the logback appenders in use
+ +
+
+ + + +
Are SLF4J + versions backward compatible? +
+ +
+

With rare theoretical exceptions, SLF4J versions are backward + compatible. This means than you can upgrade from SLF4J version + 1.0 to any later version without problems.

+ +

However, while the SLF4J API is very stable from the client's + perspective, SLF4J bindings such as slf4j-simple or + slf4j-log4j12 may require a specific version of slf4j-api. Mixing different versions of slf4j artifacts can + be problematic and is strongly discouraged. For + instance, if you are using slf4j-api-1.5.6.jar, then you should + also use slf4j-simple-1.5.6.jar, using slf4j-simple-1.4.2.jar + will not work. +

+ +

At initialization time, if SLF4J suspects that there may be a + version mismatch problem, it emits a warning about the said + mismatch. For the exact details of the version mismatch + detection mechanism, please refer to the relevant entry in this FAQ. +

+ +
+
+ + + +
I am getting + IllegalAccessError exceptions when using SLF4J. Why + is that? +
+ +
+ +

Here are the exception details.

+ +
Exception in thread "main" java.lang.IllegalAccessError: tried to access field
+org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory
+   at org.slf4j.LoggerFactory.<clinit>(LoggerFactory.java:60)
+ +

This error is caused by the static initilizer of the + LoggerFactory class attempting to directly access + the SINGLETON field of + org.slf4j.impl.StaticLoggerBinder. While this was + allowed in SLF4J 1.5.5 and earlier, in 1.5.6 and later the + SINGLETON field has been marked as private access. +

+ + +

If you get the exception shown above, then you are using an + older version of slf4j-api, e.g. 1.4.3, with a new version of a + slf4j binding, e.g. 1.5.6. Typically, this occurs when your + Maven pom.ml file incoprporates hibernate 3.3.0 which + declares a dependency on slf4j-api version 1.4.2. If your + pom.xml declares a dependency on an slf4j binding, say + slf4j-log4j12 version 1.5.6, then you will get illegal access + errors. +

+ +

To see which version of slfj4-api is pulled in by Maven, use + the maven dependency plugin as follows.

+ +

mvn dependency:tree

+ +

If you are usig Eclipse, please do not rely on the dependency + tree shown by m2eclipse.

+ +

In your pom.xml file, excplicitly declaring a + dependecy on slf4j-api matching the version of the declared + binding will make the problem go away. +

+ +
+
+ + + + +
+ + Why is SLF4J licensed under X11 type license instead of the + Apache Software License? + +
+ +
+

SLF4J is licensed under a permissive X11 type license + instead of the ASL or the LGPL + because the X11 license is deemed by both the Apache Software + Foundation as well as the Free Software Foundation as + compatible with their respective licenses. +

+ +
+
+ + +
+ + Where can I get a particular SLF4J binding? + +
+ +
+ +

SLF4J bindings for SimpleLogger, + NOPLogger, Log4jLoggerAdapter + and JDK14LoggerAdapter + are contained within the files slf4j-nop.jar, + slf4j-simple.jar, slf4j-log4j12.jar, and + slf4j-jdk14.jar. These files ship with the official SLF4J distribution. Please + note that all bindings depend on slf4j-api.jar. +

+ +

The binding for logback-classic ships with the logback + distribution. However, as with all other bindings, the + logback-classic binding requires slf4j-api.jar. +

+ +
+
+ +
+ Should my library attempt to configure logging? +
+ +
+

Embedded components such as libraries do not need and + should not configure the underlying logging system. They + invoke SLF4J to log but should let the end-user configure the + logging environment. When embedded components try to configure + logging on their own, they often override the end-user's + wishes. At the end of the day, it is the end-user who has to + read the logs and process them. She should be the person to + decide how she wants her logging configured. +

+ +
+
+ +
What about Maven2 + transitive dependencies? +
+ +
+

As an author of a library built with Maven2, you might + want to test your application using a binding, say + slf4j-log4j12 or logback-classic, without forcing log4j or + logback-classic as a dependency upon your users. As of SLF4J + version 1.3, this quite easy to accomplish. But first, since + your library's code depends on the SLF4J API you will need to + declare slf4j-api as a compile-time (default scope) + dependency. +

+
<dependency>
+  <groupId>org.slf4j</groupId>
+  <artifactId>slf4j-api</artifactId>
+  <version>${project.version}</version>
+</dependency>
+ +

Limiting the transitivity of the SLF4J binding used in your + tests can be accomplished by declaring the scope of the + SLF4J-binding dependency as "test". Here is an example:

+ +
<dependency>
+  <groupId>org.slf4j</groupId>
+  <artifactId>slf4j-log4j12</artifactId>
+  <version>${project.version}</version>
+  <scope>test</scope>
+</dependency>
+ +

Thus, as far as your users are concerned you are exporting + slf4j-api as a transitive dependency of your library, but not + any SLF4J-binding or an underlying logging system. +

+ +
+ +
+ + +
+ How do I exclude commons-logging as a + Maven dependency? + +
+ +
+

A large number of Maven projects declare commons-logging + as a dependency. Thus, if you wish to migrate to SLF4J or use + jcl-over-slf4j, you would need to declare a commons-logging + exclusion in all of your dependencies which transitively + depend on commons-logging. This can be an error prone + process. To alleviate the pain, Erik van Oosten has developed + a clever + hack around this problem. +

+
+ + +
+ + +

About the SLF4J API

+ +
+ +
Why + don't the printing methods in the Logger interface accept + message of type Object, but only messages of type String? +
+ +
+ +

In SLF4J 1.0beta4, the printing methods such as debug(), + info(), warn(), error() in the Logger interface were + modified so as to accept only messages of type String + instead of Object. +

+ +

Thus, the set of printing methods for the DEBUG level + became:

+ +
debug(String msg); 
+debug(String format, Object arg); 
+debug(String format, Object arg1, Object arg2);           
+debug(String msg, Throwable t);
+ +

Previously, the first argument in the above methods was of + type Object.

+ +

This change enforces the notion that logging systems are + about decorating and handling messages of type String, and not + any arbitrary type (Object). +

+ +

Just as importantly, the new set of method signatures offer + a clearer differentiation between the overloaded methods + whereas previously the choice of the invoked method due to + Java overloading rules were not always easy to follow.

+ +

It was also easy to make mistakes. For example, previously + it was legal to write:

+ +
logger.debug(new Exception("some error"));
+ +

Unfortunately, the above call did not print the stack trace + of the exception. Thus, a potentially crucial piece of + information could be lost. When the first parameter is + restricted to be of type String, then only the method +

+ +
debug(String msg, Throwable t);
+ +

can be used to log exceptions. Note that this method + ensures that every logged exception is accompanied with a + descriptive message.

+ +
+
+ +
+ + Can I log an exception without an accompanying message? + +
+
+

In short, no.

+ +

If e is an Exception, and you + would like to log an exception at the ERROR level, you must + add an accompanying message. For example,

+ +
logger.error("some accompanying message", e);
+ +

You might legitimately argue that not all exceptions have a + meaningful message to accompany them. Moreover, a good exception + should already contain a self explanatory description. The + accompanying message may therefore be considered redundant. +

+ + +

While these are valid arguments, there are three opposing + arguments also worth considering. First, on many, albeit not + all occasions, the accompanying message can convey useful + information nicely complementing the description contained + in the exception. Frequently, at the point where the + exception is logged, the developer has access to more + contextual information than at the point where the exception + is thrown. Second, it is not difficult to imagine more or + less generic messages, e.g. "Exception caught", "Exception + follows", that can be used as the first argument for + error(String msg, Throwable t) invocations. + Third, most log output formats display the message on a + line, followed by the exception on a separate line. Thus, + the message line would look inconsistent without a message. +

+ +

In short, if the user were allowed to log an exception + without an accompanying message, it would be the job of the + logging system to invent a message. This is actually what + the throwing(String + sourceClass, String sourceMethod, Throwable thrown) + method in java.util.logging package does. (It decides on its + own that accompanying message is the string "THROW".) +

+ +

It may initially appear strange to require an accompanying + message to log an exception. Nevertheless, this is common + practice in all log4j derived systems such as + java.util.logging, logkit, etc. and of course log4j itself. It + seems that the current consensus considers requiring an + accompanying message as a good a thing (TM). +

+ +
+
+ + + +
+ + What is the fastest way of (not) logging? +
+
+ +

SLF4J supports an advanced feature called parameterized + logging which can significantly boost logging performance for + disabled logging statement.

+ +

For some Logger logger, writing,

+
logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
+ +

incurs the cost of constructing the message parameter, that + is converting both integer i and + entry[i] to a String, and concatenating + intermediate strings. This, regardless of whether the message + will be logged or not. +

+ +

One possible way to avoid the cost of parameter + construction is by surrounding the log statement with a + test. Here is an example.

+ +
if(logger.isDebugEnabled()) {
+  logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));
+}
+ + +

This way you will not incur the cost of parameter + construction if debugging is disabled for + logger. On the other hand, if the logger is + enabled for the DEBUG level, you will incur the cost of + evaluating whether the logger is enabled or not, twice: once in + debugEnabled and once in debug. This + is an insignificant overhead because evaluating a logger takes + less than 1% of the time it takes to actually log a statement. +

+ +

Better yet, use parameterized messages

+ +

There exists a very convenient alternative based on message + formats. Assuming entry is an object, you can write: +

+ + +
Object entry = new SomeObject();
+logger.debug("The entry is {}.", entry);
+ +

After evaluating whether to log or not, and only if the + decision is affirmative, will the logger implementation format + the message and replace the '{}' pair with the string value of + entry. In other words, this form does not incur + the cost of parameter construction in case the log statement is + disabled. +

+ +

The following two lines will yield the exact same + output. However, the second form will outperform the first + form by a factor of at least 30, in case of a + disabled logging statement. +

+ +
logger.debug("The new entry is "+entry+".");
+logger.debug("The new entry is {}.", entry);
+ + +

A two argument variant is also available. For example, you + can write:

+ + +
logger.debug("The new entry is {}. It replaces {}.", entry, oldEntry);
+ +

If three or more arguments need to be passed, you can make + use of the Object[] variant. For example, you can + write:

+ +
logger.debug("Value {} was inserted between {} and {}.", new Object[] {newVal, below, above});
+ + + +

Array type arguments, including multi-dimensional arrays, + are also supported.

+ +

SLF4J uses its own message formatting implementation which + differs from that of the Java platform. This is justified by + the fact that SLF4J's implementation performs about 10 times + faster but at the cost of being non-standard and less + flexible. +

+ +

Escaping the "{}" pair

+ +

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

+ +

SLF4J only cares about the formatting anchor, that + is the '{' character immediately followed by '}'. Thus, in + case your message contains the '{' or the '}' character, you + do not have to do anything special unless the '}' character + immediately follows '}'. For example, +

+ +
logger.debug("Set {1,2} differs from {}", "3");
+ +

which will print as "Set {1,2} differs from 3".

+ +

You could have even written,

+
logger.debug("Set {1,2} differs from {{}}", "3");
+

which would have printed as "Set {1,2} differs from {3}".

+ +

In the extremely rare case where the the "{}" pair occurs + naturally within your text and you wish to disable the special + meaning of the formatting anchor, then you need to escape the + '{' character with '\', that is the backslash character. Only + the '{' character should be escaped. There is no need to + escape the '}' character. For example, +

+ +
logger.debug("Set \\{} differs from {}", "3");
+ +

will print as "Set {} differs from 3". Note that within + Java code, the backslash cracacter needs to be written as + '\\'.

+ +

In the rare case where the "\{}" occurs naturally in the + message, you can double escape the formatting anchor so that + it retains its original meaning. For example,

+ + +
logger.debug("File name is C:\\\\{}.", "file.zip");
+

will print as "File name is C:\file.zip".

+ +
+ +
+ + +
How can + I log the string contents of a single (possibly complex) + object? + +
+ +
+

In relatively rare cases where the message to be logged + is the string form of an object, then the parameterized + printing method of the appropriate level can be + used. Assuming complexObject is an object of + certain complexity, for a log statement of level DEBUG, you + can write: +

+ +
logger.debug("{}", complexObject);
+ + +

The logging system will invoke + complexObject.toString() method only after it + has ascertained that the log statement was + enabled. Otherwise, the cost of + complexObject.toString() conversion will be + advantageously avoided. +

+ +
+ +
+ + + + +
+ Why doesn't the + org.slf4j.Logger interface have methods for the FATAL + level? +
+ +
+

From the stand point of a logging system, the distinction + between a fatal error and an error is usually not very + useful. Most programmers exit the application when a fatal + error is encountered. However, a logging library cannot (and + should not) decide on its own to terminate an + application. The initiative to exit the application must be + left to the developer. +

+ + +

Thus, the most the FATAL level can do is to + highlight a given error as the cause for + application to crash. However, errors are by definition + exceptional events that merit attention. If a given + situation causes errors to be logged, the causes should be + attended to as soon as possible. However, if the "error" is + actually a normal situation which cannot be prevented but + merits being aware of, then it should be marked as WARN, not + ERROR. +

+ +

Assuming the ERROR level designates exceptional situations + meriting close attention, we are inclined to believe that the + FATAL level is superfluous. +

+ + +
+
+ +
+ Why was the TRACE level introduced only in + SLF4J version 1.4.0? + +
+ +
+ +

The addition of the TRACE level has been frequently and + hotly debated request. By studying various projects, we + observed that the TRACE level was used to disable logging + output from certain classes without needing to + configure logging for those classes. Indeed, the TRACE level + is by default disabled in log4j and logback as well most other + logging systems. The same result can be achieved by adding the + appropriate directives in configuration files. +

+ +

Thus, in many of cases the TRACE level carried the same + semantic meaning as DEBUG. In such cases, the TRACE level + merely saves a few configuration directives. In other, more + interesting occasions, where TRACE carries a different meaning + than DEBUG, Marker + objects can be put to use to convey the desired + meaning. However, if you can't be bothered with markers and + wish to use a logging level lower than DEBUG, the TRACE level + can get the job done. +

+ +

Note that while the cost of evaluating a disabled log + request is in the order of a few nanoseconds, the + use of the TRACE level (or any other level for that matter) is + discouraged in tight loops where the log request might be + evaluated millions of times. If the log request is enabled, + then it will overwhelm the target destination with massive + output. If the request is disabled, it will waste resources. +

+ +

In short, although we still discourage the use of the TRACE + level because alternatives exist or because in many cases log + requests of level TRACE are wasteful, given that people kept + asking for it, we decided to bow to popular demand. +

+
+ +
+ +
+ Does the SLF4J logging API support + I18N (internationalization)? + +
+ +
+

Yes, as of version 1.5.9, SLF4J ships with a package called + org.slf4j.cal10n which adds localized/internationalized logging + support as a thin layer built upon the CAL10N API.

+ +
+
+ +
Is it + possible to retrieve loggers without going through the static + methods in LoggerFactory? +
+ +
+ +

Yes. LoggerFactory is essentially a wrapper + around an ILoggerFactory + instance. The ILoggerFactory instance in use is + determined according to the static binding conventions of the + SLF4J framework. See the getSingleton() + method in LoggerFactory for details. +

+ +

However, nothing prevents you from using your own + ILoggerFactory instance. Note that you can also + obtain a reference to the ILoggerFactory that the + LoggerFactory class is using by invoking the + LoggerFactory.getILoggerFactory() method. +

+ +

Thus, if SLF4J binding conventions do not fit your needs, or + if you need additional flexibility, then do consider using the + ILoggerFactory interface as an alternative to + inventing your own logging API.

+
+ + + +
+ + + + +

Implementing the SLF4J API

+ +
+
How do + I make my logging framework SLF4J compatible? + +
+ + +
+ +

Adding supporting for the SLF4J is surprisingly + easy. Essentially, you coping an existing binding and tailoring + it a little (as explained below) does the trick. +

+ +

Assuming your logging system has notion of a + logger, called say MyLogger, you need to provide + an adapter for MyLogger to + org.slf4j.Logger interface. Refer to slf4j-jcl, + slf4j-jdk14, and slf4j-log4j12 modules for examples of + adapters. +

+ +

Once you have written an appropriate adapter, say + MyLoggerAdapter, you need to provide a factory + class implementing the org.slf4j.ILoggerFactory + interface. This factory should return instances + MyLoggerAdapter. Let MyLoggerFactory + be the name of your factory class. +

+ +

Once you have the adapter, namely + MyLoggerAdapter, and a factory, namely + MyLoggerFactory, the last remaining step is to + modify the StaticLoggerBinder class so that it + returns an new instance of MyLoggerFactory. You + will also need to modify the + loggerFactoryClassStr variable. +

+ +

For Marker or MDC support, you could use the one of the + existing NOP implementations. +

+ +

In summary, to create an SLF4J binding for your logging + system, follow these steps:

+ +
    +
  1. start with a copy of an existing module,
  2. +
  3. create an adapter between your logging system and + org.slf4j.Logger interface +
  4. +
  5. create a factory for the adapter created in the previous step,
  6. +
  7. modify StaticLoggerBinder class to use the + factory you created in the previous step
  8. +
+ +
+
+
+ How + can my logging system add support for the Marker + interface? + +
+
+ +

Markers constitute a revolutionary concept which is + supported by logback but not other existing logging + systems. Consequently, SLF4J conforming logging systems are + allowed to ignore marker data passed by the user. +

+ +

However, even though marker data may be ignored, the user + must still be allowed to specify marker data. Otherwise, users + would not be able to switch between logging systems that + support markers and those that do not. +

+ +

The MarkerIgnoringBase class can serve as a + base for adapters or native implementations of logging + systems lacking marker support. In + MarkerIgnoringBase, methods taking marker data + simply invoke the corresponding method without the Marker + argument, discarding any Marker data passed as + argument. Your SLF4J adapters can extend + MarkerIgnoringBase to quickly implement the + methods in org.slf4j.Logger which take a + Marker as the first argument. +

+ +
+
+ +
How does + SLF4J's version check mechanism work? +
+ +
+

The version check performed by SLF4J API during its + initialization is an elective process. Conforming SLF4J + implementations may choose not to participate, in + which case, no version check will be performed. +

+ +

However, if an SLF4J implementation decides to participate, + than it needs to declare a variable called + REQUESTED_API_VERSION within its copy of the + StaticLoggerBinder class. The value of this + variable should be equal to the version of the slf4j-api.jar + it is compiled with. If the implementation is upgraded to a + newer version of slf4j-api, than you also need to update the + value of REQUESTED_API_VERSION. +

+ +

For each version, SLF4J API maintains a list of compatible + versions. SLF4J will emit a version mismatch warning only if + the requested version is not found in the compatibility + list. So even if your SLF4J binding has a different release + schedule than SLF4J, assuming you update the SLF4J version you + use every 6 to 12 months, you can still participate in the + version check without incurring a mismatch warning. For + example, logback has a different release schedule but still + participates in version checks.

+ +

As of SLF4J 1.5.5, all bindings shipped within the + SLF4J distribution, e.g. slf4j-logj12, slf4j-simple and + slf4j-jdk14, declare the REQUESTED_API_VERSION field with a + value equal to their SLF4J version. It follows that, for + example if slf4j-simple-1.5.6.jar is mixed with + slf4j-api-1.5.5.jar, then a version mismatch warning will be + issued. Note that SLF4J versions prior to 1.5.5 did not have a + version check mechanism. Only slf4j-api-1.5.5.jar and later + can emit version mismatch warnings. (Actually, version 1.5.4 + offered a check policy which was much too restrictive and + inconsistent with the size of our user base. Consequently, + SLF4J version 1.5.5 was released just a day after 1.5.4.) +

+ +

Given its large installed user base and several external + implementations, it would have been unwise to expect all SLF4J + implementations to closely follow SLF4J's release schedule, let + alone align their release schedules with SLF4J. Hence, the + elective version check policy. +

+ +
+ +
+ +

General questions about logging

+ + +
+
Should Logger + members of a class be declared as static? +
+
+ +

We used to recommend that loggers members be + declared as instance variables instead of static. After further + analysis, we no longer recommend one approach over the + other. +

+ +

Here is a summary of the pros and cons of each approach. +

+ + + + + + + + + + + + + + + + + + + + + + +
Advantages for declaring loggers as staticDisadvantages for declaring loggers as static
+
    +
  1. common and well-established idiom
  2. +
  3. less CPU overhead: loggers are retrieved and + assigned only once, at hosting class + initialization
  4. +
  5. less memory overhead: logger declaration will + consume one reference per class
  6. +
+
+
    +
  1. For libraries shared between applications, not + possible to take advantage of repository selectors. It + should be noted that if the SLF4J binding and the + underlying API ships with each application (not shared + between applications), then each application will still + have its own logging environment. +
  2. +
  3. not IOC-friendly
  4. +
+
Advantages for declaring loggers as instance variablesDisadvantages for declaring loggers as + instance variables
+
    +
  1. Possible to take advantage of repository selectors + even for libraries shared between applications. However, + repository selectors only work if the underlying logging + system is logback-classic. Repository selectors do not + work for the SLF4J+log4j combination. +
  2. +
  3. IOC-friendly
  4. +
+
+
    +
  1. Less common idiom than declaring loggers as static + variables
  2. + +
  3. higher CPU overhead: loggers are retrieved and + assigned for each instance of the hosting class
  4. + +
  5. higher memory overhead: logger declaration will + consume one reference per instance of the hosting class
  6. +
+
+ + +

Explanation

+ +

Static logger members cost a single variable reference for + all instances of the class whereas an instance logger member + will cost a variable reference for every instance of the + class. For simple classes instantiated thousands of times + there might be a noticeable difference. +

+ +

However, more recent logging systems, e.g log4j or logback, + support a distinct logger context for each application running + in the application server. Thus, even if a single copy of + log4j.jar or logback-classic.jar is deployed + in the server, the logging system will be able to differentiate + between applications and offer a distinct logging environment + for each application. +

+ +

More specifically, each time a logger is retrieved by + invoking LoggerFactory.getLogger() method, the + underlying logging system will return an instance appropriate + for the current application. Please note that within the + same application retrieving a logger by a given name + will always return the same logger. For a given name, a + different logger will be returned only for different + applications. +

+ +

If the logger is static, then it will only be retrieved once + when the hosting class is loaded into memory. If the hosting + class is used in only in one application, there is not much to + be concerned about. However, if the hosting class is shared + between several applications, then all instances of the shared + class will log into the context of the application which + happened to first load the shared class into memory - hardly the + behavior expected by the user. +

+ +

Unfortunately, for non-native implementations of the SLF4J + API, namely with slf4j-log4j12, log4j's repository selector will + not be able to do its job properly because slf4j-log4j12, a + non-native SLF4J binding, will store logger instances in a map, + short-circuiting context-dependent logger retrieval. For native + SLF4J implementations, such as logback-classic, repository + selectors will work as expected. +

+ +

The Apache Commons wiki contains an informative + article covering the same question.

+ +

Logger serialization

+ +

Contrary to static variables, instance variables are + serialized by default. As of SLF4J version 1.5.3, logger + instances survive serialization. Thus, serialization of the host + class no longer requires any special action, even when loggers + are declared as instance variables. In previous versions, logger + instances needed to be declared as transient in the + host class.

+ +

Summary

+ +

In summary, declaring logger members as static variables + requires less CPU time and have a slightly smaller memory + footprint. On the other hand, declaring logger members as + instance variables requires more CPU time and have a slighlty + higher memory overhead. However, instance variables make it + possible to create a distinct logger environment for each + application, even for loggers declared in shared + libraries. Perhaps more important than previously mentioned + considerations, instance variables are IOC-friendly whereas + static variables are not. +

+ +

See also related + discussion in the commons-logging wiki. +

+ +
+
+ +
+
Is there a recommended idiom for + declaring a logger in a class? +
+ +
+

The following is the recommended logger declaration + idiom. For reasons explained + above, it is left to the user to determine whether loggers + are declared as static variables or not.

+ +
package some.package;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+      
+public class MyClass {
+  final (static) Logger logger = LoggerFactory.getLogger(MyClass.class);
+  ... etc
+}
+ +

Unfortunately, give that the name of the hosting class is + part of the logger declaration, the above logger declaration + idiom is not is not resistant to cut-and-pasting + between classes. +

+
+
+ + +
+ + diff --git a/slf4j-site/src/site/pages/inde_base.html b/slf4j-site/src/site/pages/inde_base.html index 83bbef9f..2addd7b4 100644 --- a/slf4j-site/src/site/pages/inde_base.html +++ b/slf4j-site/src/site/pages/inde_base.html @@ -1,28 +1,28 @@ - - - - -SLF4J - - - - - - -
- -
- -
- - - - - -
- - + + + + +SLF4J + + + + + + +
+ +
+ +
+ + + + + +
+ + diff --git a/slf4j-site/src/site/pages/index.html b/slf4j-site/src/site/pages/index.html index 764e18f3..28058853 100644 --- a/slf4j-site/src/site/pages/index.html +++ b/slf4j-site/src/site/pages/index.html @@ -1,53 +1,53 @@ - - - - - - SLF4J - - - - - - - -
- - -
- -
- - -

Simple Logging Facade for Java (SLF4J)

- -

The Simple Logging Facade for Java or (SLF4J) serves as a simple - facade or abstraction for various logging frameworks, e.g. - java.util.logging, log4j and logback, allowing the end user to plug - in the desired logging framework at deployment time. -

- -

Before you start using SLF4J, we highly recommend that you read - the two-page SLF4J user manual. -

- -

In case you wish to migrate your Java source files to SLF4J, - consider our migrator tool which can - migrate your project into SLF4J in minutes.

- -

In case an externally-maintained component you depend on uses a - logging API other than SLF4J, such as commons logging, log4j or - j.u.l, have a look at SLF4J's binary-support for legacy APIs. -

- - - -
- - + + + + + + SLF4J + + + + + + + +
+ + +
+ +
+ + +

Simple Logging Facade for Java (SLF4J)

+ +

The Simple Logging Facade for Java or (SLF4J) serves as a simple + facade or abstraction for various logging frameworks, e.g. + java.util.logging, log4j and logback, allowing the end user to plug + in the desired logging framework at deployment time. +

+ +

Before you start using SLF4J, we highly recommend that you read + the two-page SLF4J user manual. +

+ +

In case you wish to migrate your Java source files to SLF4J, + consider our migrator tool which can + migrate your project into SLF4J in minutes.

+ +

In case an externally-maintained component you depend on uses a + logging API other than SLF4J, such as commons logging, log4j or + j.u.l, have a look at SLF4J's binary-support for legacy APIs. +

+ + + +
+ + diff --git a/slf4j-site/src/site/pages/legacy.html b/slf4j-site/src/site/pages/legacy.html index 598b4942..a5ba3768 100644 --- a/slf4j-site/src/site/pages/legacy.html +++ b/slf4j-site/src/site/pages/legacy.html @@ -1,239 +1,239 @@ - - - - - Log4j Bridge - - - - - - - - -
- -
-
- - -

Bridging legacy APIs

- -

Often, some of the components you depend on rely on a logging - API other than SLF4J. You may also assume that these components - will not switch to SLF4J in the immediate future. To deal with - such circumstances, SLF4J ships with several bridging modules - which redirect calls made to log4j, JCL and java.util.logging APIs - to behave as if they were made to the SLF4J API instead. The - figure below illustrates the idea. -

- -

-

- - -

- click to enlarge -

- -

-

- -

Gradual migration to - SLF4J from Jakarta Commons Logging (JCL)

- -

jcl-over-slf4j.jar

- -

To ease migration to SLF4J from JCL, SLF4J distributions - include the jar file jcl-over-slf4j.jar. This jar file is - intended as a drop-in replacement for JCL version 1.1.1. It - implements the public API of JCL but using SLF4J underneath, hence - the name "JCL over SLF4J." -

- -

Our JCL over SLF4J implementation will allow you to migrate to - SLF4J gradually, especially if some of the libraries your software - depends on continue to use JCL for the foreseeable future. You can - immediately enjoy the benefits of SLF4J's reliability and preserve - backward compatibility at the same time. Just replace - commons-logging.jar with - jcl-over-slf4j.jar. Subsequently, the selection of the - underlying logging framework will be done by SLF4J instead of JCL - but without the class loader headaches. The underlying logging - framework can be any of the frameworks supported by SLF4J. -

- -

slf4j-jcl.jar

- -

Some of our users after having switched to SLF4J API realize that - in some contexts the use of JCL is mandatory and their use of SLF4J - can be a problem. For this uncommon but important case, SLF4J offers - a JCL binding, found in the file slf4j-jcl.jar. The JCL - binding will delegate all logging calls made through SLF4J API to - JCL. Thus, if for some reason an existing application must - use JCL, your part of that application can still code against the - SLF4J API in a manner transparent to the larger application - environment. Your choice of SLF4J API will be invisible to the rest - of the application which can continue to use JCL. -

- -

jcl-over-slf4j.jar should not be confused with - slf4j-jcl.jar

- - -

JCL-over-SLF4J, i.e. jcl-over-slf4j.jar, comes in handy - in situations where JCL needs to be supported for backward - compatibility reasons. It can be used to fix problems associated - with JCL, without necessarily adopting the SLF4J API, a decision - which can be deferred to a later time. -

- -

On the other hand, slf4j-jcl.jar is useful - after you have already adopted the SLF4J API for - your component which needs to be embedded in a larger application - environment where JCL is a formal requirement. Your software - component can still use SLF4J API without disrupting the larger - application. Indeed, slf4j-jcl.jar will delegate all - logging decisions to JCL so that the dependency on SLF4J API by your - component will be transparent to the larger whole. -

- -

Please note that jcl-over-slf4j.jar and - slf4j-jcl.jar cannot be deployed at the same time. The - former jar file will cause JCL to delegate the choice of the logging - system to SLF4J and the latter jar file will cause SLF4J to delegate - the choice of the logging system to JCL, resulting in an infinite - loop. -

- - -

Log4j over - SLF4J

- -

SLF4J ship with a module called log4j-over-slf4j. It - allows log4j users to migrate existing applications to SLF4J without - changing a single line of code but simply by replacing the - log4j.jar file with log4j-over-slf4j.jar, as - described below. -

- -

How does it work?

- -

The log4j-over-slf4j module contains replacements of most widely - used log4j classes, namely org.apache.log4j.Category, - org.apache.log4j.Logger, - org.apache.log4j.Priority, - org.apache.log4j.Level, - org.apache.log4j.MDC, and - org.apache.log4j.BasicConfigurator. These replacement - classes redirect all work to their corresponding SLF4J classes. -

- -

To use log4j-over-slf4j in your own application, the first step - is to locate and then to replace log4j.jar with - log4j-over-slf4j.jar. Note that you still need an SLF4J - binding and its dependencies for log4j-over-slf4j to work properly. -

- -

In most situations, replacing a jar file is all it takes in - order to migrate from log4j to SLF4J. -

- -

Note that as a result of this migration, log4j configuration - files will no longer be picked up. If you need to migrate your - log4j.properties file to logback, the log4j translator might - be of help. For configuring logback, please refer to its manual. -

- -

When does it not work?

- -

The log4j-over-slf4j module will not work when the - application calls log4j components that are not present in the - bridge. For example, direct references to log4j appenders, - filters or PropertyConfigurator are not supported by - log4j-over-slf4j. While the number of cases where - log4j-over-slf4j is insufficient is not completely negligible, in - the vast majority of cases where log4j is configured through a - configuration file, be it log4j.properties or - log4j.xml, log4j-over-slf4j is enough in order to migrate - your application to SLF4J. -

- -

What about the overhead?

- -

There overhead of using log4j-over-slf4j instead of log4j - directly is relatively small. Given that log4j-over-slf4j - immediately delegates all work to SLF4J, the CPU overhead should be - negligible, in the order of a few nanoseconds. There is a - memory overhead corresponding to an entry in a hashmap per logger, - which should be usually acceptable even for very large applications - consisting of several thousand loggers. Moreover, if you choose - logback as your underlying logging system, and given that logback is - both much faster and more memory-efficient than log4j, the gains - made by using logback should compensate for the overhead of using - log4j-over-slf4j instead of log4j directly. -

- -

log4j-over-slf4j.jar and slf4j-logj12.jar cannot be present - simultaneously -

- -

The presence of slf4j-logj12.jar, that is the log4j - binding for SLF4J, will force all SLF4J calls to be delegated to - log4j. The presence of log4j-over-slf4j.jar will in turn - delegate all log4j API calls to their SLF4J equivalents. If both are - present simultaneously, slf4j calls will be delegated to log4j, and - log4j calls redirected to SLF4j, resulting in an endless loop. -

- -

JUL to SLF4J

- -

The jul-to-slf4j module includes a jul handler, namely - SLF4JBridgeHandler, that routes all incoming jul records to the - SLF4j API. Please see SLF4JBridgeHandler - javadocs for usage instructions. -

- -

Contrary to other bridging modules such as jcl-over-slf4j and - log4j-over-slf4j, which re-implement JCL and respectively log4j, - the jul-to-slf4j modules does not re-implement the - java.util.logging package because packages under the java.* - namespace cannot be replaced. Instead, translates LogRecord - object into its SLF4J equivalent on each logging event. Please - note this traslation process incurs the cost of constructing a - LogRecord instance regardless of whether the SLF4J - logger is disabled for the given level or nor. Consequently, - j.u.l. to SLF4J translation can seriously impact on the cost of - disabled logging statements (60 fold increase) and a measurable - impact on enabled log statements (20% overall increase). -

- -

If application performance is a concern, then use of - SLF4JBridgeHandler is appropriate only if few j.u.l. logging - statements are in play.

- - -

jul-to-slf4j.jar and slf4j-jdk14.jar cannot be present - simultaneously -

- -

The presence of slf4j-jdk14.jar, that is the jul binding for - SLF4J, will force SLF4J calls to be delegated to jul. On the other - hand, the presence of jul-to-slf4j.jar, plus the installation of - SLF4JBridgeHandler, by invoking "SLF4JBridgeHandler.install()" will - route jul records to SLF4J. Thus, if both jar are present - simultaneously (and SLF4JBridgeHandler is installed), slf4j calls - will be delegated to jul and jul records will be routed to SLF4J, - resulting in an endless loop. -

- - - -
- - + + + + + Log4j Bridge + + + + + + + + +
+ +
+
+ + +

Bridging legacy APIs

+ +

Often, some of the components you depend on rely on a logging + API other than SLF4J. You may also assume that these components + will not switch to SLF4J in the immediate future. To deal with + such circumstances, SLF4J ships with several bridging modules + which redirect calls made to log4j, JCL and java.util.logging APIs + to behave as if they were made to the SLF4J API instead. The + figure below illustrates the idea. +

+ +

+

+ + +

+ click to enlarge +

+ +

+

+ +

Gradual migration to + SLF4J from Jakarta Commons Logging (JCL)

+ +

jcl-over-slf4j.jar

+ +

To ease migration to SLF4J from JCL, SLF4J distributions + include the jar file jcl-over-slf4j.jar. This jar file is + intended as a drop-in replacement for JCL version 1.1.1. It + implements the public API of JCL but using SLF4J underneath, hence + the name "JCL over SLF4J." +

+ +

Our JCL over SLF4J implementation will allow you to migrate to + SLF4J gradually, especially if some of the libraries your software + depends on continue to use JCL for the foreseeable future. You can + immediately enjoy the benefits of SLF4J's reliability and preserve + backward compatibility at the same time. Just replace + commons-logging.jar with + jcl-over-slf4j.jar. Subsequently, the selection of the + underlying logging framework will be done by SLF4J instead of JCL + but without the class loader headaches. The underlying logging + framework can be any of the frameworks supported by SLF4J. +

+ +

slf4j-jcl.jar

+ +

Some of our users after having switched to SLF4J API realize that + in some contexts the use of JCL is mandatory and their use of SLF4J + can be a problem. For this uncommon but important case, SLF4J offers + a JCL binding, found in the file slf4j-jcl.jar. The JCL + binding will delegate all logging calls made through SLF4J API to + JCL. Thus, if for some reason an existing application must + use JCL, your part of that application can still code against the + SLF4J API in a manner transparent to the larger application + environment. Your choice of SLF4J API will be invisible to the rest + of the application which can continue to use JCL. +

+ +

jcl-over-slf4j.jar should not be confused with + slf4j-jcl.jar

+ + +

JCL-over-SLF4J, i.e. jcl-over-slf4j.jar, comes in handy + in situations where JCL needs to be supported for backward + compatibility reasons. It can be used to fix problems associated + with JCL, without necessarily adopting the SLF4J API, a decision + which can be deferred to a later time. +

+ +

On the other hand, slf4j-jcl.jar is useful + after you have already adopted the SLF4J API for + your component which needs to be embedded in a larger application + environment where JCL is a formal requirement. Your software + component can still use SLF4J API without disrupting the larger + application. Indeed, slf4j-jcl.jar will delegate all + logging decisions to JCL so that the dependency on SLF4J API by your + component will be transparent to the larger whole. +

+ +

Please note that jcl-over-slf4j.jar and + slf4j-jcl.jar cannot be deployed at the same time. The + former jar file will cause JCL to delegate the choice of the logging + system to SLF4J and the latter jar file will cause SLF4J to delegate + the choice of the logging system to JCL, resulting in an infinite + loop. +

+ + +

Log4j over + SLF4J

+ +

SLF4J ship with a module called log4j-over-slf4j. It + allows log4j users to migrate existing applications to SLF4J without + changing a single line of code but simply by replacing the + log4j.jar file with log4j-over-slf4j.jar, as + described below. +

+ +

How does it work?

+ +

The log4j-over-slf4j module contains replacements of most widely + used log4j classes, namely org.apache.log4j.Category, + org.apache.log4j.Logger, + org.apache.log4j.Priority, + org.apache.log4j.Level, + org.apache.log4j.MDC, and + org.apache.log4j.BasicConfigurator. These replacement + classes redirect all work to their corresponding SLF4J classes. +

+ +

To use log4j-over-slf4j in your own application, the first step + is to locate and then to replace log4j.jar with + log4j-over-slf4j.jar. Note that you still need an SLF4J + binding and its dependencies for log4j-over-slf4j to work properly. +

+ +

In most situations, replacing a jar file is all it takes in + order to migrate from log4j to SLF4J. +

+ +

Note that as a result of this migration, log4j configuration + files will no longer be picked up. If you need to migrate your + log4j.properties file to logback, the log4j translator might + be of help. For configuring logback, please refer to its manual. +

+ +

When does it not work?

+ +

The log4j-over-slf4j module will not work when the + application calls log4j components that are not present in the + bridge. For example, direct references to log4j appenders, + filters or PropertyConfigurator are not supported by + log4j-over-slf4j. While the number of cases where + log4j-over-slf4j is insufficient is not completely negligible, in + the vast majority of cases where log4j is configured through a + configuration file, be it log4j.properties or + log4j.xml, log4j-over-slf4j is enough in order to migrate + your application to SLF4J. +

+ +

What about the overhead?

+ +

There overhead of using log4j-over-slf4j instead of log4j + directly is relatively small. Given that log4j-over-slf4j + immediately delegates all work to SLF4J, the CPU overhead should be + negligible, in the order of a few nanoseconds. There is a + memory overhead corresponding to an entry in a hashmap per logger, + which should be usually acceptable even for very large applications + consisting of several thousand loggers. Moreover, if you choose + logback as your underlying logging system, and given that logback is + both much faster and more memory-efficient than log4j, the gains + made by using logback should compensate for the overhead of using + log4j-over-slf4j instead of log4j directly. +

+ +

log4j-over-slf4j.jar and slf4j-logj12.jar cannot be present + simultaneously +

+ +

The presence of slf4j-logj12.jar, that is the log4j + binding for SLF4J, will force all SLF4J calls to be delegated to + log4j. The presence of log4j-over-slf4j.jar will in turn + delegate all log4j API calls to their SLF4J equivalents. If both are + present simultaneously, slf4j calls will be delegated to log4j, and + log4j calls redirected to SLF4j, resulting in an endless loop. +

+ +

JUL to SLF4J

+ +

The jul-to-slf4j module includes a jul handler, namely + SLF4JBridgeHandler, that routes all incoming jul records to the + SLF4j API. Please see SLF4JBridgeHandler + javadocs for usage instructions. +

+ +

Contrary to other bridging modules such as jcl-over-slf4j and + log4j-over-slf4j, which re-implement JCL and respectively log4j, + the jul-to-slf4j modules does not re-implement the + java.util.logging package because packages under the java.* + namespace cannot be replaced. Instead, translates LogRecord + object into its SLF4J equivalent on each logging event. Please + note this traslation process incurs the cost of constructing a + LogRecord instance regardless of whether the SLF4J + logger is disabled for the given level or nor. Consequently, + j.u.l. to SLF4J translation can seriously impact on the cost of + disabled logging statements (60 fold increase) and a measurable + impact on enabled log statements (20% overall increase). +

+ +

If application performance is a concern, then use of + SLF4JBridgeHandler is appropriate only if few j.u.l. logging + statements are in play.

+ + +

jul-to-slf4j.jar and slf4j-jdk14.jar cannot be present + simultaneously +

+ +

The presence of slf4j-jdk14.jar, that is the jul binding for + SLF4J, will force SLF4J calls to be delegated to jul. On the other + hand, the presence of jul-to-slf4j.jar, plus the installation of + SLF4JBridgeHandler, by invoking "SLF4JBridgeHandler.install()" will + route jul records to SLF4J. Thus, if both jar are present + simultaneously (and SLF4JBridgeHandler is installed), slf4j calls + will be delegated to jul and jul records will be routed to SLF4J, + resulting in an endless loop. +

+ + + +
+ + diff --git a/slf4j-site/src/site/pages/license.html b/slf4j-site/src/site/pages/license.html index d4823004..8eb148c9 100644 --- a/slf4j-site/src/site/pages/license.html +++ b/slf4j-site/src/site/pages/license.html @@ -1,68 +1,68 @@ - - - - - - SLF4J License - - - - - - -
- -
-
- - -

Licensing terms for SLF4J

- -

SLF4J source code and binaries are distributed under the - MIT license. -

- -
- Copyright (c) 2004-2008 QOS.ch - All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -
- -

These terms are identical to those of the MIT License, - also called the X License or the X11 License, which is a simple, - permissive non-copyleft free software license. It is deemed - compatible with virtually all types of licenses, commercial or - otherwise. In particular, the Free Software Foundation has declared - it compatible with - GNU GPL. It is also known to be approved by the Apache Software - Foundation as compatible with Apache Software License. -

- - - - -
- - + + + + + + SLF4J License + + + + + + +
+ +
+
+ + +

Licensing terms for SLF4J

+ +

SLF4J source code and binaries are distributed under the + MIT license. +

+ +
+ Copyright (c) 2004-2008 QOS.ch + All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +
+ +

These terms are identical to those of the MIT License, + also called the X License or the X11 License, which is a simple, + permissive non-copyleft free software license. It is deemed + compatible with virtually all types of licenses, commercial or + otherwise. In particular, the Free Software Foundation has declared + it compatible with + GNU GPL. It is also known to be approved by the Apache Software + Foundation as compatible with Apache Software License. +

+ + + + +
+ + diff --git a/slf4j-site/src/site/pages/localization.html b/slf4j-site/src/site/pages/localization.html index 56b6c0bc..94a078f0 100644 --- a/slf4j-site/src/site/pages/localization.html +++ b/slf4j-site/src/site/pages/localization.html @@ -1,158 +1,158 @@ - - - - - - Localization - - - - - - - - - -
- - -
- -
- - -

Localization support

- -

A discussion - on the slf4j-dev mailing list spawned an open-source project - called CAL10N or Compiler - Assisted Localization. As its name indicates, CAL10N - focuses on the issue of localization/internationalization in Java - applications. -

- -

The org.slf4j.cal10n package which ships with - slf4j-ext-${project.version}.jar adds an extremely thin - layer on top of CALI0N to offer localized logging.

- - -

Once you have a handle on an IMessageConveyor - instance, you can create a LocLoggerFactory, - which in turn can create LocLogger - instances capable of doing localized logging. -

- - -

Let assume that you have defined localized message your - application. In accordance with the CAL10N's philopshopy, you have - the declared the keys for those messages in the enum type - Production.

- - -
import ch.qos.cal10n.LocaleData;
-import ch.qos.cal10n.Locale;
-import ch.qos.cal10n.BaseName;
-
-@BaseName("production")
-@LocaleData( { @Locale("en_UK"), @Locale("ja_JP") })
-public enum Production  {
-  APPLICATION_STARTED,
-  APPLICATION_STOPPED,
-  ...
-  DB_CONNECTION,
-  DB_CONNECTION_FAILURE;
-}
- -

It is assumed that you have created appropriate bundle file for - the various locales "en_UK" and "ja_JP" as appropriate. Here is a - sample bundle for the "en_UK" locale. -

- - -
APPLICATION_STARTED=Application {0} has started.
-APPLICATION_STOPPED=Application {0} has stopped.
-... 
- -

Then, you - can instantiate a IMessageCoveyor, inject it into a - LogLoggerFactory, retreive multiple - LogLogger instances by name and log away, as the next - sample code illustrates. -

- - -
import java.util.Locale;
-
-import org.slf4j.cal10n.LocLogger;
-import org.slf4j.cal10n.LocLoggerFactory;
-
-import ch.qos.cal10n.IMessageConveyor;
-import ch.qos.cal10n.MessageConveyor;
-
-public class MyApplication {
-
-  // create a message conveyor for a given locale 
-  IMessageConveyor  messageConveyor = new MessageConveyor(Locale.UK);
-  
-  // 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, "fooApp");
-    // ..
-  }
-  
-  public void applicationStop() {
-    locLogger.info(Production.APPLICATION_STOPPED, "fooApp");
-    // ...
-  }
-}
- -

Assuming the resource bundle - production_en_UK.properties exists, and the underlying - logging framework is enabled for the info level, log messages will - be output in UK English. -

- -

Note that a LogLogger is a regular SLF4J logger - with additional methods supporting localization. For those - additional methods which take an enum as first parameter, - LogLogger follows the standard Java convention for - parameter substitution as defined by the java.text.MessageFormat - class. For non-localized logs, which take a String as first - parameter, LogLogger follows the {} convention, as - customary for all org.slf4j.Logger implementations. -

- -

Here is an example illustrating the difference.

- -
import ...;
-public class MyApplication {
-
-  IMessageConveyor  messageConveyor = new MessageConveyor(Locale.UK);
-  LocLoggerFactory llFactory_uk = new LocLoggerFactory(messageConveyor);
-  LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass());
-
-  public void someMethod() {
-    // follows the MessageFormat convention
-    locLogger.info(Production.APPLICATION_STARTED, "fooApp");
-
-   // follows the {} convention
-   logLogger.ingo("Hello {}", name);   
-   ...  
-  }  
-}
- -
- - + + + + + + Localization + + + + + + + + + +
+ + +
+ +
+ + +

Localization support

+ +

A discussion + on the slf4j-dev mailing list spawned an open-source project + called CAL10N or Compiler + Assisted Localization. As its name indicates, CAL10N + focuses on the issue of localization/internationalization in Java + applications. +

+ +

The org.slf4j.cal10n package which ships with + slf4j-ext-${project.version}.jar adds an extremely thin + layer on top of CALI0N to offer localized logging.

+ + +

Once you have a handle on an IMessageConveyor + instance, you can create a LocLoggerFactory, + which in turn can create LocLogger + instances capable of doing localized logging. +

+ + +

Let assume that you have defined localized message your + application. In accordance with the CAL10N's philopshopy, you have + the declared the keys for those messages in the enum type + Production.

+ + +
import ch.qos.cal10n.LocaleData;
+import ch.qos.cal10n.Locale;
+import ch.qos.cal10n.BaseName;
+
+@BaseName("production")
+@LocaleData( { @Locale("en_UK"), @Locale("ja_JP") })
+public enum Production  {
+  APPLICATION_STARTED,
+  APPLICATION_STOPPED,
+  ...
+  DB_CONNECTION,
+  DB_CONNECTION_FAILURE;
+}
+ +

It is assumed that you have created appropriate bundle file for + the various locales "en_UK" and "ja_JP" as appropriate. Here is a + sample bundle for the "en_UK" locale. +

+ + +
APPLICATION_STARTED=Application {0} has started.
+APPLICATION_STOPPED=Application {0} has stopped.
+... 
+ +

Then, you + can instantiate a IMessageCoveyor, inject it into a + LogLoggerFactory, retreive multiple + LogLogger instances by name and log away, as the next + sample code illustrates. +

+ + +
import java.util.Locale;
+
+import org.slf4j.cal10n.LocLogger;
+import org.slf4j.cal10n.LocLoggerFactory;
+
+import ch.qos.cal10n.IMessageConveyor;
+import ch.qos.cal10n.MessageConveyor;
+
+public class MyApplication {
+
+  // create a message conveyor for a given locale 
+  IMessageConveyor  messageConveyor = new MessageConveyor(Locale.UK);
+  
+  // 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, "fooApp");
+    // ..
+  }
+  
+  public void applicationStop() {
+    locLogger.info(Production.APPLICATION_STOPPED, "fooApp");
+    // ...
+  }
+}
+ +

Assuming the resource bundle + production_en_UK.properties exists, and the underlying + logging framework is enabled for the info level, log messages will + be output in UK English. +

+ +

Note that a LogLogger is a regular SLF4J logger + with additional methods supporting localization. For those + additional methods which take an enum as first parameter, + LogLogger follows the standard Java convention for + parameter substitution as defined by the java.text.MessageFormat + class. For non-localized logs, which take a String as first + parameter, LogLogger follows the {} convention, as + customary for all org.slf4j.Logger implementations. +

+ +

Here is an example illustrating the difference.

+ +
import ...;
+public class MyApplication {
+
+  IMessageConveyor  messageConveyor = new MessageConveyor(Locale.UK);
+  LocLoggerFactory llFactory_uk = new LocLoggerFactory(messageConveyor);
+  LocLogger locLogger = llFactory_uk.getLocLogger(this.getClass());
+
+  public void someMethod() {
+    // follows the MessageFormat convention
+    locLogger.info(Production.APPLICATION_STARTED, "fooApp");
+
+   // follows the {} convention
+   logLogger.ingo("Hello {}", name);   
+   ...  
+  }  
+}
+ +
+ + diff --git a/slf4j-site/src/site/pages/mailing-lists.html b/slf4j-site/src/site/pages/mailing-lists.html index 84b262b6..e7cb9620 100644 --- a/slf4j-site/src/site/pages/mailing-lists.html +++ b/slf4j-site/src/site/pages/mailing-lists.html @@ -1,127 +1,127 @@ - - - - - - SLF4J - - - - - - -
- -
-
- -

SLF4J Mailing Lists

- -

A mailing list is an electronic discussion forum that anyone can - subscribe to. When someone sends an email message to the mailing - list, a copy of that message is broadcast to everyone who is - subscribed to that mailing list. Mailing lists provide a simple and - effective communication mechanism. With potentially thousands of - subscribers, there is a common set of etiquette guidelines that you - should observe. Please keep on reading. -

- -

Respect the mailing list type

- -

The "User" lists where you can send questions and comments about - configuration, setup, usage and other "user" types of questions. - The "Developer" lists where you can send questions and comments - about the actual software source code and general "development" - types of questions. -

- -

Some questions are appropriate for posting on both the "user" and - the "developer" lists. In this case, pick one and only one. Do not - cross post. -

- -

Please do your best to ensure that you are not sending HTML or - "Stylelized" email to the list. If you are using Outlook or Outlook - Express or Eudora, chances are that you are sending HTML email by - default. There is usually a setting that will allow you to send - "Plain Text" email. -

- - - - - -

slf4j-announcements list

- -

- Low Traffic: - Subscribe | - Unsubscribe -
- Archives: - Pipermail | - MARC -

-

The announcements list is reserved for important SLF4J API - related announcements. As such, the traffic on this list is - guaranteed to be very low. -

- -

Given that implementations are expected to statically bind with - the SLF4J API, we recommend that any implementor of the SLF4J API - be subscribed at least to the announcements list. -

- -

slf4j-user list

- -

- Medium Traffic: - Subscribe | - Unsubscribe -
- Archives: - Pipermail | - Gmane | - MARC | - Nabble | - MailArchive - - -

- -

This is the list for users of slf4j. It is also a good forum for - asking questions about how slf4j works, and how it can be - used. SLF4J developers are usually subscribed to to this list in - order to offer support.

- - -

slf4j-dev list

- -

- Medium Traffic: - Subscribe | - Unsubscribe -
- Archives: - Pipermail | - Gmane | - MARC | - Nabble | - MailArchive -

-

 

- - -
- - + + + + + + SLF4J + + + + + + +
+ +
+
+ +

SLF4J Mailing Lists

+ +

A mailing list is an electronic discussion forum that anyone can + subscribe to. When someone sends an email message to the mailing + list, a copy of that message is broadcast to everyone who is + subscribed to that mailing list. Mailing lists provide a simple and + effective communication mechanism. With potentially thousands of + subscribers, there is a common set of etiquette guidelines that you + should observe. Please keep on reading. +

+ +

Respect the mailing list type

+ +

The "User" lists where you can send questions and comments about + configuration, setup, usage and other "user" types of questions. + The "Developer" lists where you can send questions and comments + about the actual software source code and general "development" + types of questions. +

+ +

Some questions are appropriate for posting on both the "user" and + the "developer" lists. In this case, pick one and only one. Do not + cross post. +

+ +

Please do your best to ensure that you are not sending HTML or + "Stylelized" email to the list. If you are using Outlook or Outlook + Express or Eudora, chances are that you are sending HTML email by + default. There is usually a setting that will allow you to send + "Plain Text" email. +

+ + + + + +

slf4j-announcements list

+ +

+ Low Traffic: + Subscribe | + Unsubscribe +
+ Archives: + Pipermail | + MARC +

+

The announcements list is reserved for important SLF4J API + related announcements. As such, the traffic on this list is + guaranteed to be very low. +

+ +

Given that implementations are expected to statically bind with + the SLF4J API, we recommend that any implementor of the SLF4J API + be subscribed at least to the announcements list. +

+ +

slf4j-user list

+ +

+ Medium Traffic: + Subscribe | + Unsubscribe +
+ Archives: + Pipermail | + Gmane | + MARC | + Nabble | + MailArchive + + +

+ +

This is the list for users of slf4j. It is also a good forum for + asking questions about how slf4j works, and how it can be + used. SLF4J developers are usually subscribed to to this list in + order to offer support.

+ + +

slf4j-dev list

+ +

+ Medium Traffic: + Subscribe | + Unsubscribe +
+ Archives: + Pipermail | + Gmane | + MARC | + Nabble | + MailArchive +

+

 

+ + +
+ + diff --git a/slf4j-site/src/site/pages/manual.html b/slf4j-site/src/site/pages/manual.html index 8b9b58e2..6d1b1dcc 100644 --- a/slf4j-site/src/site/pages/manual.html +++ b/slf4j-site/src/site/pages/manual.html @@ -1,341 +1,341 @@ - - - - - - SLF4J Manual - - - - - - - - -
- -
-
- - -

SLF4J user manual

- -

The Simple Logging Facade for Java or (SLF4J) serves as a - simple facade or abstraction for various logging frameworks, e.g. - java.util.logging, log4j and logback, allowing the end-user to - plug in the desired logging framework at deployment time. -

- -

- Hello World -

- -

In accordance with programming tradition, here is an example - illustrating the simplest way to output "Hello world" using SLF4J. - It begins by getting a logger with the name "HelloWorld". This - logger is in turn used to log the message "Hello World". -

- -
import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class HelloWorld {
-  public static void main(String[] args) {
-    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
-    logger.info("Hello World");
-  }
-}
- -

To run this example, you first need to download the slf4j distribution, and - then to unpack it. Once that is done, add these two jar files to - your class path:

- -
    -
  • slf4j-api-${project.version}.jar
  • -
  • slf4j-simple-${project.version}.jar
  • -
- -

Compiling and running HelloWorld will result in the - following output being printed on the console.

- -
0 [main] INFO HelloWorld - Hello World
- -

- Typical usage - pattern -

- -

The sample code below illustrates the typical usage pattern - for SLF4J. Note the use of {}-placeholders on line 15. See the - question "What is the - fastest way of logging?" in the FAQ for more details. -

- -

- -
 1: import org.slf4j.Logger;
- 2: import org.slf4j.LoggerFactory;
- 3: 
- 4: public class Wombat {
- 5:  
- 6:   final Logger logger = LoggerFactory.getLogger(Wombat.class);
- 7:   Integer t;
- 8:   Integer oldT;
- 9:
-10:   public void setTemperature(Integer temperature) {
-11:    
-12:     oldT = t;        
-13:     t = temperature;
-14:
-15:     logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);
-16:
-17:     if(temperature.intValue() > 50) {
-18:       logger.info("Temperature has risen above 50 degrees.");
-19:     }
-20:   }
-21: } 
- - - -

Binding with a logging - framework at deployment time

- -

As mentioned previously, SLF4J supports multiple logging - frameworks. The SLF4J distribution ships with several jar files - referred to as "SLF4J bindings".

- -
- -
slf4j-nop-${project.version}.jar
-
Binding for NOP, - silently discarding all logging.

- - -
slf4j-simple-${project.version}.jar
-
Binding for Simple - implementation, which outputs all events to - System.err. Only messages of level INFO and higher are - printed. This binding may be useful in the context of small - applications.

- -
slf4j-log4j12-${project.version}.jar -
-
Binding for log4j - version 1.2, a widely used logging framework. You also - need to place log4j.jar on your class path.

- -
slf4j-jdk14-${project.version}.jar
-
Binding for java.util.logging, also referred to as JDK 1.4 - logging (examples)

- -
slf4j-jcl-${project.version}.jar
- -
Binding for Jakarta Commons - Logging. This binding will delegate all SLF4J logging to - JCL.

-

-
- -

There are also SLF4J bindings external to the SLF4J project, - e.g. logback which - implements SLF4J natively. Logback's - - ch.qos.logback.classic.Logger class is a direct - implementation of SLF4J's - - org.slf4j.Logger interface. Thus, using SLF4J - in conjunction with logback involves strictly zero memory and - computational overhead. -

- - -

To switch logging frameworks, just replace slf4j bindings on - your class path. For example, to switch from java.util.logging - to log4j, just replace slf4j-jdk14-${project.version}.jar with - slf4j-log4j12-${project.version}.jar. -

- -

SLF4J does not rely on any special class loader machinery. In - fact, the each SLF4J binding is hardwired at compile - time to use one and only one specific logging framework. - For example, the slf4j-log12-${project.version}.jar binding is - bound at compile time to use log4j. In your code, in addition - to slf4j-api-${project.version}.jar, you simply drop - one and only one binding of your choice onto the - appropriate class path location. Do not place more than one - binding on your class path. Here is a graphical illustration of - the general idea. -

- -

 

- -

- click to enlarge -

- -

 

- - -

The SLF4J interfaces and their various adapters are extremely - simple. Most developers familiar with the Java language should - be able to read and fully understand the code in less than one - hour. No knowledge of class loaders is necessary as SLF4J does - not make use nor does it directly access any class loaders. As a - consequence, SLF4J suffers from none of the class loader - problems or memory leaks observed with Jakarta Commons Logging - (JCL). -

- -

Hopefully, the simplicity of the SLF4J interfaces and the - deployment model will make it easy for developers of other - logging frameworks to conform to the SLF4J model. -

- -

Libraries

- -

Authors of widely-distributed components and libraries may - code against the SLF4J interface in order to avoid imposing an - logging framework on the end-user of the component or library. - He or she may choose the desired logging framework at deployment - time by inserting the desired slf4j binding on the classpath, - which may be changed later by replacing an existing binding with - another on the class path and restarting the application. This - approach has proven to be simple and very robust. -

- - -

Consolidate - logging via SLF4J

- -

Often times, a given project will depend on various - components which rely on logging APIs other than SLF4J. It is - common to find projects depending on a combination of JCL, - java.util.logging, log4j and SLF4J. It then becomes desirable to - consolidate logging through a single channel. SLF4J caters for - this common use-case by providing bridging modules for JCL, - java.util.logging and log4j. For more details, please refer to - the page on Bridging legacy - APIs. -

- -

Mapped Diagnostic Context (MDC) - support

-

"Mapped Diagnostic Context" is essentially a map maintained by the - logging framework where the application can provided key-value pairs, - which can then be inserted by the logging framework in log messages.

- -

SLF4J supports MDC, or mapped diagnostic context. If the - underlying logging framework offers MDC functionality, then - SLF4J will delegate to the underlying framework's MDC. Note that - at this time, only log4j and logback offer MDC functionality. If - the underlying framework does not offer MDC, for example - java.util.logging, then SLF4J will still store MDC data but the - information therein will need to be retrieved by custom user - code.

- -

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

- -

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

- - - -

Executive - summary -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AdvantageDescription
Select your logging framework at deployment timeThe desired logging framework can be plugged in at - deployment time by inserting the appropriate jar file - (binding) on your class path. -
Fail-fast operationDue to the way that classes are loaded by the JVM, the - framework binding will be verified automatically very early - on. SLF4J will abort execution with a warning if no binding - is present. -
Bindings for popular logging frameworks - SLF4J supports popular logging frameworks, namely log4j, - java.util.logging, Simple logging and NOP. The logback project supports - SLF4J natively.
Bridging legacy logging APIs -

The implementation of JCL over SLF4J, i.e - jcl-over-slf4j.jar, will allow your project to - migrate to SLF4J piecemeal, without breaking compatibility - with existing software using JCL. Similarly, - log4j-over-slf4j.jar and jul-to-slf4j modules will allow - you to redirect log4j and respectively java.util.logging - calls to SLF4J. See the page on Bridging legacy APIs for more - details. -

-
Migrate your source codeThe slf4j-migrator utility - can help you migrate your source to use SLF4J. -
Support for parameterized log messagesAll SLF4J bindings support parameterized log messages - with significantly improved performance - results.
- - - -
- - + + + + + + SLF4J Manual + + + + + + + + +
+ +
+
+ + +

SLF4J user manual

+ +

The Simple Logging Facade for Java or (SLF4J) serves as a + simple facade or abstraction for various logging frameworks, e.g. + java.util.logging, log4j and logback, allowing the end-user to + plug in the desired logging framework at deployment time. +

+ +

+ Hello World +

+ +

In accordance with programming tradition, here is an example + illustrating the simplest way to output "Hello world" using SLF4J. + It begins by getting a logger with the name "HelloWorld". This + logger is in turn used to log the message "Hello World". +

+ +
import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class HelloWorld {
+  public static void main(String[] args) {
+    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
+    logger.info("Hello World");
+  }
+}
+ +

To run this example, you first need to download the slf4j distribution, and + then to unpack it. Once that is done, add these two jar files to + your class path:

+ +
    +
  • slf4j-api-${project.version}.jar
  • +
  • slf4j-simple-${project.version}.jar
  • +
+ +

Compiling and running HelloWorld will result in the + following output being printed on the console.

+ +
0 [main] INFO HelloWorld - Hello World
+ +

+ Typical usage + pattern +

+ +

The sample code below illustrates the typical usage pattern + for SLF4J. Note the use of {}-placeholders on line 15. See the + question "What is the + fastest way of logging?" in the FAQ for more details. +

+ +

+ +
 1: import org.slf4j.Logger;
+ 2: import org.slf4j.LoggerFactory;
+ 3: 
+ 4: public class Wombat {
+ 5:  
+ 6:   final Logger logger = LoggerFactory.getLogger(Wombat.class);
+ 7:   Integer t;
+ 8:   Integer oldT;
+ 9:
+10:   public void setTemperature(Integer temperature) {
+11:    
+12:     oldT = t;        
+13:     t = temperature;
+14:
+15:     logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);
+16:
+17:     if(temperature.intValue() > 50) {
+18:       logger.info("Temperature has risen above 50 degrees.");
+19:     }
+20:   }
+21: } 
+ + + +

Binding with a logging + framework at deployment time

+ +

As mentioned previously, SLF4J supports multiple logging + frameworks. The SLF4J distribution ships with several jar files + referred to as "SLF4J bindings".

+ +
+ +
slf4j-nop-${project.version}.jar
+
Binding for NOP, + silently discarding all logging.

+ + +
slf4j-simple-${project.version}.jar
+
Binding for Simple + implementation, which outputs all events to + System.err. Only messages of level INFO and higher are + printed. This binding may be useful in the context of small + applications.

+ +
slf4j-log4j12-${project.version}.jar +
+
Binding for log4j + version 1.2, a widely used logging framework. You also + need to place log4j.jar on your class path.

+ +
slf4j-jdk14-${project.version}.jar
+
Binding for java.util.logging, also referred to as JDK 1.4 + logging (examples)

+ +
slf4j-jcl-${project.version}.jar
+ +
Binding for Jakarta Commons + Logging. This binding will delegate all SLF4J logging to + JCL.

+

+
+ +

There are also SLF4J bindings external to the SLF4J project, + e.g. logback which + implements SLF4J natively. Logback's + + ch.qos.logback.classic.Logger class is a direct + implementation of SLF4J's + + org.slf4j.Logger interface. Thus, using SLF4J + in conjunction with logback involves strictly zero memory and + computational overhead. +

+ + +

To switch logging frameworks, just replace slf4j bindings on + your class path. For example, to switch from java.util.logging + to log4j, just replace slf4j-jdk14-${project.version}.jar with + slf4j-log4j12-${project.version}.jar. +

+ +

SLF4J does not rely on any special class loader machinery. In + fact, the each SLF4J binding is hardwired at compile + time to use one and only one specific logging framework. + For example, the slf4j-log12-${project.version}.jar binding is + bound at compile time to use log4j. In your code, in addition + to slf4j-api-${project.version}.jar, you simply drop + one and only one binding of your choice onto the + appropriate class path location. Do not place more than one + binding on your class path. Here is a graphical illustration of + the general idea. +

+ +

 

+ +

+ click to enlarge +

+ +

 

+ + +

The SLF4J interfaces and their various adapters are extremely + simple. Most developers familiar with the Java language should + be able to read and fully understand the code in less than one + hour. No knowledge of class loaders is necessary as SLF4J does + not make use nor does it directly access any class loaders. As a + consequence, SLF4J suffers from none of the class loader + problems or memory leaks observed with Jakarta Commons Logging + (JCL). +

+ +

Hopefully, the simplicity of the SLF4J interfaces and the + deployment model will make it easy for developers of other + logging frameworks to conform to the SLF4J model. +

+ +

Libraries

+ +

Authors of widely-distributed components and libraries may + code against the SLF4J interface in order to avoid imposing an + logging framework on the end-user of the component or library. + He or she may choose the desired logging framework at deployment + time by inserting the desired slf4j binding on the classpath, + which may be changed later by replacing an existing binding with + another on the class path and restarting the application. This + approach has proven to be simple and very robust. +

+ + +

Consolidate + logging via SLF4J

+ +

Often times, a given project will depend on various + components which rely on logging APIs other than SLF4J. It is + common to find projects depending on a combination of JCL, + java.util.logging, log4j and SLF4J. It then becomes desirable to + consolidate logging through a single channel. SLF4J caters for + this common use-case by providing bridging modules for JCL, + java.util.logging and log4j. For more details, please refer to + the page on Bridging legacy + APIs. +

+ +

Mapped Diagnostic Context (MDC) + support

+

"Mapped Diagnostic Context" is essentially a map maintained by the + logging framework where the application can provided key-value pairs, + which can then be inserted by the logging framework in log messages.

+ +

SLF4J supports MDC, or mapped diagnostic context. If the + underlying logging framework offers MDC functionality, then + SLF4J will delegate to the underlying framework's MDC. Note that + at this time, only log4j and logback offer MDC functionality. If + the underlying framework does not offer MDC, for example + java.util.logging, then SLF4J will still store MDC data but the + information therein will need to be retrieved by custom user + code.

+ +

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

+ +

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

+ + + +

Executive + summary +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AdvantageDescription
Select your logging framework at deployment timeThe desired logging framework can be plugged in at + deployment time by inserting the appropriate jar file + (binding) on your class path. +
Fail-fast operationDue to the way that classes are loaded by the JVM, the + framework binding will be verified automatically very early + on. SLF4J will abort execution with a warning if no binding + is present. +
Bindings for popular logging frameworks + SLF4J supports popular logging frameworks, namely log4j, + java.util.logging, Simple logging and NOP. The logback project supports + SLF4J natively.
Bridging legacy logging APIs +

The implementation of JCL over SLF4J, i.e + jcl-over-slf4j.jar, will allow your project to + migrate to SLF4J piecemeal, without breaking compatibility + with existing software using JCL. Similarly, + log4j-over-slf4j.jar and jul-to-slf4j modules will allow + you to redirect log4j and respectively java.util.logging + calls to SLF4J. See the page on Bridging legacy APIs for more + details. +

+
Migrate your source codeThe slf4j-migrator utility + can help you migrate your source to use SLF4J. +
Support for parameterized log messagesAll SLF4J bindings support parameterized log messages + with significantly improved performance + results.
+ + + +
+ + diff --git a/slf4j-site/src/site/pages/migrator.html b/slf4j-site/src/site/pages/migrator.html index d1dc58d5..e983d002 100644 --- a/slf4j-site/src/site/pages/migrator.html +++ b/slf4j-site/src/site/pages/migrator.html @@ -1,226 +1,226 @@ - - - - - - SLF4J Migrator - - - - - - -
- -
-
- - -

SLF4J Migrator

- -

The SLF4J migrator is a small Java tool for migrating Java source - files from the Jakarta Commons Logging (JCL) API to SLF4J. It can - also migrate from the log4j API to SLF4J, or from - java.util.logging API to SLF4J. -

- -

The SLF4J migrator consists of a single jar file that can be - launched as a stand-alone java application. Here is the command: -

- -

java -jar slf4j-migrator-${version}.jar

- -
- -

Once the application is launched, a window similar to the - following should appear. -

- -

slf4j-migrator.gif

- -

Use the application should be self-explanatory. Please note that - this migration tool does in-place replacement of Java files, meaning - that there will be no back-up copies of modified files. It is - your responsibility to backup your files before using SLF4J - migrator. -

- - -

Limitations

- -

SLF4J migrator is intended as a simple tool to help you to - migrate your project source using JCL, log4j or JUL to SLF4J. It can - only perform elementary conversion steps. Essentially, it will - replace appropriate import lines and logger declarations. -

- -

MyClass is a sample class using JCL. Here it is before:

- -

package some.package; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public MyClass { - - Log logger = LogFactory.getLog(MyClass.class); - - public void someMethod() { - logger.info("Hello world"); - } -}

- -

and after migration:

- -

package some.package; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public MyClass { - - Logger logger = LoggerFactory.getLogger(MyClass.class); - - public void someMethod() { - logger.info("Hello world"); - } -}

- -
- -

Altough its conversion rules are elementary, the SLF4J migrator - can still alleviate much of the grunt-work involved in migrating a - Java project from JCL to SLF4J. -

- -

Migration rules from log4j to SLF4J, or from JUL to SLF4J are - similar.

- -

General limitations

- -
    - -
  • Build scipts are not modified - -

    Your Ant/Maven/Ivy build scripts need to be modified manualy to - use SLF4J instead of JCL or log4j.

    - -

    -
  • - -
  • only messages of type String are supported - -

    If one of your log statements contains a non-string object as - its sole parameter, you will have to manually add a toString() - method call on the object. -

    - -

    For example,

    -

    logger.debug(new Object());

    -

    has to be manually re-written as

    -

    logger.debug(new Object().toString());

    - -

    -
  • - -
  • the FATAL level is not supported. - -

    You have to convert them manually. This is limitation is not - deemed very serious because there are usually very few log - statements bearing the FATAL level. -

    - -

    -

    -
  • - -
  • if a method declares multipe loggers on the same line, the - conversion will not be complete. Example: - -

    public void someMethod(Log l1, Log l2) { - ... - } - -will be converted as - - public void someMethod(Log l1, Logger l2) { - ... - }

    -
  • -
- -

Limitations when migrating from log4j

- -
    -
  • NDC statements are left as-is - -

    Since NDC is not supported by SLF4J, the migrator cannot - properly handle NDC statements. You have to migrate them to MDC - manually. Again, this limitation is not deemed serious bebause - there are usually very few NDC statements even in large projects. -

    - -

    Please note that contrary to NDC, MDC statements are migrated - correctly because SLF4J suports such statements.

    - -

    -
  • - -
  • Calls to PropertyConfigurator or - DomConfigurator cannot be migrated since they have no - SLF4J equivalents. - -

    -

    - -
  • -
- -

Limitations when migrating from JUL

- - -
    -
  • Calls to finest(), finer() or - finest() methods of - java.util.loggging.Logger are left as is. - -

    Given that finest(), finer() or - finest() calls could map to both trace() or debug() - calls in SLF4J, it is impossible to guess how the user wants to - map these calls. -

    - -

    -

    - -
  • - - -
  • All strings matching ".severe(" are replaced by the string - ".error(" without any contexual analysys. Similarly, all strings - matching ".warning(" are replaced by ".warn(". - -

    Since the match/replace operation is not contextual, if your - code contains methods named "severe" or "warning", then the - migration results will have compilation errors. Fortunately, such - errors should be rare and easy to identify. -

    - -

    -

    - -
  • - -
  • Invocations of the following methods defined in the - java.util.logging.Logger class need to be migrated - manually: log, logp, logrb, - entering, exiting. - -
  • -
- - -
- + + + + + + SLF4J Migrator + + + + + + +
+ +
+
+ + +

SLF4J Migrator

+ +

The SLF4J migrator is a small Java tool for migrating Java source + files from the Jakarta Commons Logging (JCL) API to SLF4J. It can + also migrate from the log4j API to SLF4J, or from + java.util.logging API to SLF4J. +

+ +

The SLF4J migrator consists of a single jar file that can be + launched as a stand-alone java application. Here is the command: +

+ +

java -jar slf4j-migrator-${version}.jar

+ +
+ +

Once the application is launched, a window similar to the + following should appear. +

+ +

slf4j-migrator.gif

+ +

Use the application should be self-explanatory. Please note that + this migration tool does in-place replacement of Java files, meaning + that there will be no back-up copies of modified files. It is + your responsibility to backup your files before using SLF4J + migrator. +

+ + +

Limitations

+ +

SLF4J migrator is intended as a simple tool to help you to + migrate your project source using JCL, log4j or JUL to SLF4J. It can + only perform elementary conversion steps. Essentially, it will + replace appropriate import lines and logger declarations. +

+ +

MyClass is a sample class using JCL. Here it is before:

+ +

package some.package; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public MyClass { + + Log logger = LogFactory.getLog(MyClass.class); + + public void someMethod() { + logger.info("Hello world"); + } +}

+ +

and after migration:

+ +

package some.package; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public MyClass { + + Logger logger = LoggerFactory.getLogger(MyClass.class); + + public void someMethod() { + logger.info("Hello world"); + } +}

+ +
+ +

Altough its conversion rules are elementary, the SLF4J migrator + can still alleviate much of the grunt-work involved in migrating a + Java project from JCL to SLF4J. +

+ +

Migration rules from log4j to SLF4J, or from JUL to SLF4J are + similar.

+ +

General limitations

+ +
    + +
  • Build scipts are not modified + +

    Your Ant/Maven/Ivy build scripts need to be modified manualy to + use SLF4J instead of JCL or log4j.

    + +

    +
  • + +
  • only messages of type String are supported + +

    If one of your log statements contains a non-string object as + its sole parameter, you will have to manually add a toString() + method call on the object. +

    + +

    For example,

    +

    logger.debug(new Object());

    +

    has to be manually re-written as

    +

    logger.debug(new Object().toString());

    + +

    +
  • + +
  • the FATAL level is not supported. + +

    You have to convert them manually. This is limitation is not + deemed very serious because there are usually very few log + statements bearing the FATAL level. +

    + +

    +

    +
  • + +
  • if a method declares multipe loggers on the same line, the + conversion will not be complete. Example: + +

    public void someMethod(Log l1, Log l2) { + ... + } + +will be converted as + + public void someMethod(Log l1, Logger l2) { + ... + }

    +
  • +
+ +

Limitations when migrating from log4j

+ +
    +
  • NDC statements are left as-is + +

    Since NDC is not supported by SLF4J, the migrator cannot + properly handle NDC statements. You have to migrate them to MDC + manually. Again, this limitation is not deemed serious bebause + there are usually very few NDC statements even in large projects. +

    + +

    Please note that contrary to NDC, MDC statements are migrated + correctly because SLF4J suports such statements.

    + +

    +
  • + +
  • Calls to PropertyConfigurator or + DomConfigurator cannot be migrated since they have no + SLF4J equivalents. + +

    +

    + +
  • +
+ +

Limitations when migrating from JUL

+ + +
    +
  • Calls to finest(), finer() or + finest() methods of + java.util.loggging.Logger are left as is. + +

    Given that finest(), finer() or + finest() calls could map to both trace() or debug() + calls in SLF4J, it is impossible to guess how the user wants to + map these calls. +

    + +

    +

    + +
  • + + +
  • All strings matching ".severe(" are replaced by the string + ".error(" without any contexual analysys. Similarly, all strings + matching ".warning(" are replaced by ".warn(". + +

    Since the match/replace operation is not contextual, if your + code contains methods named "severe" or "warning", then the + migration results will have compilation errors. Fortunately, such + errors should be rare and easy to identify. +

    + +

    +

    + +
  • + +
  • Invocations of the following methods defined in the + java.util.logging.Logger class need to be migrated + manually: log, logp, logrb, + entering, exiting. + +
  • +
+ + +
+ \ No newline at end of file diff --git a/slf4j-site/src/site/pages/repos.html b/slf4j-site/src/site/pages/repos.html index e2682aa0..d7efe04d 100644 --- a/slf4j-site/src/site/pages/repos.html +++ b/slf4j-site/src/site/pages/repos.html @@ -1,104 +1,104 @@ - - - - - - SLF4J - - - - - - -
- -
-
- -

Source code repositories

- -

We store the project's source code in a revision control system - called Git. Developers have write access to the repository, enabling - them to make changes to the source code. Everyone else has - read-access to the repository. Thus, anyone can check out latest - development version of the software. Note that the latest version in - the repository may not work as expected. It may even not compile. If - you are looking for a stable release, then download an official - distribution. -

- -

There are several ways to access the git repository:

- -

Web Access

- -

If you just wish to browse around or download a few individual - files, you can do so with your web-browser: -

- - - - - - - - - - - - - - -
on github - - http://github.com/ceki/slf4j/tree/master (slow but rich) -
on git.qos.ch - http://git.qos.ch/gitweb/?p=slf4j.git;a=summary (fast but minimal) -
- -

Cloning

- - -

Anyone can clone the slf4j repository. All you need is a git - client. To clone our SLF4J git repository, issue one of the two - following commands:

- - - - - - - - - - - - - - - - - - - - - - - -
transport protocolgit clone command
gitgit clone git://git.qos.ch/slf4j
gitgit clone git://github.com/ceki/slf4j.git
httpgit clone http://git.qos.ch/slf4j/
- - -

In principle, the repositories listed above have identical - contents.

- - -

Subversion

- -

Previously, we relied on Subversion as our version control - system. Git is considerably better.

- - - -
- - + + + + + + SLF4J + + + + + + +
+ +
+
+ +

Source code repositories

+ +

We store the project's source code in a revision control system + called Git. Developers have write access to the repository, enabling + them to make changes to the source code. Everyone else has + read-access to the repository. Thus, anyone can check out latest + development version of the software. Note that the latest version in + the repository may not work as expected. It may even not compile. If + you are looking for a stable release, then download an official + distribution. +

+ +

There are several ways to access the git repository:

+ +

Web Access

+ +

If you just wish to browse around or download a few individual + files, you can do so with your web-browser: +

+ + + + + + + + + + + + + + +
on github + + http://github.com/ceki/slf4j/tree/master (slow but rich) +
on git.qos.ch + http://git.qos.ch/gitweb/?p=slf4j.git;a=summary (fast but minimal) +
+ +

Cloning

+ + +

Anyone can clone the slf4j repository. All you need is a git + client. To clone our SLF4J git repository, issue one of the two + following commands:

+ + + + + + + + + + + + + + + + + + + + + + + +
transport protocolgit clone command
gitgit clone git://git.qos.ch/slf4j
gitgit clone git://github.com/ceki/slf4j.git
httpgit clone http://git.qos.ch/slf4j/
+ + +

In principle, the repositories listed above have identical + contents.

+ + +

Subversion

+ +

Previously, we relied on Subversion as our version control + system. Git is considerably better.

+ + + +
+ + diff --git a/slf4j-site/src/site/pages/support.html b/slf4j-site/src/site/pages/support.html index ceac6b74..010a56b0 100644 --- a/slf4j-site/src/site/pages/support.html +++ b/slf4j-site/src/site/pages/support.html @@ -1,43 +1,43 @@ - - - - -Log4j Bridge - - - - - - - - -
- -
- -
- -

Contractual Support

- - -

The following companies, listed in alphabetical order, offer - contractual support for SLF4J. -

- -
    -
  • QOS.ch, in Lausanne, Swizerland. For more information visit - QOS.ch's support page.
  • -
- - - - -
- - - - + + + + +Log4j Bridge + + + + + + + + +
+ +
+ +
+ +

Contractual Support

+ + +

The following companies, listed in alphabetical order, offer + contractual support for SLF4J. +

+ +
    +
  • QOS.ch, in Lausanne, Swizerland. For more information visit + QOS.ch's support page.
  • +
+ + + + +
+ + + + diff --git a/slf4j-site/src/site/pages/templates/footer.js b/slf4j-site/src/site/pages/templates/footer.js index 95b72663..83051592 100644 --- a/slf4j-site/src/site/pages/templates/footer.js +++ b/slf4j-site/src/site/pages/templates/footer.js @@ -1,18 +1,18 @@ - -document.write('') - -document.write('') - -document.write(' ') - -document.write('') - -document.write('') -document.write('') - - + +document.write('') + +document.write('') + +document.write(' ') + +document.write('') + +document.write('') +document.write('') + + diff --git a/slf4j-site/src/site/pages/templates/header.js b/slf4j-site/src/site/pages/templates/header.js index 34c33421..bbaac0db 100644 --- a/slf4j-site/src/site/pages/templates/header.js +++ b/slf4j-site/src/site/pages/templates/header.js @@ -1,7 +1,7 @@ - -document.write('

'); -document.write(''); -document.write(''); -document.write('') -document.write('

'); + +document.write('

'); +document.write(''); +document.write(''); +document.write('') +document.write('

'); document.write(''); \ No newline at end of file diff --git a/slf4j-site/src/site/pages/templates/left.js b/slf4j-site/src/site/pages/templates/left.js index c40904fb..e2a630a1 100644 --- a/slf4j-site/src/site/pages/templates/left.js +++ b/slf4j-site/src/site/pages/templates/left.js @@ -1,36 +1,36 @@ - -document.write(''); - -document.write('

 

'); -document.write('

'); -document.write(' '); -document.write(' buy direct from the developer'); -document.write(' '); + +document.write('

'); + +document.write('

 

'); +document.write('

'); +document.write(' '); +document.write(' buy direct from the developer'); +document.write(' '); document.write('

'); \ No newline at end of file diff --git a/slf4j-site/src/site/pages/templates/right.js b/slf4j-site/src/site/pages/templates/right.js index d3f5a12f..8b137891 100644 --- a/slf4j-site/src/site/pages/templates/right.js +++ b/slf4j-site/src/site/pages/templates/right.js @@ -1 +1 @@ - + diff --git a/src/main/assembly/source.xml b/src/main/assembly/source.xml index 9606f9a4..31765b7e 100644 --- a/src/main/assembly/source.xml +++ b/src/main/assembly/source.xml @@ -1,306 +1,306 @@ - - dist - - zip - tar.gz - - - - - slf4j-api/ - slf4j-api/ - - pom.xml - - - - - slf4j-jcl/ - slf4j-jcl/ - - pom.xml - - - - - slf4j-jdk14/ - slf4j-jdk14/ - - pom.xml - - - - - slf4j-log4j12/ - slf4j-log4j12/ - - pom.xml - - - - - slf4j-nop/ - slf4j-nop/ - - pom.xml - - - - - slf4j-simple/ - slf4j-simple/ - - pom.xml - - - - - slf4j-ext/ - slf4j-ext/ - - pom.xml - - - - - - jcl104-over-slf4j/ - jcl104-over-slf4j/ - - pom.xml - - - - - jcl-over-slf4j/ - jcl-over-slf4j/ - - pom.xml - - - - - jul-to-slf4j/ - jul-to-slf4j/ - - pom.xml - - - - - log4j-over-slf4j/ - log4j-over-slf4j/ - - pom.xml - - - - - slf4j-site/ - slf4j-site/ - - pom.xml - - - - - slf4j-migrator/ - slf4j-migrator/ - - pom.xml - - - - - integration/ - integration/ - - pom.xml - build.xml - lib/* - - - - - - slf4j-api/src/ - slf4j-api/src/ - - - test/output/ - - - - - - slf4j-jcl/src/ - slf4j-jcl/src/ - - - - slf4j-jdk14/src/ - slf4j-jdk14/src/ - - - - slf4j-log4j12/src/ - slf4j-log4j12/src/ - - - slf4j-nop/src/ - slf4j-nop/src/ - - - slf4j-simple/src/ - slf4j-simple/src/ - - - slf4j-ext/src/ - slf4j-ext/src/ - - - jcl-over-slf4j/src/ - jcl-over-slf4j/src/ - - - jul-to-slf4j/src/ - jul-to-slf4j/src/ - - - log4j-over-slf4j/src/ - log4j-over-slf4j/src/ - - - slf4j-site/src/ - slf4j-site/src/ - - - slf4j-migrator/src/ - slf4j-migrator/src/ - - - integration/src/ - integration/src/ - - - - - - slf4j-api/target/ - / - - slf4j-api-${project.version}-sources.jar - slf4j-api-${project.version}.jar - - - - - slf4j-jcl/target/ - / - - slf4j-jcl-${project.version}.jar - slf4j-jcl-${project.version}-sources.jar - - - - - slf4j-jdk14/target/ - / - - slf4j-jdk14-${project.version}-sources.jar - slf4j-jdk14-${project.version}.jar - - - - - slf4j-log4j12/target/ - / - - slf4j-log4j12-${project.version}.jar - slf4j-log4j12-${project.version}-sources.jar - - - - - slf4j-nop/target/ - / - - slf4j-nop-${project.version}.jar - slf4j-nop-${project.version}-sources.jar - - - - - slf4j-simple/target/ - / - - slf4j-simple-${project.version}-sources*.jar - slf4j-simple-${project.version}.jar - - - - - - slf4j-ext/target/ - / - - slf4j-ext-${project.version}-sources*.jar - slf4j-ext-${project.version}.jar - - - - - - jcl-over-slf4j/target/ - / - - jcl-over-slf4j-${project.version}-sources.jar - jcl-over-slf4j-${project.version}.jar - - - - jul-to-slf4j/target/ - / - - jul-to-slf4j-${project.version}-sources.jar - jul-to-slf4j-${project.version}.jar - - - - log4j-over-slf4j/target/ - / - - log4j-over-slf4j-${project.version}.jar - log4j-over-slf4j-${project.version}-sources.jar - - - - - slf4j-migrator/target/ - / - - slf4j-migrator-${project.version}.jar - - - - - - target/site - /site - - dist/* - - - - - - - src/ - README* - LICENSE* - pom.xml - - - - + + dist + + zip + tar.gz + + + + + slf4j-api/ + slf4j-api/ + + pom.xml + + + + + slf4j-jcl/ + slf4j-jcl/ + + pom.xml + + + + + slf4j-jdk14/ + slf4j-jdk14/ + + pom.xml + + + + + slf4j-log4j12/ + slf4j-log4j12/ + + pom.xml + + + + + slf4j-nop/ + slf4j-nop/ + + pom.xml + + + + + slf4j-simple/ + slf4j-simple/ + + pom.xml + + + + + slf4j-ext/ + slf4j-ext/ + + pom.xml + + + + + + jcl104-over-slf4j/ + jcl104-over-slf4j/ + + pom.xml + + + + + jcl-over-slf4j/ + jcl-over-slf4j/ + + pom.xml + + + + + jul-to-slf4j/ + jul-to-slf4j/ + + pom.xml + + + + + log4j-over-slf4j/ + log4j-over-slf4j/ + + pom.xml + + + + + slf4j-site/ + slf4j-site/ + + pom.xml + + + + + slf4j-migrator/ + slf4j-migrator/ + + pom.xml + + + + + integration/ + integration/ + + pom.xml + build.xml + lib/* + + + + + + slf4j-api/src/ + slf4j-api/src/ + + + test/output/ + + + + + + slf4j-jcl/src/ + slf4j-jcl/src/ + + + + slf4j-jdk14/src/ + slf4j-jdk14/src/ + + + + slf4j-log4j12/src/ + slf4j-log4j12/src/ + + + slf4j-nop/src/ + slf4j-nop/src/ + + + slf4j-simple/src/ + slf4j-simple/src/ + + + slf4j-ext/src/ + slf4j-ext/src/ + + + jcl-over-slf4j/src/ + jcl-over-slf4j/src/ + + + jul-to-slf4j/src/ + jul-to-slf4j/src/ + + + log4j-over-slf4j/src/ + log4j-over-slf4j/src/ + + + slf4j-site/src/ + slf4j-site/src/ + + + slf4j-migrator/src/ + slf4j-migrator/src/ + + + integration/src/ + integration/src/ + + + + + + slf4j-api/target/ + / + + slf4j-api-${project.version}-sources.jar + slf4j-api-${project.version}.jar + + + + + slf4j-jcl/target/ + / + + slf4j-jcl-${project.version}.jar + slf4j-jcl-${project.version}-sources.jar + + + + + slf4j-jdk14/target/ + / + + slf4j-jdk14-${project.version}-sources.jar + slf4j-jdk14-${project.version}.jar + + + + + slf4j-log4j12/target/ + / + + slf4j-log4j12-${project.version}.jar + slf4j-log4j12-${project.version}-sources.jar + + + + + slf4j-nop/target/ + / + + slf4j-nop-${project.version}.jar + slf4j-nop-${project.version}-sources.jar + + + + + slf4j-simple/target/ + / + + slf4j-simple-${project.version}-sources*.jar + slf4j-simple-${project.version}.jar + + + + + + slf4j-ext/target/ + / + + slf4j-ext-${project.version}-sources*.jar + slf4j-ext-${project.version}.jar + + + + + + jcl-over-slf4j/target/ + / + + jcl-over-slf4j-${project.version}-sources.jar + jcl-over-slf4j-${project.version}.jar + + + + jul-to-slf4j/target/ + / + + jul-to-slf4j-${project.version}-sources.jar + jul-to-slf4j-${project.version}.jar + + + + log4j-over-slf4j/target/ + / + + log4j-over-slf4j-${project.version}.jar + log4j-over-slf4j-${project.version}-sources.jar + + + + + slf4j-migrator/target/ + / + + slf4j-migrator-${project.version}.jar + + + + + + target/site + /site + + dist/* + + + + + + + src/ + README* + LICENSE* + pom.xml + + + + \ No newline at end of file diff --git a/version.pl b/version.pl index f8d8f555..5587b313 100644 --- a/version.pl +++ b/version.pl @@ -1,44 +1,44 @@ - -if ($#ARGV < 1) { - print "Usage: version.pl VER FILE {FILE, FILE}\n"; - exit; -} - -$V=$ARGV[0]; -print "VER:'${V}'\r\n"; -shift(@ARGV); - -sub replace () { - my $filename = $_[0]; - - if(-s $filename) { - print "Processing [" . $filename . "]\r\n"; - - my $original = "$filename.original"; - - rename($filename, $original); - open(OUT, ">$filename"); - open(IN, "$original"); - - my $hitCount=0; - while() { - if($hitCount == 0 && /.*<\/version>/) { - s/.*<\/version>/${V}<\/version>/; - $hitCount++; - } - print OUT; - } - close(IN); - close(OUT); - unlink($original); - } else { - print "File [" . $filename . "] does not exist\r\n" - } -} - -foreach $ARG (@ARGV) { - do replace($ARG); -} - - - + +if ($#ARGV < 1) { + print "Usage: version.pl VER FILE {FILE, FILE}\n"; + exit; +} + +$V=$ARGV[0]; +print "VER:'${V}'\r\n"; +shift(@ARGV); + +sub replace () { + my $filename = $_[0]; + + if(-s $filename) { + print "Processing [" . $filename . "]\r\n"; + + my $original = "$filename.original"; + + rename($filename, $original); + open(OUT, ">$filename"); + open(IN, "$original"); + + my $hitCount=0; + while() { + if($hitCount == 0 && /.*<\/version>/) { + s/.*<\/version>/${V}<\/version>/; + $hitCount++; + } + print OUT; + } + close(IN); + close(OUT); + unlink($original); + } else { + print "File [" . $filename . "] does not exist\r\n" + } +} + +foreach $ARG (@ARGV) { + do replace($ARG); +} + + +