pax_global_header00006660000000000000000000000064152370760050014517gustar00rootroot0000000000000052 comment=5e5f4b9b7191c8449ff1dd4f44c8bd321c3ac6e8 OpenVoxProject-structured-logging-82f59e7/000077500000000000000000000000001523707600500206455ustar00rootroot00000000000000OpenVoxProject-structured-logging-82f59e7/.github/000077500000000000000000000000001523707600500222055ustar00rootroot00000000000000OpenVoxProject-structured-logging-82f59e7/.github/dependabot.yml000066400000000000000000000005751523707600500250440ustar00rootroot00000000000000version: 2 updates: # raise PRs for gem updates - package-ecosystem: bundler directory: "/" schedule: interval: daily time: "13:00" open-pull-requests-limit: 10 # Maintain dependencies for GitHub Actions - package-ecosystem: github-actions directory: "/" schedule: interval: daily time: "13:00" open-pull-requests-limit: 10 OpenVoxProject-structured-logging-82f59e7/.github/release.yml000066400000000000000000000013231523707600500243470ustar00rootroot00000000000000--- # https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes changelog: exclude: labels: - duplicate - invalid - modulesync - question - skip-changelog - wont-fix - wontfix categories: - title: Breaking Changes 🛠 labels: - backwards-incompatible - title: New Features 🎉 labels: - enhancement - title: Bug Fixes 🐛 labels: - bug - title: Documentation Updates 📚 labels: - documentation - docs - title: Dependency Updates ⬆️ labels: - dependencies - title: Other Changes labels: - "*" OpenVoxProject-structured-logging-82f59e7/.github/workflows/000077500000000000000000000000001523707600500242425ustar00rootroot00000000000000OpenVoxProject-structured-logging-82f59e7/.github/workflows/pr-testing.yaml000066400000000000000000000031471523707600500272270ustar00rootroot00000000000000--- name: lein_test on: pull_request: {} push: branches: - main # minimal permissions permissions: contents: read jobs: run-lein-tests: name: lein test - Java ${{ matrix.java }} runs-on: ubuntu-latest strategy: fail-fast: false matrix: java: - '25' - '21' - '17' steps: - name: Check out repository code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup java uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: temurin java-version: ${{ matrix.java }} - name: Install Clojure tools uses: DeLaGuardo/setup-clojure@4c7a6f613e5089821bb3bb2a33a3ee115578580d # 13.6.1 with: cli: latest # Clojure CLI based on tools.deps lein: latest # Leiningen boot: latest # Boot.clj bb: latest # Babashka clj-kondo: latest # Clj-kondo cljstyle: latest # cljstyle zprint: latest # zprint - name: Run lein tests with update profile run: | set -x set -e lein version echo "Running tests" lein -U test tests: if: always() needs: - run-lein-tests runs-on: ubuntu-24.04 name: Test suite steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: jobs: ${{ toJSON(needs) }} OpenVoxProject-structured-logging-82f59e7/.github/workflows/release.yaml000066400000000000000000000007411523707600500265500ustar00rootroot00000000000000--- name: Release and publish package to clojars.org permissions: contents: write packages: write on: workflow_dispatch: jobs: release: uses: 'openvoxproject/shared-actions/.github/workflows/clojure_release.yml@main' secrets: github_pat: ${{ secrets.OPENVOXBOT_COMMIT_AND_PRS }} ssh_private_key: ${{ secrets.OPENVOXBOT_SSH_PRIVATE_KEY }} clojars_username: ${{ secrets.CLOJARS_USERNAME }} clojars_password: ${{ secrets.CLOJARS_PASSWORD }} OpenVoxProject-structured-logging-82f59e7/.gitignore000066400000000000000000000001431523707600500226330ustar00rootroot00000000000000/target /classes /checkouts pom.xml pom.xml.asc *.jar *.class /.lein-* /.nrepl-port .hgignore .hg/ OpenVoxProject-structured-logging-82f59e7/LICENSE000066400000000000000000000261351523707600500216610ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.OpenVoxProject-structured-logging-82f59e7/README.md000066400000000000000000000132751523707600500221340ustar00rootroot00000000000000# org.openvoxproject/structured-logging [![Clojars Project](https://img.shields.io/clojars/v/org.openvoxproject/structured-logging.svg)](https://clojars.org/org.openvoxproject/structured-logging) `structured-logging` is a library that helps you to: - write arbitrary JSON to your logs, making it easier to interface with log analysis tools. - write messages to arbitrarily named loggers, instead of just the one named after the namespace in which the log statement appears. It is built on `clojure.tools.logging`, but it only works with logback. ## Usage ### maplog Structured log entries are created by calling `maplog` like this: (maplog :warn {:user-service "https://...", :status 503, :elapsed 27} #(format "Failed to query user-service %s. Response: status %d" (:user-service %) (:status %))) The second parameter is the structured data you want to log, and any clojure map is ok, as long as [Cheshire](https://github.com/dakrone/cheshire) can handle it. The log message itself is generated by passing the structured data to the function provided as the final argument. This provides a general way to support arbitrary formatters, including some like those in [clj-i18n](https://github.com/openvoxproject/clj-i18n), which require that their invocations appear literally, at each translation call site, i.e.: (maplog :info {:temperature t :stamp (now)} #(i18n/trs "Temperature has exceeded {0} at {1}" (:temperature %) (:stamp %))) ### Named loggers When you would pass a log-level parameter, you may instead supply a vector of `[:custom-logger :level]`. This will log a message to the logger named "custom-logger". Then you can specifically address that logger in your logback configuration (to redirect it to a different log file, for example). ## Common fields If you use the recommended logger configuration, as described below, you will see the following fields in each JSON log message: * @timestamp * message * logger_name * thread_name * level * level_value (numeric, suitable for sorting) * stack_trace Additional relevant fields may be added in any given message, but this base set will always be present. ## Configuration ### JSON text If you want to log JSON data where you would otherwise log regular text, replace the `encoder` element in your `logback.xml` with this one: Even though this says 'logstash' on it, it works completely independently from any log aggregation system. The final `` element is important - that inserts our custom properties into each json message. ## Logstash integration You can also log directly to logstash with an appender configured like this: my.great.logstash.server.com 4560 You will also need to add a reference to the appender from the `` element: ... ## Log Output We are using a json encoder that comes with the `logstash-logback` integration library. (https://github.com/logstash/logstash-logback-encoder) This can be used in conjunction with the logstash tcp appender, or in conjunction with a typical file appender. In either case, the json for the above log message looks something like this: { "@timestamp": "...", "level": "WARN", "user-service": "https://...", "status": 503, "elapsed": 27 } The exact fields that show up depend on how you've configured the encoder; '@timestamp' is a logstash convention. ## Answers to expected questions *Can I embed arbitrary structures in there?* You can log anything that cheshire can serialize, but you may wish to stick to simple key-value formats to keep your logs easy to analyze. *What happens when I log a map with :level as the key?* Don't do that. It's not yet clear how this case should be handled. For now, avoid such keys. Namespacing your map keys may be prudent if you're worried about collisions. *Does this library require logstash?* No. It does depend on the json encoder that comes with the logback-logstash integration library, but you can point the json it spits out at any old logback appender. Critically, it has a feature that allows us to edit the json before it gets written, which is where we add our custom information. We *could* write such an encoder ourselves, but they already wrote it. *Why didn't you use one of the other logback-json encoders?* Because those just encode the normal log event fields as json; the useful feature here is the ability to include arbitrary data as part of the json. ## Tips Structured logging is a slippery slope and should be applied where it has clear benefits. While we've streamlined it a lot, this is heavier than regular logging, and it's still non-application code that you have to scatter throughout your program. ## License Copyright © 2015 Puppet Labs Copyright © 2025 Vox Pupuli Distributed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html) OpenVoxProject-structured-logging-82f59e7/project.clj000066400000000000000000000016031523707600500230050ustar00rootroot00000000000000(defproject org.openvoxproject/structured-logging "1.0.3" :description "Write data structures to your logs from clojure." :url "https://github.com/openvoxproject/structured-logging" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/licenses/LICENSE-2.0.html"} :dependencies [[org.clojure/clojure "1.12.5"] [net.logstash.logback/logstash-logback-encoder "4.11"] [org.clojure/tools.logging "0.6.0"] [cheshire "6.2.0"] [org.slf4j/slf4j-api "1.7.36"]] :deploy-repositories [["releases" {:url "https://clojars.org/repo" :username :env/CLOJARS_USERNAME :password :env/CLOJARS_PASSWORD :sign-releases false}]] :lein-release {:scm :git :deploy-via :lein-deploy}) OpenVoxProject-structured-logging-82f59e7/renovate.json000066400000000000000000000004061523707600500233630ustar00rootroot00000000000000{ "$schema": "https://docs.renovatebot.com/renovate-schema.json", "addLabels": ["renovate", "dependencies"], "assigneesFromCodeOwners": true, "automerge": true, "automergeType": "pr", "dependencyDashboard": true, "enabledManagers": ["leiningen"] } OpenVoxProject-structured-logging-82f59e7/src/000077500000000000000000000000001523707600500214345ustar00rootroot00000000000000OpenVoxProject-structured-logging-82f59e7/src/puppetlabs/000077500000000000000000000000001523707600500236135ustar00rootroot00000000000000OpenVoxProject-structured-logging-82f59e7/src/puppetlabs/structured_logging/000077500000000000000000000000001523707600500275255ustar00rootroot00000000000000OpenVoxProject-structured-logging-82f59e7/src/puppetlabs/structured_logging/core.clj000066400000000000000000000076761523707600500311670ustar00rootroot00000000000000(ns puppetlabs.structured-logging.core (:require [clojure.tools.logging :refer [*logger-factory*]] [clojure.tools.logging.impl :as impl] [puppetlabs.structured-logging.protocols :refer :all] [cheshire.core :as cheshire]) (:import [net.logstash.logback.marker Markers LogstashMarker] [com.fasterxml.jackson.core JsonGenerator])) (definterface ISemlogMarker (semlogMap [] "Returns the semlog map for this marker.")) (defn- merge-clojure-map-marker "Create a marker that, when written to the LogStash json encoder, will json-encode the given map `m` and merge it with any already-created json. Use the following encoder configuration inside your logback appender configuration to write your log messages as json: " [m] (proxy [LogstashMarker ISemlogMarker] ["SEMLOG_MAP"] (writeTo [^JsonGenerator generator] (binding [cheshire/*generator* generator] ;; `::none` is the 'wholeness' parameter to cheshire, which indicates which ;; start- and end-object markers to write. In this case we don't want any ;; of them, so we'll pass `::none`. This is not on the list of supported values, ;; but the fact that it's not equal to any of them means it will work. (cheshire/write m ::none))) (semlogMap [] m))) (extend-protocol MarkerLogger org.slf4j.Logger (write-with-marker! [logger level e msg marker-map] (let [^String msg (str msg) marker (merge-clojure-map-marker marker-map)] (if e (case level :trace (.trace logger marker msg e) :debug (.debug logger marker msg e) :info (.info logger marker msg e) :warn (.warn logger marker msg e) :error (.error logger marker msg e) :fatal (.error logger marker msg e) (throw (IllegalArgumentException. (str level)))) (case level :trace (.trace logger marker msg) :debug (.debug logger marker msg) :info (.info logger marker msg) :warn (.warn logger marker msg) :error (.error logger marker msg) :fatal (.error logger marker msg) (throw (IllegalArgumentException. (str level)))))))) (defmacro maplog "Logs an event with ctx-map as an slf4j event Marker. The logger-level parameter may be either a log level keyword like :error or a vector of a custom logger and the log level, like [:sync :error]. Calls (create-message ctx-map) to generate the log message string. Examples: (maplog :info {:status 200} #(str \"Received success status \" (:status %)) (maplog [:sync :warn] {:remote ..., :response ...} #(format \"Failed to pull record from remote %s. Response: status %s\" (:remote %) (:status %))) (maplog [:sync :info] {:remote ...} #(format \"Finished pull from %s in %s seconds\" sync-time (:remote %))) (maplog :info {:status 200} #(i18n/trs \"Received success status {0}\" (:status %1)))" ([logger-level ctx-map create-message] `(maplog ~logger-level nil ~ctx-map ~create-message)) ([logger-level throwable ctx-map create-message] `(let [logger-level# ~logger-level [ns# level#] (if (coll? logger-level#) logger-level# [~*ns* logger-level#]) ns# (if (keyword? ns#) (name ns#) ns#) logger# (impl/get-logger *logger-factory* ns#) ctx-map# ~ctx-map] (when (impl/enabled? logger# level#) (write-with-marker! logger# level# ~throwable (~create-message ctx-map#) ctx-map#))))) OpenVoxProject-structured-logging-82f59e7/src/puppetlabs/structured_logging/protocols.clj000066400000000000000000000002311523707600500322370ustar00rootroot00000000000000(ns puppetlabs.structured-logging.protocols) (defprotocol MarkerLogger (write-with-marker! [^org.slf4j.Logger logger level ^Throwable e msg marker])) OpenVoxProject-structured-logging-82f59e7/test/000077500000000000000000000000001523707600500216245ustar00rootroot00000000000000OpenVoxProject-structured-logging-82f59e7/test/puppetlabs/000077500000000000000000000000001523707600500240035ustar00rootroot00000000000000OpenVoxProject-structured-logging-82f59e7/test/puppetlabs/structured_logging/000077500000000000000000000000001523707600500277155ustar00rootroot00000000000000OpenVoxProject-structured-logging-82f59e7/test/puppetlabs/structured_logging/core_test.clj000066400000000000000000000036061523707600500324030ustar00rootroot00000000000000(ns puppetlabs.structured-logging.core-test (:require [clojure.test :refer :all] [clojure.tools.logging :refer [*logger-factory*]] [clojure.tools.logging.impl :as impl] [puppetlabs.structured-logging.core :refer :all] [puppetlabs.structured-logging.protocols :refer :all])) (def ^:private stns *ns*) (defn make-log-record [logger-ns level ex message marker] (letfn [(maybe-add-exception [rec] (if ex (assoc rec :throwable ex) rec)) (maybe-add-marker [rec] (if marker (assoc rec :marker marker) rec))] (-> {:ns logger-ns, :level level, :message message} maybe-add-exception maybe-add-marker))) (defn atom-logger-factory [log-atom] (reify impl/LoggerFactory (name [_] "atomLogger") (get-logger [_ logger-ns] (reify impl/Logger (enabled? [_ _] true) (write! [_ level ex message] (swap! log-atom conj (make-log-record logger-ns level ex message nil))) MarkerLogger (write-with-marker! [logger level ex message marker] (swap! log-atom conj (make-log-record logger-ns level ex message marker))))))) (defn expect-log [f expected-log] (let [log (atom [])] (binding [*logger-factory* (atom-logger-factory log)] (f)) (is (= expected-log @log)))) (def throwable (Exception. "ex")) (deftest maplog-behavior (are [f expected] (expect-log f expected) #(maplog :error {:x 1} (fn [m] (str "Test " (:x m)))) [{:ns stns, :level :error, :message "Test 1" :marker {:x 1}}] #(maplog [:sync :error] {:x 2} (fn [m] (str "Test " (:x m)))) [{:ns "sync", :level :error, :message "Test 2" :marker {:x 2}}] #(maplog [:sync :error] throwable {:x 3} (fn [m] (str "Test " (:x m)))) [{:ns "sync", :level :error, :message "Test 3", :throwable throwable :marker {:x 3}}]))