From c92ae2f1ac87359bb459148fe426506169ea8538 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Charaoui?= <jerome@riseup.net> Date: Wed, 11 Jan 2023 10:28:45 -0500 Subject: [PATCH] New upstream version 1.2.4 --- .gitignore | 6 + CHANGELOG.md | 140 ++++ CONTRIBUTING.md | 12 + LICENSE | 205 ++++++ README.md | 155 +++-- pom.xml | 25 +- project.clj | 18 + src/main/clojure/clojure/tools/logging.clj | 157 +++-- .../clojure/clojure/tools/logging/impl.clj | 182 ++++-- .../clojure/tools/logging/readable.clj | 171 +++++ .../clojure/clojure/tools/logging/test.clj | 268 ++++++++ .../clojure/tools/logging/test_impl.clj | 149 +++++ .../clojure/tools/logging/test_readable.clj | 247 ++++++++ .../clojure/tools/logging/test_test.clj | 132 ++++ .../clojure/clojure/tools/test_logging.clj | 599 +++++++++--------- src/test/clojure/external/ns.clj | 8 + src/test/clojure/log4j2.xml | 13 + 17 files changed, 2038 insertions(+), 449 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 project.clj create mode 100644 src/main/clojure/clojure/tools/logging/readable.clj create mode 100644 src/main/clojure/clojure/tools/logging/test.clj create mode 100644 src/test/clojure/clojure/tools/logging/test_impl.clj create mode 100644 src/test/clojure/clojure/tools/logging/test_readable.clj create mode 100644 src/test/clojure/clojure/tools/logging/test_test.clj create mode 100644 src/test/clojure/external/ns.clj create mode 100644 src/test/clojure/log4j2.xml diff --git a/.gitignore b/.gitignore index eb5a316..ca41f24 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,7 @@ +.classpath +.lein-* +.nrepl-* +.project +.settings +bin target diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..bd4f612 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,140 @@ +# Changelog +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html) +([despite its flaws](https://www.youtube.com/watch?v=oyLBGkS5ICk)). + +## next + +### Changed +- Bumped log4j test deps to 2.17.1 + +## [1.2.3] - 2021-12-18 + +### Changed +- Bumped log4j test deps to 2.17.0 + +## [1.2.2] - 2021-12-14 + +### Changed +- Bumped log4j test deps to 2.16.0 + +## [1.2.1] - 2021-12-10 + +### Changed +- Bumped all testing deps to latest (particularly log4j) + +## [1.2.0] - 2021-12-10 + +### Changed +- Bumped all testing deps to latest (particularly log4j) + +## [1.1.0] - 2020-04-25 +### Added +- Add implementation of `spyf` to `clojure.tools.logging.readable`. + +### Changed +- Decreased the per-call overhead when using SLF4J, Commons Logging, and Log4j2. + Previously, their associated `logger-factory` implementations were calling + library-specific static convenience methods for each call to `get-logger`. + These methods have some baked-in setup overhead, which now only occurs during + instantiation of the associated `logger-factory`. + +## [1.0.0] - 2020-02-27 +### Added +- Add support for printing message arguments readably in + [`clojure.tools.logging.readable`](https://clojure.github.io/tools.logging/#clojure.tools.logging.readable). + +## [0.6.0] - 2020-02-07 +### Added +- Add support for explicitly selecting a logger factory by setting the + `"clojure.tools.logging.factory"` system property. For details, see the + [README](https://github.com/clojure/tools.logging#configuration), + and the documentation for [\*logger-factory\*](https://clojure.github.io/tools.logging/#clojure.tools.logging/*logger-factory*). + +## [0.5.0] - 2019-07-22 +### Added +- Add support for testing logs in [`clojure.tools.logging.test`](https://clojure.github.io/tools.logging/#clojure.tools.logging.test). + +### Changed +- Now passes the context classloader of current thread to `Class/forName` when + determining whether logging implementation classes are available on the + classpath. This was done to allow testing of the various `impl/*-factory` + functions, and seems consistent with clojure internals. + +## [0.4.1] - 2018-05-07 +### Fixed +- Fix inadvertent reflection when using log4j2. + +## [0.4.0] - 2017-06-04 +### Added +- Allow arbitrary values for `level` in logging adapters. +- Add support for log4j2. + +## [0.3.1] - 2014-09-20 +### Fixed +- Change ns forms so their subforms are contained in parens not []. + +## [0.3.0] - 2014-06-07 +### Added +- Provide disabled instances of `Logger` and `LoggerFactory`. +- Add `spyf`, like `spy` but takes a format string for the result. + +### Fixed +- Fix typos in recent README changes. +- Update outdated unreleased diff link. + +## [0.2.6] - 2013-02-04 +### Fixed +- Avoid double evaluation of `message` arg to `logf` and `logp`. + +## [0.2.4] - 2012-07-09 +### Fixed +- Avoid reflection in logging adapters. + +## [0.2.3] - 2011-09-29 +### Fixed +- Fix broken protocol extension due to incompatibility between syntax-quote and + extend-type. + +## [0.2.2] - 2011-09-28 +### Changed +- Auto-detecting logging implementation now prefers SLF4J over Commons Logging. +- Move logging implementation code into `clojure.tools.logging.impl`. + +## [0.2.0] - 2011-07-19 +### Changed +- Changed naming from "log" to "logger". +- Move implementation support to `clojure.tools.logging.impl`. +### Fixed +- Fix newline trimming in `spy` macro. +- Fix improper arity call of `log*` from `logp` and `logf`. + +## [0.1.2] - 2011-03-18 +### Fixed +- Annotate dynamic vars. + +## 0.1.0 - 2011-03-11 +### Added +- Initial implementation of Clojure-aware logging abstraction. + +[Unreleased]: https://github.com/clojure/tools.logging/compare/tools.logging-1.1.0...HEAD +[1.2.3]: https://github.com/clojure/tools.logging/compare/v1.2.2...v1.2.3 +[1.2.2]: https://github.com/clojure/tools.logging/compare/v1.2.1...v1.2.2 +[1.2.1]: https://github.com/clojure/tools.logging/compare/v1.2.0...v1.2.1 +[1.2.0]: https://github.com/clojure/tools.logging/compare/tools.logging-1.1.0...v1.2.0 +[1.1.0]: https://github.com/clojure/tools.logging/compare/tools.logging-1.0.0...tools.logging-1.1.0 +[1.0.0]: https://github.com/clojure/tools.logging/compare/tools.logging-0.6.0...tools.logging-1.0.0 +[0.6.0]: https://github.com/clojure/tools.logging/compare/tools.logging-0.5.0...tools.logging-0.6.0 +[0.5.0]: https://github.com/clojure/tools.logging/compare/tools.logging-0.4.1...tools.logging-0.5.0 +[0.4.1]: https://github.com/clojure/tools.logging/compare/tools.logging-0.4.0...tools.logging-0.4.1 +[0.4.0]: https://github.com/clojure/tools.logging/compare/tools.logging-0.3.1...tools.logging-0.4.0 +[0.3.1]: https://github.com/clojure/tools.logging/compare/tools.logging-0.3.0...tools.logging-0.3.1 +[0.3.0]: https://github.com/clojure/tools.logging/compare/tools.logging-0.2.6...tools.logging-0.3.0 +[0.2.6]: https://github.com/clojure/tools.logging/compare/tools.logging-0.2.4...tools.logging-0.2.6 +[0.2.4]: https://github.com/clojure/tools.logging/compare/tools.logging-0.2.3...tools.logging-0.2.4 +[0.2.3]: https://github.com/clojure/tools.logging/compare/tools.logging-0.2.2...tools.logging-0.2.3 +[0.2.2]: https://github.com/clojure/tools.logging/compare/tools.logging-0.2.0...tools.logging-0.2.2 +[0.2.0]: https://github.com/clojure/tools.logging/compare/tools.logging-0.1.2...tools.logging-0.2.0 +[0.1.2]: https://github.com/clojure/tools.logging/compare/tools.logging-0.1.0...tools.logging-0.1.2 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..26313e3 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,12 @@ +This is a [Clojure contrib] project. + +Under the Clojure contrib [guidelines], this project cannot accept +pull requests. All patches must be submitted via [JIRA]. + +See [Contributing] on the Clojure website for +more information on how to contribute. + +[Clojure contrib]: https://clojure.org/community/contrib_libs +[Contributing]: https://clojure.org/community/contributing +[JIRA]: https://clojure.atlassian.net/browse/TLOG +[guidelines]: https://clojure.org/community/contrib_howto diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e246f6a --- /dev/null +++ b/LICENSE @@ -0,0 +1,205 @@ +Eclipse Public License - v 1.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC +LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM +CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + +a) in the case of the initial Contributor, the initial code and documentation + distributed under this Agreement, and +b) in the case of each subsequent Contributor: + i) changes to the Program, and + ii) additions to the Program; + + where such changes and/or additions to the Program originate from and are + distributed by that particular Contributor. A Contribution 'originates' + from a Contributor if it was added to the Program by such Contributor + itself or anyone acting on such Contributor's behalf. Contributions do not + include additions to the Program which: (i) are separate modules of + software distributed in conjunction with the Program under their own + license agreement, and (ii) are not derivative works of the Program. + +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents" mean patent claims licensable by a Contributor which are +necessarily infringed by the use or sale of its Contribution alone or when +combined with the Program. + +"Program" means the Contributions distributed in accordance with this +Agreement. + +"Recipient" means anyone who receives the Program under this Agreement, +including all Contributors. + +2. GRANT OF RIGHTS + a) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free copyright license to + reproduce, prepare derivative works of, publicly display, publicly + perform, distribute and sublicense the Contribution of such Contributor, + if any, and such derivative works, in source code and object code form. + b) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free patent license under + Licensed Patents to make, use, sell, offer to sell, import and otherwise + transfer the Contribution of such Contributor, if any, in source code and + object code form. This patent license shall apply to the combination of + the Contribution and the Program if, at the time the Contribution is + added by the Contributor, such addition of the Contribution causes such + combination to be covered by the Licensed Patents. The patent license + shall not apply to any other combinations which include the Contribution. + No hardware per se is licensed hereunder. + c) Recipient understands that although each Contributor grants the licenses + to its Contributions set forth herein, no assurances are provided by any + Contributor that the Program does not infringe the patent or other + intellectual property rights of any other entity. Each Contributor + disclaims any liability to Recipient for claims brought by any other + entity based on infringement of intellectual property rights or + otherwise. As a condition to exercising the rights and licenses granted + hereunder, each Recipient hereby assumes sole responsibility to secure + any other intellectual property rights needed, if any. For example, if a + third party patent license is required to allow Recipient to distribute + the Program, it is Recipient's responsibility to acquire that license + before distributing the Program. + d) Each Contributor represents that to its knowledge it has sufficient + copyright rights in its Contribution, if any, to grant the copyright + license set forth in this Agreement. + +3. REQUIREMENTS + +A Contributor may choose to distribute the Program in object code form under +its own license agreement, provided that: + + a) it complies with the terms and conditions of this Agreement; and + b) its license agreement: + i) effectively disclaims on behalf of all Contributors all warranties + and conditions, express and implied, including warranties or + conditions of title and non-infringement, and implied warranties or + conditions of merchantability and fitness for a particular purpose; + ii) effectively excludes on behalf of all Contributors all liability for + damages, including direct, indirect, special, incidental and + consequential damages, such as lost profits; + iii) states that any provisions which differ from this Agreement are + offered by that Contributor alone and not by any other party; and + iv) states that source code for the Program is available from such + Contributor, and informs licensees how to obtain it in a reasonable + manner on or through a medium customarily used for software exchange. + +When the Program is made available in source code form: + + a) it must be made available under this Agreement; and + b) a copy of this Agreement must be included with each copy of the Program. + Contributors may not remove or alter any copyright notices contained + within the Program. + +Each Contributor must identify itself as the originator of its Contribution, +if +any, in a manner that reasonably allows subsequent Recipients to identify the +originator of the Contribution. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities with +respect to end users, business partners and the like. While this license is +intended to facilitate the commercial use of the Program, the Contributor who +includes the Program in a commercial product offering should do so in a manner +which does not create potential liability for other Contributors. Therefore, +if a Contributor includes the Program in a commercial product offering, such +Contributor ("Commercial Contributor") hereby agrees to defend and indemnify +every other Contributor ("Indemnified Contributor") against any losses, +damages and costs (collectively "Losses") arising from claims, lawsuits and +other legal actions brought by a third party against the Indemnified +Contributor to the extent caused by the acts or omissions of such Commercial +Contributor in connection with its distribution of the Program in a commercial +product offering. The obligations in this section do not apply to any claims +or Losses relating to any actual or alleged intellectual property +infringement. In order to qualify, an Indemnified Contributor must: +a) promptly notify the Commercial Contributor in writing of such claim, and +b) allow the Commercial Contributor to control, and cooperate with the +Commercial Contributor in, the defense and any related settlement +negotiations. The Indemnified Contributor may participate in any such claim at +its own expense. + +For example, a Contributor might include the Program in a commercial product +offering, Product X. That Contributor is then a Commercial Contributor. If +that Commercial Contributor then makes performance claims, or offers +warranties related to Product X, those performance claims and warranties are +such Commercial Contributor's responsibility alone. Under this section, the +Commercial Contributor would have to defend claims against the other +Contributors related to those performance claims and warranties, and if a +court requires any other Contributor to pay any damages as a result, the +Commercial Contributor must pay those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED 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. Each +Recipient is solely responsible for determining the appropriateness of using +and distributing the Program and assumes all risks associated with its +exercise of rights under this Agreement , including but not limited to the +risks and costs of program errors, compliance with applicable laws, damage to +or loss of data, programs or equipment, and unavailability or interruption of +operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY +CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION +LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE +EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY +OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under +applicable law, it shall not affect the validity or enforceability of the +remainder of the terms of this Agreement, and without further action by the +parties hereto, such provision shall be reformed to the minimum extent +necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Program itself +(excluding combinations of the Program with other software or hardware) +infringes such Recipient's patent(s), then such Recipient's rights granted +under Section 2(b) shall terminate as of the date such litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it fails to +comply with any of the material terms or conditions of this Agreement and does +not cure such failure in a reasonable period of time after becoming aware of +such noncompliance. If all Recipient's rights under this Agreement terminate, +Recipient agrees to cease use and distribution of the Program as soon as +reasonably practicable. However, Recipient's obligations under this Agreement +and any licenses granted by Recipient relating to the Program shall continue +and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, but in +order to avoid inconsistency the Agreement is copyrighted and may only be +modified in the following manner. The Agreement Steward reserves the right to +publish new versions (including revisions) of this Agreement from time to +time. No one other than the Agreement Steward has the right to modify this +Agreement. The Eclipse Foundation is the initial Agreement Steward. The +Eclipse Foundation may assign the responsibility to serve as the Agreement +Steward to a suitable separate entity. Each new version of the Agreement will +be given a distinguishing version number. The Program (including +Contributions) may always be distributed subject to the version of the +Agreement under which it was received. In addition, after a new version of the +Agreement is published, Contributor may elect to distribute the Program +(including its Contributions) under the new version. Except as expressly +stated in Sections 2(a) and 2(b) above, Recipient receives no rights or +licenses to the intellectual property of any Contributor under this Agreement, +whether expressly, by implication, estoppel or otherwise. All rights in the +Program not expressly granted under this Agreement are reserved. + +This Agreement is governed by the laws of the State of New York and the +intellectual property laws of the United States of America. No party to this +Agreement will bring a legal action under this Agreement more than one year +after the cause of action arose. Each party waives its rights to a jury trial in +any resulting litigation. + + diff --git a/README.md b/README.md index 3d83ddd..79e71a0 100644 --- a/README.md +++ b/README.md @@ -1,76 +1,151 @@ # Logging -Logging macros which delegate to a specific logging implementation. At runtime a specific implementation is selected from, in order, slf4j, Apache commons-logging, log4j, and finally java.util.logging. +Logging macros which delegate to a specific logging implementation, selected +at runtime when the `clojure.tools.logging` namespace is first loaded. -Logging levels are specified by clojure keywords corresponding to the values used in log4j and commons-logging: +## Installation - :trace, :debug, :info, :warn, :error, :fatal +Lastest stable release is [1.2.3] -Logging occurs with the `log` macro, or the level-specific convenience macros, which write either directly or via an agent. The log macros will not evaluate their message arguments unless the specific logging level is in effect. Alternately, you can use the `spy` macro when you have code that needs to be evaluated, and also want to output the code and its result to the log. +[CLI/`deps.edn`](https://clojure.org/reference/deps_and_cli) dependency information: +```clojure +org.clojure/tools.logging {:mvn/version "1.2.3"} +``` -Unless otherwise specified, the current namespace (as identified by `*ns*`) will be used as the log-ns (similar to how the java class name is usually used). Note: your logging configuration should display the name that was passed to the logging implementation, and not perform stack-inspection, otherwise you'll see some ugly and unhelpful text in your logs. +Leiningen: -Use the `enabled?` macro to write conditional code against the logging level (beyond simply whether or not to call log, which is handled automatically). +```clojure +[org.clojure/tools.logging "1.2.3"] +``` + +Maven: + +```xml +<dependency> + <groupId>org.clojure</groupId> + <artifactId>tools.logging</artifactId> + <version>1.2.3</version> +</dependency> +``` + +Gradle: + +```clojure +compile "org.clojure:tools.logging:1.2.3" +``` -You can redirect all java writes of `System.out` and `System.err` to the log system by calling `log-capture!`. To bind `*out*` and `*err*` to the log system invoke `with-logs`. In both cases a log-ns (e.g., "com.example.captured") must be specified in order to namespace the output. ## Usage -The following short example should give you what you need to get started: +[Latest API Documentation](https://clojure.github.io/tools.logging) + +Logging occurs with the `log` macro, or the level-specific convenience macros +(e.g., `debug`, `debugf`). Only when the specified logging level is enabled will +the message arguments be evaluated and the underlying logging implementation be +invoked. By default, that invocation will occur via an agent when inside a +running STM transaction. + +### Namespacing of log entries + +Unless otherwise specified, the current namespace (as identified by `*ns*`) will +be used as the "logger name" when interacting with logging implementations. Most +logging implementations allow for varying configuration by logger name. + +Note: You should configure your logging implementation to display the logger +name that was passed to it. If it instead the logging implementation performs +stack-inspection you'll see some ugly and unhelpful text in your logs. + +### Redirecting output to logs - (ns example.core - (:use [clojure.tools.logging :only (info error)])) +You can redirect all java writes of `System.out` and `System.err` to the log +system by calling `log-capture!`. To bind `*out*` and `*err*` to the log system +invoke `with-logs`. In both cases a logger name must be provided in lieu of +using `*ns*`. - (defn divide [one two] - (try - (info "Calculated" (/ one two)) - (catch Exception ex - (error ex "There was an error in calculation")))) +## Configuration -For those new to using a java logging library, the following is a very basic configuration for log4j. Place it in a file called `log4j.properties` and place that file (and the log4j JAR) on the classpath. +_NOTE: Logging configuration (e.g., setting of logging levels, formatting) is +specific to the underlying logging implementation, and is out of scope for this +library._ - log4j.rootLogger=WARN, A1 - log4j.logger.user=DEBUG - log4j.appender.A1=org.apache.log4j.ConsoleAppender - log4j.appender.A1.layout=org.apache.log4j.PatternLayout - log4j.appender.A1.layout.ConversionPattern=%d %-5p %c: %m%n +### Selecting a logging implementation -The above will print messages to the console for `:debug` or higher if one is in the `user` namespace, and `:warn` or higher in all other namespaces. +To control which logging implementation is used, set the `clojure.tools.logging.factory` +system property to the fully-qualified name of a no-arg function that returns an +instance of `clojure.tools.logging.impl/LoggerFactory`. There are a number of +factory functions provided in the [`clojure.tools.logging.impl`](https://clojure.github.io/tools.logging/#clojure.tools.logging.impl/find-factory) +namespace. -### Installation +[Leiningen example]: -Logging is available in Maven central. Add it to your Maven project's `pom.xml`: +```clojure +:jvm-opts ["-Dclojure.tools.logging.factory=clojure.tools.logging.impl/slf4j-factory"] +``` - <dependency> - <groupId>org.clojure</groupId> - <artifactId>tools.logging</artifactId> - <version>0.2.0</version> - </dependency> +If the system property is unset, an implementation will be automatically chosen +based on whichever of the following implementations is successfully loaded first: -or your leiningen project.clj: +1. [SLF4J] +2. [Apache Commons Logging] +3. [Log4J 2] +4. [Log4J] +5. [java.util.logging] - [org.clojure/tools.logging "0.2.0"] +The above approach is problematic given that applications often inadvertently pull +in multiple logging implementations as transitive dependencies. As such, it is +_strongly_ advised that you set the system property. -Please note the changelog below. +### Log4J2 -### Building Logging +A simple Log4j2 [configuration](https://logging.apache.org/log4j/2.x/manual/configuration.html): -0. Clone the repo -1. Make sure you have maven installed -2. Run the maven build; run either: - 1. `mvn install`: This will produce a logging jar file in the `target` -directory, and run all tests with the most recently-released build -of Clojure. +```properties +status = warn +monitorInterval = 5 + +appender.console.type = Console +appender.console.name = STDOUT +appender.console.layout.type = PatternLayout +appender.console.layout.pattern = %date %level %logger %message%n%throwable + +rootLogger.level = info +rootLogger.appenderRef.stdout.ref = STDOUT +``` + +*Note:* The above [pattern](https://logging.apache.org/log4j/2.x/manual/layouts.html#Patterns) +explicitly uses `%throwable` so that `clojure.lang.ExceptionInfo` exceptions +will be printed with their data maps. If either `%xThrowable` (the default) or +`%rThrowable` is used, the data maps will not be printed. + +## FAQ + +#### When logging an `ex-info` exception, why isn't the data map printed? + +This is likely because the logging implementation is printing the contents of +`Throwable.getMessage()`, which returns just the message arg to `ex-info`. + +Logging implementations that print the contents of `toString()` or use `Throwable.printStackTrace(...)` +will end up printing the data map. ## Thanks * Chris Dean * Phil Hagelberg * Richard Newman +* Sean Corfield * Timothy Pratley ## License -Copyright © 2009 Alex Taggart +Copyright © 2009-2021 Rich Hickey, Alex Taggart, and contributors Licensed under the EPL. (See the file epl.html.) + + +[1.2.3]: https://github.com/clojure/tools.logging/tree/v1.2.3 +[Leiningen example]: https://github.com/technomancy/leiningen/blob/master/doc/TUTORIAL.md#setting-jvm-options +[SLF4J]: http://www.slf4j.org/ +[Apache Commons Logging]: https://commons.apache.org/logging +[Log4J 2]: https://logging.apache.org/log4j/2.x/ +[Log4J]: http://logging.apache.org/log4j/1.2/ +[java.util.logging]: https://docs.oracle.com/en/java/javase/13/docs/api/java.logging/java/util/logging/package-summary.html diff --git a/pom.xml b/pom.xml index f5e62f7..d7d9a91 100644 --- a/pom.xml +++ b/pom.xml @@ -1,13 +1,13 @@ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>tools.logging</artifactId> - <version>0.2.3</version> - <name>${artifactId}</name> + <version>1.2.4</version> + <name>tools.logging</name> <parent> <groupId>org.clojure</groupId> <artifactId>pom.contrib</artifactId> - <version>0.0.23</version> + <version>1.1.0</version> </parent> <developers> @@ -20,31 +20,38 @@ <connection>scm:git:git@github.com:clojure/tools.logging.git</connection> <developerConnection>scm:git:git@github.com:clojure/tools.logging.git</developerConnection> <url>git@github.com:clojure/tools.logging.git</url> + <tag>v1.2.4</tag> </scm> <dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> - <version>1.6.2</version> + <version>1.7.32</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> - <version>1.6.2</version> + <version>1.7.32</version> <scope>test</scope> </dependency> <dependency> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - <version>1.2.16</version> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-api</artifactId> + <version>2.17.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.logging.log4j</groupId> + <artifactId>log4j-core</artifactId> + <version>2.17.1</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> - <version>1.1.1</version> + <version>1.2</version> <scope>test</scope> </dependency> </dependencies> diff --git a/project.clj b/project.clj new file mode 100644 index 0000000..5779ec0 --- /dev/null +++ b/project.clj @@ -0,0 +1,18 @@ +(defproject org.clojure/tools.logging "1.1.1-SNAPSHOT" + :description "Clojure logging API." + :url "https://github.com/clojure/tools.logging" + :license {:name "Eclipse Public License" + :url "http://www.eclipse.org/legal/epl-v10.html"} + :source-paths ["src/main/clojure"] + :test-paths ["src/test/clojure"] + :dependencies [[org.clojure/clojure "1.3.0"]] + :aliases {"cloverage" ["with-profile" "dev,cloverage" "cloverage" "--fail-threshold" "100"]} + :profiles {:cloverage {:plugins [[lein-cloverage "1.0.9"]]} + :dev {:dependencies [[org.clojure/clojure "1.8.0"] + [org.clojure/test.check "1.1.1"] + [org.slf4j/slf4j-api "1.7.32"] + [org.slf4j/slf4j-log4j12 "1.7.32"] + [org.apache.logging.log4j/log4j-api "2.17.1"] + [org.apache.logging.log4j/log4j-core "2.17.1"] + [commons-logging "1.2"] + [criterium "0.4.6"]]}}) diff --git a/src/main/clojure/clojure/tools/logging.clj b/src/main/clojure/clojure/tools/logging.clj index 6199760..e963f06 100644 --- a/src/main/clojure/clojure/tools/logging.clj +++ b/src/main/clojure/clojure/tools/logging.clj @@ -11,14 +11,18 @@ ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns ^{:author "Alex Taggart" - :doc "Logging macros which delegate to a specific logging implementation. At - runtime a specific implementation is selected from, in order, slf4j, - Apache commons-logging, slf4j, log4j, and finally java.util.logging."} + :doc "Logging macros which delegate to a specific logging implementation. + + A logging implementation is selected at runtime when this namespace is first + loaded. For more details, see the documentation for *logger-factory*. + + If you want to test that your code emits specific log messages, see the + clojure.tools.logging.test namespace."} clojure.tools.logging - [:use + (:use [clojure.string :only [trim-newline]] - [clojure.pprint :only [code-dispatch pprint with-pprint-dispatch]]] - [:require [clojure.tools.logging.impl :as impl]]) + [clojure.pprint :only [code-dispatch pprint with-pprint-dispatch]]) + (:require [clojure.tools.logging.impl :as impl])) (def ^{:doc "The default agent used for performing logging when direct logging is @@ -49,14 +53,15 @@ One can override the above by setting *force* to :direct or :agent; all subsequent writes will be direct or via an agent, respectively." [logger level throwable message] - (if (cond - (nil? *force*) (and (clojure.lang.LockingTransaction/isRunning) - (*tx-agent-levels* level)) - (= *force* :agent) true - (= *force* :direct) false) + (if (case *force* + :agent true + :direct false + (and (clojure.lang.LockingTransaction/isRunning) + (*tx-agent-levels* level))) (send-off *logging-agent* (fn [_#] (impl/write! logger level throwable message))) - (impl/write! logger level throwable message))) + (impl/write! logger level throwable message)) + nil) (declare ^{:dynamic true} *logger-factory*) ; default LoggerFactory instance for calling impl/get-logger @@ -76,29 +81,33 @@ (defmacro logp "Logs a message using print style args. Can optionally take a throwable as its - second arg. See level-specific macros, e.g., debug." + second arg. See level-specific macros, e.g., debug. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([level message & more] [level throwable message & more])} [level x & more] (if (or (instance? String x) (nil? more)) ; optimize for common case `(log ~level (print-str ~x ~@more)) `(let [logger# (impl/get-logger *logger-factory* ~*ns*)] (if (impl/enabled? logger# ~level) - (if (instance? Throwable ~x) ; type check only when enabled - (log* logger# ~level ~x (print-str ~@more)) - (log* logger# ~level nil (print-str ~x ~@more))))))) + (let [x# ~x] + (if (instance? Throwable x#) ; type check only when enabled + (log* logger# ~level x# (print-str ~@more)) + (log* logger# ~level nil (print-str x# ~@more)))))))) (defmacro logf "Logs a message using a format string and args. Can optionally take a - throwable as its second arg. See level-specific macros, e.g., debugf." + throwable as its second arg. See level-specific macros, e.g., debugf. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([level fmt & fmt-args] [level throwable fmt & fmt-args])} [level x & more] (if (or (instance? String x) (nil? more)) ; optimize for common case `(log ~level (format ~x ~@more)) `(let [logger# (impl/get-logger *logger-factory* ~*ns*)] (if (impl/enabled? logger# ~level) - (if (instance? Throwable ~x) ; type check only when enabled - (log* logger# ~level ~x (format ~@more)) - (log* logger# ~level nil (format ~x ~@more))))))) + (let [x# ~x] + (if (instance? Throwable x#) ; type check only when enabled + (log* logger# ~level x# (format ~@more)) + (log* logger# ~level nil (format x# ~@more)))))))) (defmacro enabled? "Returns true if the specific logging level is enabled. Use of this macro @@ -125,6 +134,17 @@ (trim-newline s#))) a#))) +(defmacro spyf + "Evaluates expr and may write (format fmt result) to the log. Returns the + result of expr. Defaults to :debug log level. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." + ([fmt expr] + `(spyf :debug ~fmt ~expr)) + ([level fmt expr] + `(let [a# ~expr] + (log ~level (format ~fmt a#)) + a#))) + (defn log-stream "Creates a PrintStream that will output to the log at the specified level." [level logger-ns] @@ -183,93 +203,136 @@ ; Implementation Notes: ; - no enabled? check before making writers since that may change later (let [[logger-ns out-level err-level] (if (vector? arg) - arg - [arg :info :error])] - (if (and logger-ns (seq body)) - `(binding [*out* (java.io.OutputStreamWriter. - (log-stream ~out-level ~logger-ns)) - *err* (java.io.OutputStreamWriter. - (log-stream ~err-level ~logger-ns))] - ~@body)))) - + arg + [arg :info :error])] + `(binding [*out* (java.io.OutputStreamWriter. + (log-stream ~out-level ~logger-ns)) + *err* (java.io.OutputStreamWriter. + (log-stream ~err-level ~logger-ns))] + ~@body))) ;; level-specific macros (defmacro trace - "Trace level logging using print-style args." + "Trace level logging using print-style args. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :trace ~@args)) (defmacro debug - "Debug level logging using print-style args." + "Debug level logging using print-style args. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :debug ~@args)) (defmacro info - "Info level logging using print-style args." + "Info level logging using print-style args. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :info ~@args)) (defmacro warn - "Warn level logging using print-style args." + "Warn level logging using print-style args. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :warn ~@args)) (defmacro error - "Error level logging using print-style args." + "Error level logging using print-style args. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :error ~@args)) (defmacro fatal - "Fatal level logging using print-style args." + "Fatal level logging using print-style args. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([message & more] [throwable message & more])} [& args] `(logp :fatal ~@args)) (defmacro tracef - "Trace level logging using format." + "Trace level logging using format. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :trace ~@args)) (defmacro debugf - "Debug level logging using format." + "Debug level logging using format. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :debug ~@args)) (defmacro infof - "Info level logging using format." + "Info level logging using format. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :info ~@args)) (defmacro warnf - "Warn level logging using format." + "Warn level logging using format. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :warn ~@args)) (defmacro errorf - "Error level logging using format." + "Error level logging using format. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :error ~@args)) (defmacro fatalf - "Fatal level logging using format." + "Fatal level logging using format. + Use the 'logging.readable' namespace to avoid wrapping args in pr-str." {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} [& args] `(logf :fatal ~@args)) -(def ^{:doc - "An instance satisfying the impl/LoggerFactory protocol. Used internally to - obtain an impl/Logger. Defaults to the value returned from impl/find-factory." - :dynamic true} - *logger-factory* - (impl/find-factory)) +(defn- call-str [str] + (let [fq-sym (symbol str) + ns-str (or (namespace fq-sym) + (throw (RuntimeException. + (format "The value of the clojure.tools.logging.factory system property is not fully-qualified: %s" + (pr-str str))))) + ns-sym (symbol ns-str) + _ (try + (require ns-sym) + (catch Exception ex + (throw (RuntimeException. + (format "Could not resolve namespace for %s. Either it does not exist or it has a (circular) dependency on clojure.tools.logging." + (pr-str str)))))) + fn-sym (symbol (name fq-sym)) + fn-var (ns-resolve ns-sym fn-sym)] + (if fn-var + (fn-var) + (throw (RuntimeException. + (format "Could not resolve var for %s." + (pr-str str))))))) + +(defn- find-factory [] + (if-let [factory-fn-str (System/getProperty "clojure.tools.logging.factory")] + (call-str factory-fn-str) + (impl/find-factory))) + +(def ^:dynamic *logger-factory* + "An instance satisfying the clojure.tools.logging.impl/LoggerFactory protocol, + which allows uniform access to an underlying logging implementation. + + The default value will be obtained by invoking a no-arg function named by the + \"clojure.tools.logging.factory\" system property, or if unset, by invoking + clojure.tools.logging.impl/find-factory. + + After loading, this var can be programmatically changed to a different + LoggerFactory implementation via binding or alter-var-root. + + See the various factory functions in clojure.tools.logger.impl." + (find-factory)) diff --git a/src/main/clojure/clojure/tools/logging/impl.clj b/src/main/clojure/clojure/tools/logging/impl.clj index 76cb9c1..cac7fb1 100644 --- a/src/main/clojure/clojure/tools/logging/impl.clj +++ b/src/main/clojure/clojure/tools/logging/impl.clj @@ -32,18 +32,41 @@ (get-logger [factory logger-ns] "Returns an implementation-specific Logger by namespace.")) +(def disabled-logger + "A Logger that is not enabled and does nothing on write." + (reify Logger + (enabled? [_ _] false) + (write! [_ _ _ _]))) + +(def disabled-logger-factory + "A LoggerFactory that always provides the disabled-logger." + (reify LoggerFactory + (name [_] "disabled") + (get-logger [_ _] disabled-logger))) + +(defn class-found? + "Returns true if the Class associated with the given classname can be found + using the context ClassLoader for the current thread." + [name] + (try + (Class/forName name true (.. Thread currentThread getContextClassLoader)) + true + (catch ClassNotFoundException _ + false))) + + (defn slf4j-factory "Returns a SLF4J-based implementation of the LoggerFactory protocol, or nil if not available." [] - (try - (Class/forName "org.slf4j.Logger") + (when (class-found? "org.slf4j.Logger") (eval - `(do + `(let [; Same as is done inside LoggerFactory/getLogger(String). + factory# (org.slf4j.LoggerFactory/getILoggerFactory)] (extend org.slf4j.Logger Logger {:enabled? - (fn [logger# level#] + (fn [^org.slf4j.Logger logger# level#] (condp = level# :trace (.isTraceEnabled logger#) :debug (.isDebugEnabled logger#) @@ -55,33 +78,41 @@ :write! (fn [^org.slf4j.Logger logger# level# ^Throwable e# msg#] (let [^String msg# (str msg#)] - (condp = level# - :trace (.trace logger# msg# e#) - :debug (.debug logger# msg# e#) - :info (.info logger# msg# e#) - :warn (.warn logger# msg# e#) - :error (.error logger# msg# e#) - :fatal (.error logger# msg# e#) - (throw (IllegalArgumentException. (str level#))))))}) + (if e# + (condp = level# + :trace (.trace logger# msg# e#) + :debug (.debug logger# msg# e#) + :info (.info logger# msg# e#) + :warn (.warn logger# msg# e#) + :error (.error logger# msg# e#) + :fatal (.error logger# msg# e#) + (throw (IllegalArgumentException. (str level#)))) + (condp = level# + :trace (.trace logger# msg#) + :debug (.debug logger# msg#) + :info (.info logger# msg#) + :warn (.warn logger# msg#) + :error (.error logger# msg#) + :fatal (.error logger# msg#) + (throw (IllegalArgumentException. (str level#)))))))}) (reify LoggerFactory (name [_#] "org.slf4j") (get-logger [_# logger-ns#] - (org.slf4j.LoggerFactory/getLogger ^String (str logger-ns#)))))) - (catch Exception e nil))) + (.getLogger factory# ^String (str logger-ns#)))))))) (defn cl-factory "Returns a Commons Logging-based implementation of the LoggerFactory protocol, or nil if not available." [] - (try - (Class/forName "org.apache.commons.logging.Log") + (when (class-found? "org.apache.commons.logging.Log") (eval - `(do + `(let [; Same as is done inside LogFactory/getLog(String). + factory# (org.apache.commons.logging.LogFactory/getFactory)] (extend org.apache.commons.logging.Log Logger {:enabled? - (fn [logger# level#] + (fn [^org.apache.commons.logging.Log logger# level#] (condp = level# :trace (.isTraceEnabled logger#) :debug (.isDebugEnabled logger#) @@ -91,28 +122,35 @@ :fatal (.isFatalEnabled logger#) (throw (IllegalArgumentException. (str level#))))) :write! - (fn [logger# level# e# msg#] - (condp = level# - :trace (.trace logger# msg# e#) - :debug (.debug logger# msg# e#) - :info (.info logger# msg# e#) - :warn (.warn logger# msg# e#) - :error (.error logger# msg# e#) - :fatal (.fatal logger# msg# e#) - (throw (IllegalArgumentException. (str level#)))))}) + (fn [^org.apache.commons.logging.Log logger# level# e# msg#] + (if e# + (condp = level# + :trace (.trace logger# msg# e#) + :debug (.debug logger# msg# e#) + :info (.info logger# msg# e#) + :warn (.warn logger# msg# e#) + :error (.error logger# msg# e#) + :fatal (.fatal logger# msg# e#) + (throw (IllegalArgumentException. (str level#)))) + (condp = level# + :trace (.trace logger# msg#) + :debug (.debug logger# msg#) + :info (.info logger# msg#) + :warn (.warn logger# msg#) + :error (.error logger# msg#) + :fatal (.fatal logger# msg#) + (throw (IllegalArgumentException. (str level#))))))}) (reify LoggerFactory (name [_#] "org.apache.commons.logging") (get-logger [_# logger-ns#] - (org.apache.commons.logging.LogFactory/getLog (str logger-ns#)))))) - (catch Exception e nil))) + (.getInstance factory# (str logger-ns#)))))))) (defn log4j-factory "Returns a Log4j-based implementation of the LoggerFactory protocol, or nil if not available." [] - (try - (Class/forName "org.apache.log4j.Logger") + (when (class-found? "org.apache.log4j.Logger") (eval `(let [levels# {:trace org.apache.log4j.Level/TRACE :debug org.apache.log4j.Level/DEBUG @@ -123,32 +161,62 @@ (extend org.apache.log4j.Logger Logger {:enabled? - (fn [logger# level#] - (.isEnabledFor logger# - (or - (levels# level#) - (throw (IllegalArgumentException. (str level#)))))) + (fn [^org.apache.log4j.Logger logger# level#] + (.isEnabledFor logger# (get levels# level# level#))) :write! - (fn [logger# level# e# msg#] - (let [level# (or - (levels# level#) - (throw (IllegalArgumentException. (str level#))))] - (if-not e# - (.log logger# level# msg#) - (.log logger# level# msg# e#))))}) + (fn [^org.apache.log4j.Logger logger# level# e# msg#] + (let [level# (get levels# level# level#)] + (if e# + (.log logger# level# msg# e#) + (.log logger# level# msg#))))}) (reify LoggerFactory (name [_#] "org.apache.log4j") (get-logger [_# logger-ns#] - (org.apache.log4j.Logger/getLogger ^String (str logger-ns#)))))) - (catch Exception e nil))) + (org.apache.log4j.Logger/getLogger ^String (str logger-ns#)))))))) + +(defn log4j2-factory + "Returns a Log4j2-based implementation of the LoggerFactory protocol, or nil if + not available." + [] + (when (class-found? "org.apache.logging.log4j.Logger") + (eval + `(let [; Same as is done inside LogManager/getLogger(String). + context# (org.apache.logging.log4j.LogManager/getContext false) + levels# {:trace org.apache.logging.log4j.Level/TRACE + :debug org.apache.logging.log4j.Level/DEBUG + :info org.apache.logging.log4j.Level/INFO + :warn org.apache.logging.log4j.Level/WARN + :error org.apache.logging.log4j.Level/ERROR + :fatal org.apache.logging.log4j.Level/FATAL}] + (extend org.apache.logging.log4j.Logger + Logger + {:enabled? + (fn [logger# level#] + (.isEnabled ^org.apache.logging.log4j.Logger logger# + ^org.apache.logging.log4j.Level (get levels# level# level#))) + :write! + (fn [^org.apache.logging.log4j.Logger logger# level# e# msg#] + (let [level# (get levels# level# level#)] + (if e# + (.log ^org.apache.logging.log4j.Logger logger# + ^org.apache.logging.log4j.Level level# + ^Object msg# + ^Throwable e#) + (.log ^org.apache.logging.log4j.Logger logger# + ^org.apache.logging.log4j.Level level# + ^Object msg#))))}) + (reify LoggerFactory + (name [_#] + "org.apache.logging.log4j") + (get-logger [_# logger-ns#] + (.getLogger context# ^String (str logger-ns#)))))))) (defn jul-factory "Returns a java.util.logging-based implementation of the LoggerFactory protocol, or nil if not available." [] - (try - (Class/forName "java.util.logging.Logger") + (when (class-found? "java.util.logging.Logger") (eval `(let [levels# {:trace java.util.logging.Level/FINEST :debug java.util.logging.Level/FINE @@ -159,17 +227,11 @@ (extend java.util.logging.Logger Logger {:enabled? - (fn [logger# level#] - (.isLoggable logger# - (or - (levels# level#) - (throw (IllegalArgumentException. (str level#)))))) + (fn [^java.util.logging.Logger logger# level#] + (.isLoggable logger# (get levels# level# level#))) :write! - (fn [logger# level# ^Throwable e# msg#] - (let [^java.util.logging.Level level# - (or - (levels# level#) - (throw (IllegalArgumentException. (str level#)))) + (fn [^java.util.logging.Logger logger# level# ^Throwable e# msg#] + (let [^java.util.logging.Level level# (get levels# level# level#) ^String msg# (str msg#)] (if e# (.log logger# level# msg# e#) @@ -178,15 +240,15 @@ (name [_#] "java.util.logging") (get-logger [_# logger-ns#] - (java.util.logging.Logger/getLogger (str logger-ns#)))))) - (catch Exception e nil))) + (java.util.logging.Logger/getLogger (str logger-ns#)))))))) (defn find-factory "Returns the first non-nil value from slf4j-factory, cl-factory, - log4j-factory, and jul-factory." + log4j2-factory, log4j-factory, and jul-factory." [] (or (slf4j-factory) (cl-factory) + (log4j2-factory) (log4j-factory) (jul-factory) (throw ; this should never happen in 1.5+ diff --git a/src/main/clojure/clojure/tools/logging/readable.clj b/src/main/clojure/clojure/tools/logging/readable.clj new file mode 100644 index 0000000..b69b1c5 --- /dev/null +++ b/src/main/clojure/clojure/tools/logging/readable.clj @@ -0,0 +1,171 @@ +;; Copyright (c) Alex Taggart. All rights reserved. The use +;; and distribution terms for this software are covered by the Eclipse +;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) +;; which can be found in the file epl-v10.html at the root of this +;; distribution. By using this software in any fashion, you are +;; agreeing to be bound by the terms of this license. You must not +;; remove this notice, or any other, from this software. + +(ns ^{:author "Alex Taggart" + :doc "Logging macros that support printing message (some) arguments as + if wrapped in pr-str, the goal being to preserve their data representation + distinct from the explanatory text. See logp and logf for details regarding + which args are treated in this manner. + + Examples: + + (require '[clojure.tools.logging :as log] + '[clojure.tools.logging.readable :as logr]) + + (def x \"bar\") + ; Logged as... + (log/debug \"foo\" x \"baz\") ; foo bar baz + (logr/debug \"foo\" x \"baz\") ; foo \"bar\" baz + (log/debugf \"foo %s %s\" x \"baz\") ; foo bar baz + (logr/debugf \"foo %s %s\" x \"baz\") ; foo \"bar\" \"baz\" + "} + clojure.tools.logging.readable + (:require [clojure.tools.logging :as log] + [clojure.tools.logging.impl :as impl])) + +(defn- readable-print-args [args] + (for [arg args] + (if (string? arg) + arg + `(pr-str ~arg)))) + +(defmacro logp + "Logs a message using print style args, where message args that are not + literal strings will be printed readably, as if wrapped in pr-str. Can + optionally take a throwable as its second arg. See level-specific macros, + e.g., debug." + {:arglists '([level message & more] [level throwable message & more])} + [level x & more] + ; Why bind `*print-readably*` to true? + ; The `pr` functions do not bind `*print-readably*`, which defaults to true; + ; instead the `print` functions bind `*print-readably*` to nil, then invoke + ; `pr` functions. + ; As such, absent explicit binding, if this code happened to be invoked in a + ; context where `*print-readably*` was nil, then the non-string message args + ; passed to pr-str would still not be printed readably. + (if (or (string? x) (nil? more)) ; optimize for non-exception case + `(log/log ~level (binding [*print-readably* true] + (print-str ~@(readable-print-args (cons x more))))) + `(let [logger# (impl/get-logger log/*logger-factory* ~*ns*)] + (if (impl/enabled? logger# ~level) + (let [x# ~x] + (if (instance? Throwable x#) + (log/log* logger# ~level x# + (binding [*print-readably* true] + (print-str ~@(readable-print-args more)))) + (log/log* logger# ~level nil + (binding [*print-readably* true] + (print-str (pr-str x#) ; x is not a literal string, so pr-str x# + ~@(readable-print-args more)))))))))) + +(defn- readable-format-args [args] + (for [arg args] + `(pr-str ~arg))) + +(defmacro logf + "Logs a message using a format string and args, where all format args will be + printed readably, as if wrapped in pr-str. Can optionally take a throwable as + its second arg. See level-specific macros, e.g., debugf." + {:arglists '([level fmt & fmt-args] [level throwable fmt & fmt-args])} + [level x & more] + (if (or (instance? String x) (nil? more)) ; optimize for non-exception case + `(log/log ~level (binding [*print-readably* true] + (format ~x ~@(readable-format-args more)))) + `(let [logger# (impl/get-logger log/*logger-factory* ~*ns*)] + (if (impl/enabled? logger# ~level) + (let [x# ~x] + (if (instance? Throwable x#) ; type check only when enabled + (log/log* logger# ~level x# (binding [*print-readably* true] + (format ~(first more) ; not applied to the format string + ~@(readable-format-args (rest more))))) + (log/log* logger# ~level nil (binding [*print-readably* true] + (format x# ~@(readable-format-args more)))))))))) + +;; level-specific macros + +(defmacro trace + "Trace level logging using print-style args. See logp for details." + {:arglists '([message & more] [throwable message & more])} + [& args] + `(logp :trace ~@args)) + +(defmacro debug + "Debug level logging using print-style args. See logp for details." + {:arglists '([message & more] [throwable message & more])} + [& args] + `(logp :debug ~@args)) + +(defmacro info + "Info level logging using print-style args. See logp for details." + {:arglists '([message & more] [throwable message & more])} + [& args] + `(logp :info ~@args)) + +(defmacro warn + "Warn level logging using print-style args. See logp for details." + {:arglists '([message & more] [throwable message & more])} + [& args] + `(logp :warn ~@args)) + +(defmacro error + "Error level logging using print-style args. See logp for details." + {:arglists '([message & more] [throwable message & more])} + [& args] + `(logp :error ~@args)) + +(defmacro fatal + "Fatal level logging using print-style args. See logp for details." + {:arglists '([message & more] [throwable message & more])} + [& args] + `(logp :fatal ~@args)) + +(defmacro tracef + "Trace level logging using format. See logf for details." + {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} + [& args] + `(logf :trace ~@args)) + +(defmacro debugf + "Debug level logging using format. See logf for details." + {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} + [& args] + `(logf :debug ~@args)) + +(defmacro infof + "Info level logging using format. See logf for details." + {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} + [& args] + `(logf :info ~@args)) + +(defmacro warnf + "Warn level logging using format. See logf for details." + {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} + [& args] + `(logf :warn ~@args)) + +(defmacro errorf + "Error level logging using format. See logf for details." + {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} + [& args] + `(logf :error ~@args)) + +(defmacro fatalf + "Fatal level logging using format. See logf for details." + {:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])} + [& args] + `(logf :fatal ~@args)) + +(defmacro spyf + "Evaluates expr and may write (logf level fmt result) to the log. Returns the + result of expr. Defaults to :debug log level." + ([fmt expr] + `(spyf :debug ~fmt ~expr)) + ([level fmt expr] + `(let [a# ~expr] + (logf ~level ~fmt a#) + a#))) diff --git a/src/main/clojure/clojure/tools/logging/test.clj b/src/main/clojure/clojure/tools/logging/test.clj new file mode 100644 index 0000000..19a8ff4 --- /dev/null +++ b/src/main/clojure/clojure/tools/logging/test.clj @@ -0,0 +1,268 @@ +;; Copyright (c) Alex Taggart. All rights reserved. The use +;; and distribution terms for this software are covered by the Eclipse +;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) +;; which can be found in the file epl-v10.html at the root of this +;; distribution. By using this software in any fashion, you are +;; agreeing to be bound by the terms of this license. You must not +;; remove this notice, or any other, from this software. + + +(ns ^{:author "Alex Taggart" + :doc + "Support for testing whether logging calls are made. + + Usage example: + (require '[clojure.tools.logging :as log] + '[clojure.tools.logging.test :refer [logged? with-log]) + + (with-log + (log/info \"Hello World!\") + (log/error (Exception. \"Did a thing\") \"Error: oops\") + (logged? 'user :info #\"Hello\") ; true + (logged? 'user :error [Throwable #\"thing\"] #\"Error:\") ; true + (logged? 'user :debug \"Hi\")) ; false"} + clojure.tools.logging.test + (:import [clojure.lang Fn Keyword Namespace Symbol] + java.util.Set + java.util.regex.Pattern) + (:require [clojure.tools.logging :refer [*logger-factory*]] + [clojure.tools.logging.impl :as impl])) + + +(defmulti match-logger-ns? + "Returns true if expected matches the actual namespace. Used by + LogEntry/matches? implementation. + + Dispatches on the types of expected and actual. + + Provided methods' dispatch values and matching: + :default if equal + [Fn Object] if (f actual) is logically true + [String Namespace] if string equals namespace's string + [Symbol Namespace] if symbol equals namespace's symbol" + (fn [expected actual] + [(type expected) (type actual)])) + +(defmethod match-logger-ns? :default + [expected actual] + (= expected actual)) + +(defmethod match-logger-ns? [Fn Object] + [expected actual] + (expected actual)) + +(defmethod match-logger-ns? [String Namespace] + [expected actual] + (= expected (str actual))) + +(defmethod match-logger-ns? [Symbol Namespace] + [expected ^Namespace actual] + (= expected (.name actual))) + + + +(defmulti match-level? + "Returns true if expected matches the actual level. Used by + LogEntry/matches? implementation. + + Dispatches on the types of expected and actual. + + Provided methods' dispatch values and matching: + :default if equal + [Fn Object] if (f actual) is logically true + [Set Object] if set contains actual" + (fn [expected actual] + [(type expected) (type actual)])) + +(defmethod match-level? :default + [expected actual] + (= expected actual)) + +(defmethod match-level? [Fn Object] + [expected actual] + (expected actual)) + +(defmethod match-level? [Set Object] + [expected actual] + (contains? expected actual)) + + + +(defmulti match-throwable? + "Returns true if expected matches the actual throwable. Used by + LogEntry/matches? implementation. + + Dispatches on the types of expected and actual. If expected is a vector, will + instead use a vector of the contained types. + + Provided methods' dispatch values and matching: + :default if equal + [Fn Object] if (f actual) is logically true + [Class Object] if actual is an instance of Class + [[Class String] Throwable] ... and if string equals exception message + [[Class Pattern] Throwable] ... and if pattern matches exception message" + (fn [expected actual] + (if (vector? expected) + [(mapv type expected) (type actual)] + [(type expected) (type actual)]))) + +(defmethod match-throwable? :default + [expected actual] + (= expected actual)) + +(defmethod match-throwable? [Fn Object] + [expected actual] + (expected actual)) + +(defmethod match-throwable? [Class Object] + [expected actual] + (instance? expected actual)) + +(defmethod match-throwable? [[Class String] Throwable] + [[expected-ex expected-msg] ^Throwable actual] + (and (match-throwable? expected-ex actual) + (= expected-msg (.getMessage actual)))) + +(defmethod match-throwable? [[Class Pattern] Throwable] + [[expected-ex expected-msg] ^Throwable actual] + (and (match-throwable? expected-ex actual) + (boolean (re-find expected-msg (.getMessage actual))))) + + + +(defmulti match-message? + "Returns true if expected matches the actual message. Used by + LogEntry/matches? implementation. + + Dispatches on the types of expected and actual. + + Provided methods' dispatch values and matching: + :default if equal + [Fn Object] if (f actual) is logically true + [Pattern String] if pattern matches actual" + (fn [expected actual] + [(type expected) (type actual)])) + +(defmethod match-message? :default + [expected actual] + (= expected actual)) + +(defmethod match-message? [Fn Object] + [expected actual] + (expected actual)) + +(defmethod match-message? [Pattern String] + [expected actual] + (boolean (re-find expected actual))) + + + +(defprotocol MatchableLogEntry + (matches? [this logger-ns level throwable message])) + + + +(defrecord LogEntry [logger-ns level throwable message] + MatchableLogEntry + (matches? [_ exp-logger-ns exp-level exp-throwable exp-message] + (and (match-logger-ns? exp-logger-ns logger-ns) + (match-level? exp-level level) + (match-throwable? exp-throwable throwable) + (match-message? exp-message message)))) + + + +(defprotocol StatefulLog + (entries [this] + "Returns a vector of the entries in this log, oldest first.") + (append! [this logger-ns level throwable message] + "Returns this log with a new log entry appended.")) + + + +(defn atomic-log + "Returns a StatefulLog, appending to an atom the result of invoking + log-entry-fn with the same args as append!" + [log-entry-fn] + (let [log (atom [])] + (reify + StatefulLog + (entries [_] + (deref log)) + (append! [this logger-ns level throwable message] + (swap! log (fnil conj []) (log-entry-fn logger-ns level throwable message)) + this)))) + + + +(defn logger-factory + "Returns a LoggerFactory that will append log entries to stateful-log. Levels + are enabled when (enabled-pred logger-ns level) is true." + [stateful-log enabled-pred] + (reify impl/LoggerFactory + (name [_] "clojure.tools.logging.test/logger-factory") + (get-logger [_ logger-ns] + (reify impl/Logger + (enabled? [_ level] (enabled-pred logger-ns level)) + (write! [_ level throwable message] + (append! stateful-log logger-ns level throwable message) + nil))))) + + + +(def ^:dynamic + ^{:doc "The instance of StatefulLog used by with-log. By default unbound."} + *stateful-log*) + + + +(defn the-log + "Returns the vector of current log entries. + + Must be invoked within a context where *stateful-log* is bound to an instance + of StatefulLog containing MatchableLogEntry items (e.g., inside with-log)." + [] + (entries *stateful-log*)) + + + +(defn matches + "Returns matching log entries, otherwise nil. See match-logger-ns?, + match-level?, match-throwable?, and match-message? for the default matching + behavior applied to the given args. + + Must be invoked within a context where *stateful-log* is bound to an instance + of StatefulLog containing MatchableLogEntry items (e.g., inside with-log)." + ([logger-ns level message] + (matches logger-ns level nil message)) + ([logger-ns level throwable message] + (seq (filter #(matches? % logger-ns level throwable message) (the-log))))) + + + +(defn logged? + "Returns true if the log contains matching entries. See match-logger-ns?, + match-level?, match-throwable?, and match-message? for the default matching + behavior applied to the given args. + + Must be invoked within a context where *stateful-log* is bound to an instance + of StatefulLog containing MatchableLogEntry items (e.g., inside with-log)." + ([logger-ns level message] + (boolean (matches logger-ns level message))) + ([logger-ns level throwable message] + (boolean (matches logger-ns level throwable message)))) + + + +(defmacro with-log [& body] + "Evaluates body within a context where logging is collected. + + See logged?, matches, the-log." + `(let [stateful-log# (atomic-log ->LogEntry) + logger-factory# (logger-factory stateful-log# (constantly true))] + (binding [*stateful-log* stateful-log# + *logger-factory* logger-factory#] + ~@body))) + + + diff --git a/src/test/clojure/clojure/tools/logging/test_impl.clj b/src/test/clojure/clojure/tools/logging/test_impl.clj new file mode 100644 index 0000000..8648b3d --- /dev/null +++ b/src/test/clojure/clojure/tools/logging/test_impl.clj @@ -0,0 +1,149 @@ +(ns clojure.tools.logging.test-impl + (:use clojure.test) + (:require [clojure.tools.logging.impl :as impl])) + + +(deftest test-disabled-logger-factory + (is (= "disabled" (impl/name impl/disabled-logger-factory))) + (is (identical? impl/disabled-logger (impl/get-logger impl/disabled-logger-factory nil)))) + +(deftest test-disabled-logger + (is (= false (impl/enabled? impl/disabled-logger :fatal)))) + +(defn blacklist-loader [blacklist loader] + (proxy [ClassLoader] [] + (loadClass [name] + (if (contains? (set blacklist) name) + (throw (ClassNotFoundException. name)) + (.loadClass loader name))))) + +(deftest test-blacklist-loader + (let [white "org.slf4j.Logger" + black-1 "java.util.logging.Logger" + black-2 "org.apache.log4j.Logger" + orig-loader (.. Thread currentThread getContextClassLoader) + blacklist-loader (blacklist-loader #{black-1 black-2} orig-loader)] + (Class/forName white true orig-loader) + (Class/forName black-1 true orig-loader) + (Class/forName black-2 true orig-loader) + (Class/forName white true blacklist-loader) + (is (thrown? ClassNotFoundException + (Class/forName black-1 true blacklist-loader))) + (is (thrown? ClassNotFoundException + (Class/forName black-2 true blacklist-loader))))) + +(defmacro with-blacklist-loader [forbidden-set & body] + `(let [forbidden-set# ~forbidden-set + orig-loader# (.. Thread currentThread getContextClassLoader) + this-loader# (blacklist-loader forbidden-set# orig-loader#)] + (try + (.. Thread currentThread (setContextClassLoader this-loader#)) + ~@body + (finally + (.. Thread currentThread (setContextClassLoader orig-loader#)))))) + +(defn thread-loader [] + (.. Thread currentThread getContextClassLoader)) + +(deftest test-with-blacklist-loader + (with-blacklist-loader #{"org.apache.log4j.Logger"} + (Class/forName "org.slf4j.Logger" true (thread-loader)) + (is (thrown? ClassNotFoundException + (Class/forName "org.apache.log4j.Logger" true (thread-loader))))) + (Class/forName "org.apache.log4j.Logger" true (thread-loader))) + + +(deftest test-class-found? + (is (= true (impl/class-found? "org.apache.log4j.Logger"))) + (is (= true (impl/class-found? "org.slf4j.Logger"))) + (with-blacklist-loader #{"org.apache.log4j.Logger"} + (is (= true (impl/class-found? "org.slf4j.Logger"))) + (is (= false (impl/class-found? "org.apache.log4j.Logger"))))) + + +(deftest test-find-factory + (testing "has all loggers" + (are [classname] (impl/class-found? classname) + "org.slf4j.Logger" + "org.apache.commons.logging.Log" + "org.apache.logging.log4j.Logger" + "org.apache.log4j.Logger" + "java.util.logging.Logger")) + + (testing "finds slf4j" + (with-blacklist-loader [] + (is (= "org.slf4j" (impl/name (impl/find-factory)))))) + + (testing "finds cl" + (with-blacklist-loader ["org.slf4j.Logger"] + (is (= "org.apache.commons.logging" (impl/name (impl/find-factory)))))) + + (testing "finds log4j2" + (with-blacklist-loader ["org.slf4j.Logger" + "org.apache.commons.logging.Log"] + (is (= "org.apache.logging.log4j" (impl/name (impl/find-factory)))))) + + (testing "finds log4j" + (with-blacklist-loader ["org.slf4j.Logger" + "org.apache.commons.logging.Log" + "org.apache.logging.log4j.Logger"] + (is (= "org.apache.log4j" (impl/name (impl/find-factory)))))) + + (testing "finds jul" + (with-blacklist-loader ["org.slf4j.Logger" + "org.apache.commons.logging.Log" + "org.apache.logging.log4j.Logger" + "org.apache.log4j.Logger"] + (is (= "java.util.logging" (impl/name (impl/find-factory)))))) + + (testing "finds none" + (with-blacklist-loader ["org.slf4j.Logger" + "org.apache.commons.logging.Log" + "org.apache.logging.log4j.Logger" + "org.apache.log4j.Logger" + "java.util.logging.Logger"] + (is (thrown? RuntimeException (impl/find-factory)))))) + + +(let [[factory level] (try + [(impl/log4j2-factory) (eval 'org.apache.logging.log4j.Level/FATAL)] + (catch UnsupportedClassVersionError _ + ; This will happen when not using a 1.7+ jvm, e.g., + ; during matrix testing. Use the no-op factory + ; to get past testing log4j2. + [impl/disabled-logger-factory nil]))] + (def maybe-log4j2-factory factory) + (def maybe-log4j2-level level)) + +(def logger-factories [impl/disabled-logger-factory + (impl/slf4j-factory) + (impl/cl-factory) + maybe-log4j2-factory + (impl/log4j-factory) + (impl/jul-factory)]) + +(deftest test-logger-factory-impls-satisfy + (doseq [lf logger-factories] + (is (satisfies? impl/LoggerFactory lf)))) + +(deftest test-logger-impls-satisfy + (doseq [lf logger-factories] + (is (satisfies? impl/Logger (impl/get-logger lf "logger-ns"))))) + +(deftest test-enabled-non-kw-levels + ; Just checking that the call doesn't blow up. + (are [lf level] (let [logger (impl/get-logger lf "logger-ns")] + (impl/enabled? logger level) + true) + maybe-log4j2-factory maybe-log4j2-level + (impl/log4j-factory) org.apache.log4j.Level/FATAL + (impl/jul-factory) java.util.logging.Level/SEVERE)) + +(deftest test-write-non-kw-levels + ; Just checking that the call doesn't blow up. + (are [lf level] (let [logger (impl/get-logger lf "logger-ns")] + (impl/write! logger level nil "message") + true) + maybe-log4j2-factory maybe-log4j2-level + (impl/log4j-factory) org.apache.log4j.Level/FATAL + (impl/jul-factory) java.util.logging.Level/SEVERE)) diff --git a/src/test/clojure/clojure/tools/logging/test_readable.clj b/src/test/clojure/clojure/tools/logging/test_readable.clj new file mode 100644 index 0000000..3ba09e2 --- /dev/null +++ b/src/test/clojure/clojure/tools/logging/test_readable.clj @@ -0,0 +1,247 @@ +(ns clojure.tools.logging.test-readable + (:use clojure.test) + (:require + [clojure.set :as set] + [clojure.tools.logging.readable :refer :all] + [clojure.tools.logging.test :as log-test :refer [logged? with-log]])) + +(deftest logp-single-eval + (with-log + (let [cnt (atom 0)] + (logp :debug (str (swap! cnt inc))) + (logp :debug (str (swap! cnt inc)) :foo) + (logp :debug (Exception. (str (swap! cnt inc))) (str (swap! cnt inc))) + (logp :debug (Exception. (str (swap! cnt inc))) (str (swap! cnt inc)) :foo) + (is (== 6 @cnt))))) + +(deftest logf-single-eval + (with-log + (let [cnt (atom 0)] + (logf :debug (str (swap! cnt inc))) + (logf :debug (str (swap! cnt inc)) :foo) + (logf :debug (Exception. (str (swap! cnt inc))) (str (swap! cnt inc))) + (logf :debug (Exception. (str (swap! cnt inc))) (str (swap! cnt inc)) :foo) + (is (== 6 @cnt))))) + +(deftest logp-msg1 + (with-log + (logp :debug "hello") + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello"))) + (with-log + (let [hello "hello"] + (logp :debug hello)) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "\"hello\""))) + (with-log + (let [hello "hello"] + (binding [*print-readably* nil] + (logp :debug hello))) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "\"hello\""))) + (with-log + (logp :debug (pr-str "hello")) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "\"\\\"hello\\\"\""))) + (with-log + (logp :debug (print-str "hello")) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "\"hello\"")))) + +(deftest logp-msg2 + (let [hello "hello" + world "world"] + (with-log + (logp :debug "hello" "world") + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello world"))) + (with-log + (logp :debug "hello" world) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello \"world\""))) + (with-log + (logp :debug hello "world") + (is (logged? "clojure.tools.logging.test-readable" :debug nil "\"hello\" world"))) + (with-log + (logp :debug hello world) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "\"hello\" \"world\""))) + (with-log + (binding [*print-readably* nil] + (logp :debug hello world)) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "\"hello\" \"world\""))))) + +(deftest logp-ex0 + (let [e (Exception.)] + (with-log + (logp :debug e) + (is (logged? "clojure.tools.logging.test-readable" :debug nil (print-str (pr-str e))))) + (with-log + (binding [*print-readably* nil] + (logp :debug e)) + (is (logged? "clojure.tools.logging.test-readable" :debug nil (print-str (pr-str e))))))) + +(deftest logp-ex1 + (let [e (Exception.) + hello "hello"] + (with-log + (logp :debug e "hello") + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello"))) + (with-log + (logp :debug e hello) + (is (logged? "clojure.tools.logging.test-readable" :debug e "\"hello\""))) + (with-log + (binding [*print-readably* nil] + (logp :debug e hello)) + (is (logged? "clojure.tools.logging.test-readable" :debug e "\"hello\""))))) + +(deftest logp-ex2 + (let [e (Exception.) + hello "hello" + world "world"] + (with-log + (logp :debug e "hello" "world") + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello world"))) + (with-log + (logp :debug e "hello" world) + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello \"world\""))) + (with-log + (logp :debug e hello "world") + (is (logged? "clojure.tools.logging.test-readable" :debug e "\"hello\" world"))) + (with-log + (logp :debug e hello world) + (is (logged? "clojure.tools.logging.test-readable" :debug e "\"hello\" \"world\""))) + (with-log + (binding [*print-readably* nil] + (logp :debug e hello world)) + (is (logged? "clojure.tools.logging.test-readable" :debug e "\"hello\" \"world\""))))) + + +(deftest logf-msg1 + (with-log + (logf :debug "hello") + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello"))) + (with-log + (let [hello "hello"] + (logf :debug hello)) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello"))) + (with-log + (let [hello "hello"] + (binding [*print-readably* nil] + (logf :debug hello))) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello"))) + (with-log + (logf :debug (pr-str "hello")) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "\"hello\""))) + (with-log + (logf :debug (print-str "hello")) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello")))) + +(deftest logf-msg2 + (let [hello "hello %s" + world "world"] + (with-log + (logf :debug "hello %s" "world") + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello \"world\""))) + (with-log + (logf :debug "hello %s" world) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello \"world\""))) + (with-log + (logf :debug hello "world") + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello \"world\""))) + (with-log + (logf :debug hello world) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello \"world\""))) + (with-log + (binding [*print-readably* nil] + (logf :debug hello world)) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "hello \"world\""))))) + +(deftest logf-ex0 + (is (thrown? ClassCastException (logf :debug (Exception.))))) + +(deftest logf-ex1 + (let [e (Exception.) + hello "hello"] + (with-log + (logf :debug e "hello") + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello"))) + (with-log + (logf :debug e hello) + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello"))) + (with-log + (binding [*print-readably* nil] + (logf :debug e hello)) + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello"))))) + +(deftest logf-ex2 + (let [e (Exception.) + hello "hello %s" + world "world"] + (with-log + (logf :debug e "hello %s" "world") + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello \"world\""))) + (with-log + (logf :debug e "hello %s" world) + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello \"world\""))) + (with-log + (logf :debug e hello "world") + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello \"world\""))) + (with-log + (logf :debug e hello world) + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello \"world\""))) + (with-log + (binding [*print-readably* nil] + (logf :debug e hello world)) + (is (logged? "clojure.tools.logging.test-readable" :debug e "hello \"world\""))))) + + +(deftest spyf-default + (with-log + (spyf "result: %s" (str "hello" " " "world")) + (is (logged? "clojure.tools.logging.test-readable" :debug nil "result: \"hello world\"")))) + +(deftest spyf-level + (doseq [level #{:trace :debug :info :warn :error :fatal}] + (with-log + (spyf level "result: %s" (str "hello" " " "world")) + (is (logged? "clojure.tools.logging.test-readable" level nil "result: \"hello world\""))))) + + +(deftest println-style + (are [f kw] (with-log + (f "hello" "world") + (logged? "clojure.tools.logging.test-readable" kw nil "hello world")) + trace :trace + debug :debug + info :info + warn :warn + error :error + fatal :fatal)) + +(deftest println-style-ex + (let [e (Exception.)] + (are [f kw] (with-log + (f e "hello" "world") + (logged? "clojure.tools.logging.test-readable" kw e "hello world")) + trace :trace + debug :debug + info :info + warn :warn + error :error + fatal :fatal))) + +(deftest format-style + (are [f kw] (with-log + (f "%s %s" "hello" "world") + (logged? "clojure.tools.logging.test-readable" kw nil "\"hello\" \"world\"")) + tracef :trace + debugf :debug + infof :info + warnf :warn + errorf :error + fatalf :fatal)) + +(deftest format-style-ex + (let [e (Exception.)] + (are [f kw] (with-log + (f e "%s %s" "hello" "world") + (logged? "clojure.tools.logging.test-readable" kw e "\"hello\" \"world\"")) + tracef :trace + debugf :debug + infof :info + warnf :warn + errorf :error + fatalf :fatal))) diff --git a/src/test/clojure/clojure/tools/logging/test_test.clj b/src/test/clojure/clojure/tools/logging/test_test.clj new file mode 100644 index 0000000..9c6b3a1 --- /dev/null +++ b/src/test/clojure/clojure/tools/logging/test_test.clj @@ -0,0 +1,132 @@ +(ns clojure.tools.logging.test-test + (:require [clojure.test :refer [are deftest is testing]] + [clojure.tools.logging :as log] + [clojure.tools.logging.impl :as impl] + [clojure.tools.logging.test :refer :all])) + +(def this-ns (the-ns 'clojure.tools.logging.test-test)) + + +; Note using (= true/false ...) in order to prove the result is a boolean. + +(deftest test-match-logger-ns? + (are [expected actual] (= true (match-logger-ns? expected actual)) + 1 1 + keyword? :kw + "clojure.tools.logging.test-test" this-ns + 'clojure.tools.logging.test-test this-ns) + + (are [expected actual] (= false (match-logger-ns? expected actual)) + 2 1 + symbol? :kw + "xxx" this-ns + 'xxx this-ns)) + + +(deftest test-match-level? + (are [expected actual] (= true (match-level? expected actual)) + 1 1 + keyword? :kw + #{:a} :a) + + (are [expected actual] (= false (match-level? expected actual)) + 2 1 + symbol? :kw + #{:b} :a)) + + +(deftest test-match-throwable? + (are [expected actual] (= true (match-throwable? expected actual)) + 1 1 + keyword? :kw + Throwable (Exception.) + [Throwable "oops"] (Exception. "oops") + [Throwable #"o+"] (Exception. "oops")) + + (are [expected actual] (= false (match-throwable? expected actual)) + 2 1 + symbol? :kw + RuntimeException (Exception.) + [RuntimeException "oops"] (Exception. "oops") + [Exception "ok"] (Exception. "oops") + [RuntimeException #"o+"] (Exception. "oops") + [Exception #"a+"] (Exception. "oops"))) + + +(deftest test-match-message? + (are [expected actual] (= true (match-message? expected actual)) + 1 1 + keyword? :kw + #"o+" "oops") + + (are [expected actual] (= false (match-message? expected actual)) + 2 1 + symbol? :kw + #"a+" "oops")) + +(deftest test-log-entry + (let [log-entry (->LogEntry :logger-ns-1 :level-1 :throwable-1 :message-1)] + (is (matches? log-entry :logger-ns-1 :level-1 :throwable-1 :message-1)) + (are [exp-logger-ns exp-level exp-throwable exp-message] + (not (matches? log-entry exp-logger-ns exp-level exp-throwable exp-message)) + :logger-ns-2 :level-1 :throwable-1 :message-1 + :logger-ns-1 :level-2 :throwable-1 :message-1 + :logger-ns-1 :level-1 :throwable-2 :message-1 + :logger-ns-1 :level-1 :throwable-1 :message-2))) + + +(deftest test-atomic-log + (is (= [] (entries (atomic-log ->LogEntry)))) + (let [log (-> (atomic-log ->LogEntry) + (append! :logger-ns-1 :level-1 :throwable-1 :message-1) + (append! :logger-ns-2 :level-2 :throwable-2 :message-2))] + (is (vector? (entries log))) + (is (= [(->LogEntry :logger-ns-1 :level-1 :throwable-1 :message-1) + (->LogEntry :logger-ns-2 :level-2 :throwable-2 :message-2)] + (entries log))))) + + +(deftest test-logger-factory + (let [stateful-log (atomic-log ->LogEntry) + logger-factory (logger-factory stateful-log (constantly true)) + logger-1 (impl/get-logger logger-factory :logger-ns-1) + logger-2 (impl/get-logger logger-factory :logger-ns-2)] + (is (= "clojure.tools.logging.test/logger-factory" + (impl/name logger-factory))) + (are [level] (impl/enabled? logger-1 level) + :trace :debug :info :warn :error :fatal :foobar) + (impl/write! logger-1 :level-1 :throwable-1 :message-1) + (impl/write! logger-2 :level-2 :throwable-2 :message-2) + (is (= [(->LogEntry :logger-ns-1 :level-1 :throwable-1 :message-1) + (->LogEntry :logger-ns-2 :level-2 :throwable-2 :message-2)] + (entries stateful-log))))) + + +(deftest test-with-log + (let [ex (ex-info "oops" {:a 1})] + (with-log + (log/debug "debugging") + (log/error ex "erroring") + (is (= true (logged? this-ns :debug "debugging"))) + (is (= true (logged? this-ns :error ex "erroring"))) + (is (= false (logged? this-ns :fatal "fataling")))))) + + +; Test extending example + +(defrecord ContextualMessage [text context]) + +(defmethod match-message? [clojure.lang.IPersistentVector ContextualMessage] + [[expected-text expected-context] actual] + (and (= expected-text (:text actual)) + (= expected-context (-> actual :context (select-keys (keys expected-context)))))) + +(deftest test-with-log-custom-message + (let [msg (->ContextualMessage "stuff" {:a 1 :b 2})] + (with-log + (log/log :debug msg) + (is (= [(->LogEntry this-ns :debug nil msg)] (the-log))) + (is (logged? this-ns :debug ["stuff" {:a 1}])) + (is (logged? this-ns :debug ["stuff" {:a 1 :b 2}])) + (is (not (logged? this-ns :debug ["stuff" {:a 1 :c 2}])))))) + diff --git a/src/test/clojure/clojure/tools/test_logging.clj b/src/test/clojure/clojure/tools/test_logging.clj index 79b48e4..e84d8b0 100644 --- a/src/test/clojure/clojure/tools/test_logging.clj +++ b/src/test/clojure/clojure/tools/test_logging.clj @@ -1,324 +1,321 @@ (ns clojure.tools.test-logging - [:use clojure.test - clojure.tools.logging] - [:require [clojure.tools.logging.impl :as impl]]) - -(deftest test-impls - (are [lf] (binding [*logger-factory* lf] - (enabled? :fatal)) - (impl/slf4j-factory) - (impl/cl-factory) - (impl/log4j-factory) - (impl/jul-factory))) - - -(def ^{:dynamic true} *entries* (atom [])) - -(defn test-factory [enabled-set] - (reify impl/LoggerFactory - (name [_] "test factory") - (get-logger [_ log-ns] - (reify impl/Logger - (enabled? [_ level] (contains? enabled-set level)) - (write! [_ lvl ex msg] - (swap! *entries* conj [(str log-ns) lvl ex msg])))))) - -(use-fixtures :once - (fn [f] - (binding [*logger-factory* - (test-factory #{:trace :debug :info :warn :error :fatal})] - (f)))) - -(use-fixtures :each - (fn [f] - (f) - (swap! *entries* (constantly [])))) - + (:use clojure.test) + (:require + [clojure.set :as set] + [clojure.tools.logging :as log :refer :all] + [clojure.tools.logging.impl :as impl] + [clojure.tools.logging.test :as log-test :refer [logged? + matches]])) + + +(defn log-entry-with-thread + "Returns a log entry that also captures the current thread." + [logger-ns level throwable message] + (assoc (log-test/->LogEntry logger-ns level throwable message) + ::thread (Thread/currentThread))) + +(defn same-thread? + "Returns true if the thread that created the log entry is the current thread." + [log-entry] + (when-not (::thread log-entry) + (throw (ex-info "Log entry does not have a thread." log-entry))) + (identical? (::thread log-entry) + (Thread/currentThread))) + +(defn direct-logged? + "Returns true if there is a matching entry that also was created with the + current thread, i.e., not via an agent." + [logger-ns level throwable message] + (->> (log-test/matches logger-ns level throwable message) + (filter same-thread?) + seq + boolean)) + +(defn agent-logged? + "Returns true if there is a matching entry that also was created with a thread + other than the current thread, i.e., via an agent." + [logger-ns level throwable message] + (->> (log-test/matches logger-ns level throwable message) + (remove same-thread?) + seq + boolean)) + +(defmacro with-log + [& body] + `(let [stateful-log# (log-test/atomic-log log-entry-with-thread) + logger-factory# (log-test/logger-factory stateful-log# (constantly true))] + (binding [log-test/*stateful-log* stateful-log# + *logger-factory* logger-factory#] + ~@body))) + +(defmacro with-log-level [level & body] + `(let [stateful-log# (log-test/atomic-log log-entry-with-thread) + logger-factory# (log-test/logger-factory stateful-log# #(= ~level %2))] + (binding [log-test/*stateful-log* stateful-log# + *logger-factory* logger-factory#] + ~@body))) + +(deftest log-yields-nil + (let [enabled-logger (reify impl/Logger + (enabled? [_ _] true) + (write! [_ _ _ _] :non-nil)) + disabled-logger (reify impl/Logger + (enabled? [_ _] false) + (write! [_ _ _ _] :non-nil))] + (binding [*force* :agent] + (is (nil? (log* enabled-logger :debug nil :msg))) + (is (nil? (log* disabled-logger :debug nil :msg)))) + (binding [*force* :direct] + (is (nil? (log* enabled-logger :debug nil :msg))) + (is (nil? (log* disabled-logger :debug nil :msg)))))) + +(deftest log-single-eval + (with-log + (let [cnt (atom 0)] + (log :debug (swap! cnt inc)) + (log :debug (Exception. (str (swap! cnt inc))) (swap! cnt inc)) + (is (== 3 @cnt))))) + +(deftest logp-single-eval + (with-log + (let [cnt (atom 0)] + (logp :debug (str (swap! cnt inc))) + (logp :debug (str (swap! cnt inc)) :foo) + (logp :debug (Exception. (str (swap! cnt inc))) (str (swap! cnt inc))) + (logp :debug (Exception. (str (swap! cnt inc))) (str (swap! cnt inc)) :foo) + (is (== 6 @cnt))))) + +(deftest logf-single-eval + (with-log + (let [cnt (atom 0)] + (logf :debug (str (swap! cnt inc))) + (logf :debug (str (swap! cnt inc)) :foo) + (logf :debug (Exception. (str (swap! cnt inc))) (str (swap! cnt inc))) + (logf :debug (Exception. (str (swap! cnt inc))) (str (swap! cnt inc)) :foo) + (is (== 6 @cnt))))) (deftest log-msg - (log :debug "foo") - (is (= ["clojure.tools.test-logging" - :debug - nil - "foo"] - (peek @*entries*)))) + (with-log + (log :debug "foo") + (is (logged? "clojure.tools.test-logging" + :debug + nil + "foo")))) (deftest log-ex - (let [e (Exception.)] - (log :debug e "foo") - (is (= ["clojure.tools.test-logging" - :debug - e - "foo"] - (peek @*entries*))))) + (with-log + (let [e (Exception.)] + (log :debug e "foo") + (is (logged? "clojure.tools.test-logging" + :debug + e + "foo"))))) (deftest log-custom-ns - (let [e (Exception.)] - (log "other.ns" :debug e "foo") - (is (= ["other.ns" - :debug - e - "foo"] - (peek @*entries*))))) - -(comment ; Tests failing on build machine for some unknown reason. - ; See http://groups.google.com/group/clojure-dev/browse_thread/thread/fde32342f3c006bd -(deftest log-tx-agent - (let [flag (atom false) - so send-off] - (binding [send-off (fn [a f & args] - (compare-and-set! flag false true) - (apply so a f args))] + (with-log + (let [e (Exception.)] + (log "other.ns" :debug e "foo") + (is (logged? "other.ns" + :debug + e + "foo"))))) + +(def all-levels #{:trace :debug :info :warn :error :fatal}) +(def default-tx-agent-levels #{:info :warn}) +(def default-no-tx-agent-levels (set/difference all-levels default-tx-agent-levels)) + +(deftest log-tx-agent-default + (doseq [level default-tx-agent-levels] + (with-log-level level (dosync - (log :info "foo"))) - (await *logging-agent*) - (is (= ["clojure.tools.test-logging" - :info - nil - "foo"] - (peek @*entries*))) - (is (true? @flag)))) - -(deftest log-tx-noagent - (let [flag (atom false) - so send-off] - (binding [send-off (fn [a f & args] - (compare-and-set! flag false true) - (apply so a f args))] - (dosync - (log :error "foo"))) - (await *logging-agent*) - (is (= ["clojure.tools.test-logging" - :error - nil - "foo"] - (peek @*entries*))) - (is (false? @flag)))) - -(deftest log-alter-tx-agent-levels - (let [flag (atom false) - so send-off] - (binding [send-off (fn [a f & args] - (compare-and-set! flag false true) - (apply so a f args)) - *tx-agent-levels* #{:error}] + (log level "foo")) + (await *logging-agent*) + (is (agent-logged? "clojure.tools.test-logging" level nil "foo"))))) + +(deftest log-no-tx-agent-default + (doseq [level default-no-tx-agent-levels] + (with-log-level level (dosync - (log :error "foo"))) - (await *logging-agent*) - (is (= ["clojure.tools.test-logging" - :error - nil - "foo"] - (peek @*entries*))) - (is (true? @flag)))) + (log level "foo")) + (await *logging-agent*) + (is (direct-logged? "clojure.tools.test-logging" level nil "foo"))))) + +(deftest log-tx-agent-custom + (doseq [level default-no-tx-agent-levels] + (binding [*tx-agent-levels* default-no-tx-agent-levels] + (with-log-level level + (dosync + (log level "foo")) + (await *logging-agent*) + (is (agent-logged? "clojure.tools.test-logging" level nil "foo")))))) + +(deftest log-no-tx-agent-custom + (doseq [level default-tx-agent-levels] + (binding [*tx-agent-levels* default-no-tx-agent-levels] + (with-log-level level + (dosync + (log level "foo")) + (await *logging-agent*) + (is (direct-logged? "clojure.tools.test-logging" level nil "foo")))))) (deftest log-force-agent - (let [flag (atom false) - so send-off] - (binding [send-off (fn [a f & args] - (compare-and-set! flag false true) - (apply so a f args)) - *force* :agent] - (log :debug "foo")) - (await *logging-agent*) - (is (= ["clojure.tools.test-logging" - :debug - nil - "foo"] - (peek @*entries*))) - (is (true? @flag)))) + (doseq [level all-levels] + (binding [*force* :agent] + (with-log-level level + (dosync + (log level "foo")) + (await *logging-agent*) + (is (agent-logged? "clojure.tools.test-logging" level nil "foo")))))) (deftest log-force-direct - (let [flag (atom false) - so send-off] - (binding [send-off (fn [a f & args] - (compare-and-set! flag false true) - (apply so a f args)) - *force* :direct] - (dosync - (log :info "foo"))) - (await *logging-agent*) - (is (= ["clojure.tools.test-logging" - :info - nil - "foo"] - (peek @*entries*))) - (is (false? @flag)))) -) + (doseq [level all-levels] + (binding [*force* :direct] + (with-log-level level + (dosync + (log level "foo")) + (await *logging-agent*) + (is (direct-logged? "clojure.tools.test-logging" level nil "foo")))))) (deftest logp-msg-no-optimize - (let [a "foo" - b "bar"] - (logp :debug a b)) - (is (= ["clojure.tools.test-logging" - :debug - nil - "foo bar"] - (peek @*entries*)))) + (with-log + (let [a "foo" + b "bar"] + (logp :debug a b)) + (is (logged? "clojure.tools.test-logging" :debug nil "foo bar")))) (deftest logp-msg1 - (logp :debug "hello") - (is (= ["clojure.tools.test-logging" - :debug - nil - "hello"] - (peek @*entries*)))) + (with-log + (logp :debug "hello") + (is (logged? "clojure.tools.test-logging" :debug nil "hello")))) (deftest logp-msg2 - (logp :debug "hello" "world") - (is (= ["clojure.tools.test-logging" - :debug - nil - "hello world"] - (peek @*entries*)))) + (with-log + (logp :debug "hello" "world") + (is (logged? "clojure.tools.test-logging" :debug nil "hello world")))) (deftest logp-ex0 - (let [e (Exception.)] - (logp :debug e) - (is (= ["clojure.tools.test-logging" - :debug - nil - (print-str e)] - (peek @*entries*))))) + (with-log + (let [e (Exception.)] + (logp :debug e) + (is (logged? "clojure.tools.test-logging" :debug nil (print-str e)))))) (deftest logp-ex1 - (let [e (Exception.)] - (logp :debug e "hello") - (is (= ["clojure.tools.test-logging" - :debug - e - "hello"] - (peek @*entries*))))) + (with-log + (let [e (Exception.)] + (logp :debug e "hello") + (is (logged? "clojure.tools.test-logging" :debug e "hello"))))) (deftest logp-ex2 - (let [e (Exception.)] - (logp :debug e "hello" "world") - (is (= ["clojure.tools.test-logging" - :debug - e - "hello world"] - (peek @*entries*))))) + (with-log + (let [e (Exception.)] + (logp :debug e "hello" "world") + (is (logged? "clojure.tools.test-logging" :debug e "hello world"))))) (deftest logf-msg-no-optimize - (let [a "foo %s" - b "bar"] - (logf :debug a b)) - (is (= ["clojure.tools.test-logging" - :debug - nil - "foo bar"] - (peek @*entries*)))) + (with-log + (let [a "foo %s" + b "bar"] + (logf :debug a b)) + (is (logged? "clojure.tools.test-logging" :debug nil "foo bar")))) (deftest logf-msg1 - (logf :debug "hello") - (is (= ["clojure.tools.test-logging" - :debug - nil - "hello"] - (peek @*entries*)))) + (with-log + (logf :debug "hello") + (is (logged? "clojure.tools.test-logging" :debug nil "hello")))) (deftest logf-msg3 - (logf :debug "%s %s" "hello" "world") - (is (= ["clojure.tools.test-logging" - :debug - nil - "hello world"] - (peek @*entries*)))) + (with-log + (logf :debug "%s %s" "hello" "world") + (is (logged? "clojure.tools.test-logging" :debug nil "hello world")))) (deftest logf-ex0 - (is (thrown? Exception (logf :debug (Exception.))))) + (is (thrown? ClassCastException (logf :debug (Exception.))))) (deftest logf-ex3 - (let [e (Exception.)] - (logf :debug e "%s %s" "hello" "world") - (is (= ["clojure.tools.test-logging" - :debug - e - "hello world"] - (peek @*entries*))))) + (with-log + (let [e (Exception.)] + (logf :debug e "%s %s" "hello" "world") + (is (logged? "clojure.tools.test-logging" :debug e "hello world"))))) (deftest enabled-true - (is (= true (enabled? :fatal)))) + (with-log-level :fatal + (is (enabled? :fatal)))) (deftest enabled-false - (binding [*logger-factory* (test-factory #{})] - (is (= false (enabled? :fatal))))) + (with-log-level :debug + (is (not (enabled? :fatal))))) (deftest spy-default - (spy (+ 4 5)) - (is (= ["clojure.tools.test-logging" - :debug - nil - (format "(+ 4 5)%n=> 9")] - (peek @*entries*)))) + (with-log-level :debug + (spy (+ 4 5)) + (is (logged? "clojure.tools.test-logging" :debug nil (format "(+ 4 5)%n=> 9"))))) (deftest spy-level - (spy :fatal (+ 4 5)) - (is (= ["clojure.tools.test-logging" - :fatal - nil - (format "(+ 4 5)%n=> 9")] - (peek @*entries*)))) - -(comment + (doseq [level all-levels] + (with-log-level level + (spy level (+ 4 5)) + (is (logged? "clojure.tools.test-logging" level nil (format "(+ 4 5)%n=> 9")))))) + +(deftest spyf-default + (with-log-level :debug + (spyf "result: %s" (+ 4 5)) + (is (logged? "clojure.tools.test-logging" :debug nil (format "result: 9"))))) + +(deftest spyf-level + (doseq [level all-levels] + (with-log-level level + (spyf level "result: %s" (+ 4 5)) + (is (logged? "clojure.tools.test-logging" level nil (format "result: 9")))))) + (deftest capturing - (log-capture! "foobar") - (.println System/out "hello world") - (is (= ["foobar" - :info - nil - "hello world"] - (peek @*entries*))) - (.println System/err "oh noes") - (is (= ["foobar" - :error - nil - "oh noes"] - (peek @*entries*))) - (log-uncapture!)) + (with-log + (log-capture! "foobar") + (.println System/out "hello world") + (is (logged? "foobar" :info nil "hello world")) + (log-uncapture!)) + + (with-log + (log-capture! "foobar") + (.println System/err "oh noes") + (is (logged? "foobar" :error nil "oh noes")) + (log-uncapture!))) (deftest capturing-level - (log-capture! "foobar" :error :fatal) - (.println System/out "hello world") - (is (= ["foobar" - :error - nil - "hello world"] - (peek @*entries*))) - (.println System/err "oh noes") - (is (= ["foobar" - :fatal - nil - "oh noes"] - (peek @*entries*))) - (log-uncapture!)) + (with-log + (log-capture! "foobar" :error :fatal) + (.println System/out "hello world") + (is (logged? "foobar" :error nil "hello world")) + (log-uncapture!)) + + (with-log + (log-capture! "foobar" :error :fatal) + (.println System/err "oh noes") + (is (logged? "foobar" :fatal nil "oh noes")) + (log-uncapture!))) + (deftest with-logs-default - (with-logs "foobar" (println "hello world")) - (is (= ["foobar" - :info - nil - "hello world"] - (peek @*entries*)))) + (with-log + (with-logs "foobar" + (println "hello world")) + (is (logged? "foobar" :info nil "hello world")))) (deftest with-logs-level - (with-logs ["foobar" :fatal :fatal] (println "hello world")) - (is (= ["foobar" - :fatal - nil - "hello world"] - (peek @*entries*)))) -) + (with-log + (with-logs ["foobar" :error :fatal] + (println "hello world")) + (is (logged? "foobar" :error nil "hello world"))) + + (with-log + (with-logs ["foobar" :error :fatal] + (binding [*out* *err*] + (println "hello world"))) + (is (logged? "foobar" :fatal nil "hello world")))) (deftest println-style - (are [f kw] - (= ["clojure.tools.test-logging" - kw - nil - "hello world"] - (do - (f "hello" "world") - (peek @*entries*))) + (are [f kw] (with-log + (f "hello" "world") + (logged? "clojure.tools.test-logging" kw nil "hello world")) trace :trace debug :debug info :info @@ -328,14 +325,9 @@ (deftest println-style-ex (let [e (Exception.)] - (are [f kw] - (= ["clojure.tools.test-logging" - kw - e - "hello world"] - (do - (f e "hello" "world") - (peek @*entries*))) + (are [f kw] (with-log + (f e "hello" "world") + (logged? "clojure.tools.test-logging" kw e "hello world")) trace :trace debug :debug info :info @@ -344,14 +336,9 @@ fatal :fatal))) (deftest format-style - (are [f kw] - (= ["clojure.tools.test-logging" - kw - nil - "hello world"] - (do - (f "%s %s" "hello" "world") - (peek @*entries*))) + (are [f kw] (with-log + (f "%s %s" "hello" "world") + (logged? "clojure.tools.test-logging" kw nil "hello world")) tracef :trace debugf :debug infof :info @@ -361,17 +348,43 @@ (deftest format-style-ex (let [e (Exception.)] - (are [f kw] - (= ["clojure.tools.test-logging" - kw - e - "hello world"] - (do - (f e "%s %s" "hello" "world") - (peek @*entries*))) + (are [f kw] (with-log + (f e "%s %s" "hello" "world") + (logged? "clojure.tools.test-logging" kw e "hello world")) tracef :trace debugf :debug infof :info warnf :warn errorf :error fatalf :fatal))) + + +(deftest test-call-str + (testing "throws exception if input is not fully-qualified" + (is (thrown-with-msg? RuntimeException #"fully-qualified" + (#'log/call-str "foobar")))) + + (testing "throws exception if ns does not exist" + (is (thrown-with-msg? RuntimeException #"resolve namespace" + (#'log/call-str "missing.ns/some-fn")))) + + (testing "throws exception if fn does not exist" + (is (thrown-with-msg? RuntimeException #"resolve var" + (#'log/call-str "external.ns/does-not-exist-fn")))) + + (testing "yields the right factory when specified" + (is (= "external.ns/good-fn" + (impl/name (#'log/call-str "external.ns/factory")))))) + + +(deftest test-find-factory + (testing "when system property is unset, invokes impl/find-factory" + (System/clearProperty "clojure.tools.logging.factory") + (is (= (impl/name (impl/find-factory)) (impl/name (#'log/find-factory))))) + + (testing "when system propery is set, yields the results" + (System/setProperty "clojure.tools.logging.factory" "external.ns/factory") + (is (= "external.ns/good-fn" (impl/name (#'log/find-factory))))) + + (System/clearProperty "clojure.tools.logging.factory")) + diff --git a/src/test/clojure/external/ns.clj b/src/test/clojure/external/ns.clj new file mode 100644 index 0000000..8c29c86 --- /dev/null +++ b/src/test/clojure/external/ns.clj @@ -0,0 +1,8 @@ +(ns external.ns + "Used by clojure.tools.logging.test-logging." + (:require [clojure.tools.logging.impl :as impl])) + +(defn factory [] + (reify impl/LoggerFactory + (name [_] "external.ns/good-fn") + (get-logger [_ _] (impl/disabled-logger)))) diff --git a/src/test/clojure/log4j2.xml b/src/test/clojure/log4j2.xml new file mode 100644 index 0000000..3b21b32 --- /dev/null +++ b/src/test/clojure/log4j2.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Configuration status="WARN"> + <Appenders> + <Console name="Console" target="SYSTEM_OUT"> + <PatternLayout pattern="%d %-5p %c: %m%n"/> + </Console> + </Appenders> + <Loggers> + <Root level="fatal"> + <AppenderRef ref="Console"/> + </Root> + </Loggers> +</Configuration> \ No newline at end of file -- GitLab