├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── ReleaseNotes.md ├── profiles.clj ├── project.clj ├── src └── com │ └── palletops │ └── log_config │ ├── slf4j.clj │ ├── timbre.clj │ ├── timbre │ ├── async_channel.clj │ ├── tools_logging.clj │ └── wrap.clj │ └── tools_logging.clj └── test └── com └── palletops └── log_config ├── slf4j_test.clj ├── timbre ├── async_channel_test.clj └── wrap_test.clj └── timbre_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: clojure 2 | lein: lein2 3 | before_script: 4 | - lein2 version 5 | script: lein2 test 6 | after_success: 7 | - lein2 pallet-release push 8 | env: 9 | global: 10 | secure: WuIIrCLoywneHfr3CVIkih2Qh0sCDd4eMWDYvKEU28GKHT4ZCylTrCHvhpVmUK8wb7C1gmielW3fySAB+KOcr6kCN2IN5uq65puKazXt9Z+WtoKsI5CDbqgX46vko6jopRcCKmok+ZbdmCtA+dooaDjCamrAKFPwX9W1257l0RU= 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of Washington and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # log-config 2 | 3 | A Clojure library designed to help configure your [timbre][timbre] logging. 4 | 5 | The `com.palletops.log-config.timbre` namespace provides timbre 6 | middleware and formatters. 7 | 8 | Add `[com.palletops/log-config "0.1.4"]` to your dependencies. 9 | 10 | ## Filtering Levels by Namespace 11 | 12 | The `min-level` function provides a timbre middleware to filter log 13 | messages for a single namespace to those at or above a threshold 14 | level. 15 | 16 | The `min-levels` function provides a timbre middleware to filter log 17 | messages based on a map from namespace to a threshold level. 18 | 19 | The `min-level-appender` function provides an appender adaptor to 20 | filter log messages based on a map from namespace to a threshold level 21 | provided in the `:min-levels` timbre configuration key. 22 | 23 | ## Domain Based Logging 24 | 25 | For logs at the domain level, the namespace is often irrelevant. The 26 | `with-domain` macro allows specifying a domain keyword for a dynamic 27 | clojure scope. The `domain-msg` timbre middleware adds this domain 28 | keyword to log messages on the `:domain` key. The 29 | `format-with-domain` timbre formatter will show the domain in 30 | preference to the namespace if the `:domain` key is set. 31 | 32 | ## Logging Contexts 33 | 34 | Often, the same code is called in multiple contexts, and the log 35 | message would be improved by adding some of that contextual 36 | information. The `with-context` macro allows specifying a data map 37 | for a dynamic clojure scope. The `context-msg` timbre middleware adds 38 | this context map to log messages on the `:context` key. The 39 | `format-with-context` timbre formatter will show the context keys and 40 | value in the log message. 41 | 42 | There is also a `format-with-domain-context` that shows both domain 43 | and context values. 44 | 45 | ## Tags for Filtering Log Messages 46 | 47 | To allow domain level filtering of log messages, use the `with-tags` 48 | macro, specifying a set of keywords. The `tags-msg` timbre middleware 49 | adds this tag set on the `:tags` key. 50 | 51 | ## Add Log Message Key based on a Var 52 | 53 | The `add-var` function returns a timbre middleware to set a log 54 | message key based on the value of the specified var. 55 | 56 | ## Timbre and Java Logging 57 | 58 | There are a number of logging choices on the JVM. Different libraries 59 | you use may depend on different logging libraries. If you're writing 60 | a library, you may wish to allow for logging via Java Logging, while 61 | still using timbre. 62 | 63 | ### Logging From Timbre to Java Logging 64 | 65 | The `com.palletops.log-config.timbre.tools-logging` namespace provides 66 | the `make-tools-logging-appender` function, that returns a timbre 67 | appender that outputs to tools.logging. 68 | 69 | To use it, add an entry in your timbre configuration `:appenders`: 70 | 71 | ```clj 72 | :appenders {:jl (make-tools-logging-appender {}) 73 | ``` 74 | 75 | ### Logging java logging to timbre 76 | 77 | See [`taoensso.timbre.tools.logging`](http://ptaoussanis.github.io/timbre/taoensso.timbre.tools.logging.html). 78 | 79 | ## Logging in Tests 80 | 81 | Sometimes it is useful to be able to modify log levels in tests. We 82 | provide the `logging-threshold-fixture` function for use as a 83 | `clojure.test` fixture, and `suppress-logging` which provides a scope 84 | where all configured appenders are disabled. 85 | 86 | ## License 87 | 88 | Copyright © 2014 Hugo Duncan 89 | 90 | Distributed under the Eclipse Public License either version 1.0 or (at 91 | your option) any later version. 92 | 93 | [timbre]: https://github.com/ptaoussanis/timbre 94 | [log4j]: http://logging.apache.org/log4j/ 95 | [log4j2]: http://logging.apache.org/log4j/2.x/ 96 | [slf4j]: http://www.slf4j.org/manual.html "SLF4J" 97 | [commons-logging]: http://commons.apache.org/proper/commons-logging "Apache Commons Logging" 98 | -------------------------------------------------------------------------------- /ReleaseNotes.md: -------------------------------------------------------------------------------- 1 | ## 0.1.4 2 | 3 | - Add test and check aliases 4 | 5 | - Fix typo in suppress-logging macro 6 | 7 | ## 0.1.3 8 | 9 | - Add dynamic wrapping of vars 10 | This lets you dynamically add and remove entry and exit logging to all 11 | functions in a namespace. 12 | 13 | - Add :kws option to async-appender 14 | Allow specification of the keys to forward using the :kws key. Defaults to 15 | [:hostname :ns :args :throwable :profile-stats]. 16 | 17 | - Add async-channel appender and memory-sink 18 | Add an appender that writes to a core.async channel. The memory-sink can 19 | be used to read the channel into an atom with bounded memory usage. 20 | 21 | Closes #3 22 | 23 | ## 0.1.2 24 | 25 | - Add with-tags, tags-msg to add a tag set to :tags 26 | Adds the with-tags macro to set tags for a scope. The tags-msg middleware 27 | is used to add the tags onto the :tags message key. 28 | 29 | The :tags are not logged (by default). 30 | 31 | Closes #2 32 | 33 | ## 0.1.1 34 | 35 | - Fix with-total-unquote 36 | Fixes #1 37 | 38 | ## 0.1.0 39 | 40 | - Initial Release 41 | -------------------------------------------------------------------------------- /profiles.clj: -------------------------------------------------------------------------------- 1 | {:dev {:test-selectors {:default (complement :slf4j) 2 | :slf4j :slf4j} 3 | :plugins [[lein-pallet-release "RELEASE"]] 4 | :aliases {"check" ["with-profile" "+logback" "check"]}} 5 | :no-checkouts {:checkout-deps-shares ^{:replace true} []} 6 | :logback {:dependencies [[org.clojure/tools.logging "0.2.6"] 7 | [ch.qos.logback/logback-classic "1.0.9"]] 8 | :aliases {"test" ["test" ":slf4j"]}} 9 | :release {:set-version {:updates [{:path "README.md", 10 | :no-snapshot true}]}}}x 11 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject com.palletops/log-config "0.1.5-SNAPSHOT" 2 | :description "Log appenders and middleware for timbre" 3 | :url "http://github.com/palletops/log-config" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.5.1" 7 | :scope "provided"] 8 | [org.clojure/tools.logging "0.2.6"] 9 | [com.taoensso/timbre "3.1.6"] 10 | [org.clojure/core.async "0.1.278.0-76b25b-alpha" 11 | :scope "provided"]]) 12 | -------------------------------------------------------------------------------- /src/com/palletops/log_config/slf4j.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.log-config.slf4j 2 | "Functions for manipulating slf4j" 3 | (:import 4 | (org.slf4j Logger LoggerFactory MDC))) 5 | 6 | 7 | ;;;; Mapped Diagnostic Context (MDC) 8 | (defn put-context [key val] 9 | (MDC/put (name key) (str val))) 10 | 11 | (defmacro with-context 12 | "Specify the logging context for a given body. `bindings` is a vector of 13 | keyword value pairs to be set on the Mapped Diagnostic Context." 14 | [kw-vals & body] 15 | `(let [current-context-map# (MDC/getCopyOfContextMap) 16 | context# ~kw-vals] 17 | (assert (or (map? context#) (not context#)) 18 | "Value supplied to with-context must be a map.") 19 | (try 20 | (doseq [[k# v#] context#] 21 | (put-context k# v#)) 22 | ~@body 23 | (finally 24 | (if current-context-map# 25 | (MDC/setContextMap current-context-map#) 26 | (MDC/clear)))))) 27 | -------------------------------------------------------------------------------- /src/com/palletops/log_config/timbre.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.log-config.timbre 2 | "Timbre middleware functions" 3 | (:require 4 | [clojure.string :refer [join upper-case]] 5 | [taoensso.timbre :as timbre])) 6 | 7 | ;;; # Namespace Specific Level Filtering 8 | (defn min-level 9 | "Returns a timbre middleware to filter messages for namespace by min 10 | level." 11 | [ns level] 12 | (fn min-level [msg] 13 | (if (or (not= ns (:ns msg)) 14 | (<= 0 (#'timbre/levels-compare (:level msg) level))) 15 | msg))) 16 | 17 | (defn min-levels 18 | "Returns a timbre middleware to filter messages for namespace by a 19 | map of min level for each ns." 20 | [level-map] 21 | (fn min-levels [msg] 22 | (if-let [level (get level-map (:ns msg))] 23 | (if (<= 0 (#'timbre/levels-compare (:level msg) level)) 24 | msg) 25 | msg))) 26 | 27 | (defn min-level-appender 28 | "Returns a timbre appender that wraps the specified appender and 29 | filters messages for namespace by a map of min level for each ns, 30 | given in the :min-levels config key." 31 | [appender] 32 | (fn min-level-appender [{:keys [ap-config ns level] :as msg}] 33 | (if-let [min-lvl (level (get (:min-levels ap-config {}) (:ns msg)))] 34 | (if (<= 0 (#'timbre/levels-compare level min-lvl)) 35 | (appender msg)) 36 | (appender msg)))) 37 | 38 | ;;; # Add Log Message Key based on a Var 39 | (defn add-var 40 | "Return a timbre middleware to add the value of the given var as a 41 | kw in the message map." 42 | [kw v] 43 | {:pre [(var? v)]} 44 | (fn add-var 45 | [msg] 46 | (assoc msg kw (var-get v)))) 47 | 48 | 49 | ;;; # Context in Log Messages 50 | (def ^{:dynamic true :doc "Thread specific context"} 51 | *context* nil) 52 | 53 | (defn context 54 | "Return the current context." 55 | [] 56 | *context*) 57 | 58 | (defmacro with-total-context 59 | "Execute body within the given context." 60 | [context & body] 61 | `(binding [*context* ~context] 62 | ~@body)) 63 | 64 | (defmacro with-context 65 | "Execute body with the given context merged onto the current context." 66 | [context & body] 67 | `(binding [*context* (merge *context* ~context)] 68 | ~@body)) 69 | 70 | (defmacro with-context-update 71 | "Execute body with the given context merged onto the current context." 72 | [[path f & args] & body] 73 | `(binding [*context* (update-in *context* ~path ~f ~@args)] 74 | ~@body)) 75 | 76 | (def context-msg 77 | "Add context to log messages on the :context key" 78 | (add-var :context #'*context*)) 79 | 80 | (defn format-with-context 81 | "A formatter that shows values in the :context key." 82 | [{:keys [level throwable message timestamp hostname ns context] :as ev} 83 | ;; Any extra appender-specific opts: 84 | & [{:keys [nofonts?] :as appender-fmt-output-opts}]] 85 | (format "%s %s %s [%s]%s - %s%s" 86 | timestamp hostname 87 | (-> level name upper-case) 88 | (if (seq context) 89 | (str " " (join " " (map (fn [[k v]] (str k " " v)) context))) 90 | "") 91 | ns (or message "") 92 | (or (timbre/stacktrace throwable "\n" (when nofonts? {})) ""))) 93 | 94 | ;;; # Tags 95 | 96 | ;;; Tags provide a set of keywords on which log messages can be filtered. The 97 | ;;; `tags-message` middleware is used to add them to the log message. 98 | 99 | (def ^:dynamic *tags* nil) 100 | 101 | (defmacro with-tags 102 | "Set the tags for any log messages in body." 103 | [tags & body] 104 | `(binding [*tags* ~tags] 105 | (assert (set? *tags*) "The tags must be a set of Named items.") 106 | ~@body)) 107 | 108 | (def tags-msg 109 | "Add tags to log messages on the :tags key" 110 | (add-var :tags #'*tags*)) 111 | 112 | ;;; # Domain logging 113 | 114 | ;;; Domain logging adds a keyword which is used as an alternative to 115 | ;;; the namespace. 116 | 117 | ;;; The `format-with-domain` timbre formatter will show the domain in 118 | ;;; preference to the namespace. 119 | 120 | (def ^:dynamic *domain* nil) 121 | 122 | (defmacro with-domain 123 | "Set the domain for any log messages in body." 124 | [domain & body] 125 | `(binding [*domain* ~domain] 126 | (assert (or (string? *domain*) (keyword? *domain*) (symbol? *domain*)) 127 | "The domain must be a string, keyword or symbol.") 128 | ~@body)) 129 | 130 | (def domain-msg 131 | "Add domain to log messages on the :domain key" 132 | (add-var :domain #'*domain*)) 133 | 134 | (defn format-with-domain 135 | "A formatter that shows domain rather than ns when it is set." 136 | [{:keys [level throwable message timestamp hostname ns domain]} 137 | & [{:keys [nofonts?] :as appender-fmt-output-opts}]] 138 | ;; [] - 139 | (format "%s %s %s [%s] - %s%s" 140 | timestamp hostname 141 | (-> level name upper-case) 142 | (or (and domain (name domain)) ns) 143 | (or message "") 144 | (or (timbre/stacktrace throwable "\n" (when nofonts? {})) ""))) 145 | 146 | ;;; # Formatter for Context and Domain 147 | (defn format-with-domain-context 148 | "A formatter that shows domain rather than ns when it is set, and 149 | adds any :context values." 150 | [{:keys [level throwable message timestamp hostname ns domain context]} 151 | & [{:keys [nofonts?] :as appender-fmt-output-opts}]] 152 | ;; [] - 153 | (format "%s %s %s [%s]%s - %s%s" 154 | timestamp hostname 155 | (-> level name upper-case) 156 | (or (and domain (name domain)) ns) 157 | (if (seq context) 158 | (str " " (join " " (map (fn [[k v]] (str k " " v)) context))) 159 | "") 160 | (or message "") 161 | (or (timbre/stacktrace throwable "\n" (when nofonts? {})) ""))) 162 | 163 | ;;; # Logging Threshold Fixture 164 | 165 | (defn logging-threshold-fixture 166 | "Change the logging threshold inside a scope." 167 | ([level appender] 168 | (fn [f] 169 | (let [config @timbre/config] 170 | (timbre/set-config! [:appenders appender :min-level] level) 171 | (try (f) 172 | (finally (timbre/merge-config! config)))))) 173 | ([level] (logging-threshold-fixture level :standard-out)) 174 | ([] (logging-threshold-fixture :warn :standard-out))) 175 | 176 | (defmacro suppress-logging 177 | "Suppress all logging inside the scope of the function." 178 | [& body] 179 | `(let [config# @timbre/config] 180 | (try 181 | (doseq [appender# (keys (:appenders config#))] 182 | (timbre/set-config! [:appenders appender# :enabled?] false)) 183 | ~@body 184 | (finally (timbre/merge-config! config#))))) 185 | -------------------------------------------------------------------------------- /src/com/palletops/log_config/timbre/async_channel.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.log-config.timbre.async-channel 2 | "A timbre appender that writes to a channel" 3 | (:require 4 | [clojure.core.async :refer [go put!]])) 5 | 6 | (defn make-async-channel-appender 7 | "Returns an async channel appender, the outputs to ch. 8 | 9 | It is advised that the channel, ch, is non-blocking. 10 | 11 | A config map can be provided here as an argument. In addition to the 12 | standard appender configuration options, the `:kws` option allows 13 | specification of a sequence of keys to forward to the channel, 14 | defaults to [:hostname :ns :args :throwable :profile-stats]. 15 | 16 | (make-async-channel-appender {:enabled? true})" 17 | [ch appender-opts] 18 | (let [default-opts {:enabled? true :kws [:hostname :ns :args :throwable 19 | :profile-stats]} 20 | opts (merge default-opts appender-opts)] 21 | (merge opts 22 | {:fn 23 | (fn [{:keys [] :as apfn-args}] 24 | (put! ch (select-keys apfn-args (:kws opts))))}))) 25 | 26 | (defn- add-to-memory 27 | "Add `msg` to the sequence in the atom `memory`, limiting the 28 | sequence to `n` elements." 29 | [memory n msg] 30 | (if (>= (count @memory) n) 31 | (swap! memory (fn [s] (conj (pop s) msg))) 32 | (swap! memory (fnil conj []) msg))) 33 | 34 | (defn memory-sink 35 | "Save messages from an async channel, `ch`, into a bounded memory area, 36 | held in the atom, `memory`. Save up to `max-messages` messages." 37 | [ch memory max-messages] 38 | {:pre [(instance? clojure.lang.Atom memory) 39 | (number? max-messages)]} 40 | (go 41 | (loop [] 42 | (if-let [m (> ns ns-interns vals (filter (comp fn? var-get)))] 40 | (doseq [v ns-fn-vars] 41 | (wrap-var v wrappers)))) 42 | 43 | (defn unwrap-ns-vars 44 | "Remove function wrappers from the functions in a given namespace." 45 | [ns] 46 | (let [ns-fn-vars (->> ns ns-interns vals (filter (comp fn? var-get)))] 47 | (doseq [v ns-fn-vars] 48 | (unwrap-var v)))) 49 | 50 | (defn fn-entry-logger 51 | "Return a wrapper function to wrap functions with entry logging at 52 | the specified log level." 53 | [level] 54 | (fn [f {:keys [name]}] 55 | (fn entry-logger [& args] 56 | (log level name args) 57 | (apply f args)))) 58 | 59 | (defn fn-exit-logger 60 | "Return a wrapper function to wrap functions with exit logging at 61 | the specified log level." 62 | [level] 63 | (fn [f {:keys [name]}] 64 | (fn entry-logger [& args] 65 | (let [r (apply f args)] 66 | (log level name "->" r) 67 | r)))) 68 | 69 | (defn log-ns-fns 70 | "Log entry and exit of all functions in a namespace." 71 | [ns level] 72 | (wrap-ns-vars ns [(fn-entry-logger level)(fn-exit-logger level)])) 73 | -------------------------------------------------------------------------------- /src/com/palletops/log_config/tools_logging.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.log-config.tools-logging 2 | (:require 3 | [clojure.stacktrace :as stacktrace] 4 | [clojure.tools.logging :as logging])) 5 | 6 | ;; tools.logging 0.2.0 and up 7 | 8 | ;;; A null logger 9 | ;;; Suppresses all logging. Can be useful to quiet test cases. 10 | (deftype NullLogger 11 | [] 12 | clojure.tools.logging.impl.Logger 13 | (enabled? [log level] false) 14 | (write! [log level throwable message])) 15 | 16 | (def null-log (delay (NullLogger.))) 17 | 18 | (deftype NullLoggerFactory 19 | [] 20 | clojure.tools.logging.impl.LoggerFactory 21 | (name [factory] "null logger") 22 | (get-logger [factory log-ns] @null-log)) 23 | 24 | (def null-logger-factory (delay (NullLoggerFactory.))) 25 | 26 | ;;; A stdout logger 27 | ;;; Logs everyting to stdout. Can be useful to test logging. 28 | (deftype StdoutLogger 29 | [] 30 | clojure.tools.logging.impl.Logger 31 | (enabled? [log level] true) 32 | (write! [log level throwable message] 33 | (println (name level) message) 34 | (when throwable 35 | (stacktrace/print-stack-trace 36 | (stacktrace/root-cause throwable))))) 37 | (def stdout-log (delay (StdoutLogger.))) 38 | 39 | (deftype StdoutLoggerFactory 40 | [] 41 | clojure.tools.logging.impl.LoggerFactory 42 | (name [factory] "stdout logger") 43 | (get-logger [factory log-ns] @stdout-log)) 44 | (def stdout-logger-factory (delay (StdoutLoggerFactory.))) 45 | 46 | (defmacro with-logger-factory 47 | [factory & body] 48 | `(binding [logging/*logger-factory* ~factory] ~@body)) 49 | 50 | ;;; Macros to use specific logging implementations in a given scope 51 | (defmacro logging-to-stdout 52 | "Send log messages to stdout for inspection" 53 | [& forms] 54 | `(with-logger-factory @stdout-logger-factory 55 | ~@forms)) 56 | 57 | (defmacro logging-to-string 58 | "Send log messages to a string for inspection" 59 | [& forms] 60 | `(with-out-str 61 | (with-logger-factory @stdout-logger-factory 62 | ~@forms))) 63 | 64 | (defmacro suppress-logging 65 | "Prevent log messages to reduce test log noise" 66 | [& forms] 67 | `(with-logger-factory @null-logger-factory 68 | ~@forms)) 69 | -------------------------------------------------------------------------------- /test/com/palletops/log_config/slf4j_test.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.log-config.slf4j-test 2 | (:require 3 | [clojure.test :refer :all] 4 | [taoensso.timbre :refer [example-config info log]] 5 | [com.palletops.log-config.tools-logging :refer :all] 6 | [com.palletops.log-config.timbre 7 | :refer [add-var format-with-context]] 8 | [com.palletops.log-config.timbre.tools-logging 9 | :refer [make-tools-logging-appender with-context]] 10 | [com.palletops.log-config.tools-logging 11 | :refer [logging-to-string]])) 12 | 13 | (def v {:m 1}) 14 | 15 | (deftest ^:slf4j with-context-test 16 | (testing "with context aware formatter" 17 | (let [config (merge example-config 18 | {:fmt-output-fn format-with-context 19 | :appenders {:slf4j (make-tools-logging-appender {})}})] 20 | (testing "without context setting middleware" 21 | (is (not 22 | (re-find 23 | #":m 1\n$" 24 | (logging-to-string 25 | (with-context {:m 1} 26 | (log config :info "something"))))) 27 | "log message doesn't contain context")) 28 | (testing "with context setting middleware" 29 | (is (re-find 30 | #":m 1" 31 | (logging-to-string 32 | (with-context {:m 1} 33 | (log (assoc config :middleware [(add-var :context #'v)]) 34 | :info "something")))) 35 | "log message contains context"))))) 36 | -------------------------------------------------------------------------------- /test/com/palletops/log_config/timbre/async_channel_test.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.log-config.timbre.async-channel-test 2 | (:require 3 | [clojure.core.async :refer [ :a:a.*" 12 | (with-out-str (test-fn :a)))) 13 | (finally 14 | (unwrap-ns-vars 'com.palletops.log-config.timbre.wrap-test))) 15 | (is (= "" (with-out-str (test-fn :a))))) 16 | -------------------------------------------------------------------------------- /test/com/palletops/log_config/timbre_test.clj: -------------------------------------------------------------------------------- 1 | (ns com.palletops.log-config.timbre-test 2 | (:require 3 | [clojure.test :refer :all] 4 | [taoensso.timbre :refer [example-config info log]] 5 | [com.palletops.log-config.timbre :refer :all])) 6 | 7 | (def v {:m 1}) 8 | 9 | (deftest context-test 10 | (testing "context via explicit add-var" 11 | (is (re-find #":m 1" 12 | (with-out-str 13 | (log (merge example-config 14 | {:fmt-output-fn format-with-context 15 | :middleware [(add-var :context #'v)]}) 16 | :info "something"))))) 17 | (testing "context via with-context and context-msg" 18 | (is (re-find #":m 1" 19 | (with-out-str 20 | (with-context {:m 1} 21 | (log (merge example-config 22 | {:fmt-output-fn format-with-context 23 | :middleware [context-msg]}) 24 | :info "something"))))))) 25 | 26 | (def d :domain) 27 | 28 | (deftest domain-test 29 | (testing "domain via explicit add-var" 30 | (is (re-find #"\[domain\]" 31 | (with-out-str 32 | (log (merge example-config 33 | {:fmt-output-fn format-with-domain 34 | :middleware [(add-var :domain #'d)]}) 35 | :info "something"))))) 36 | (testing "context via with-domain and domain-msg" 37 | (is (re-find #"\[domain\]" 38 | (with-out-str 39 | (with-domain :domain 40 | (log (merge example-config 41 | {:fmt-output-fn format-with-domain 42 | :middleware [domain-msg]}) 43 | :info "something"))))))) 44 | 45 | (deftest domain-context-test 46 | (testing "domain and context" 47 | (is (re-find #"\[domain\] :m 1" 48 | (with-out-str 49 | (with-domain :domain 50 | (with-context {:m 1} 51 | (log (merge example-config 52 | {:fmt-output-fn format-with-domain-context 53 | :middleware [context-msg domain-msg]}) 54 | :info "something")))))))) 55 | 56 | (deftest with-context-update-test 57 | (with-context-update [[:x] (fnil conj []) :y] 58 | (is (= {:x [:y]} (context))))) 59 | 60 | (defn format-with-tags 61 | [{:keys [tags]} & []] 62 | (pr-str tags)) 63 | 64 | (deftest tags-test 65 | (testing "tags" 66 | (is (= (str (pr-str #{:a :b}) \newline) 67 | (with-out-str 68 | (with-tags #{:a :b} 69 | (log (merge example-config 70 | {:fmt-output-fn format-with-tags 71 | :middleware [tags-msg]}) 72 | :info "something"))))))) 73 | --------------------------------------------------------------------------------