Created
July 25, 2017 16:10
-
-
Save danboykis/152e3418fa3c03aaf1df2d8972ee01c9 to your computer and use it in GitHub Desktop.
a size based rolling appender
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns example.file-size-rolling-appender | |
"Rolling file appender." | |
(:require [clojure.java.io :as io] | |
[taoensso.timbre :as timbre]) | |
(:import [java.io File] | |
[java.text SimpleDateFormat])) | |
;; TODO Test port to Timbre v4 | |
(defn- rename-old-create-new-log [^File log ^File old-log] | |
(.renameTo log old-log) | |
(.createNewFile log)) | |
(defn- archive-piece [pattern date-ms] (-> pattern SimpleDateFormat. (.format date-ms))) | |
(defn- roll-log [log path archive-part] | |
(let [old-path (format "%s.%s" path archive-part) | |
old-log (io/file old-path)] | |
(if (.exists old-log) | |
(loop [index 0] | |
(let [index-path (format "%s.%d" old-path index) | |
index-log (io/file index-path)] | |
(if (.exists index-log) | |
(recur (+ index 1)) | |
(rename-old-create-new-log log index-log)))) | |
(rename-old-create-new-log log old-log)))) | |
(defn in-bytes [[n unit]] | |
(case unit | |
:kb (* n 1024) | |
:mb (* n 1024 1024) | |
:gb (* n 1024 1024 1024) | |
n)) | |
(defn rolling-appender | |
"Returns a Rolling file appender. Opts: | |
:path - logfile path. | |
:pattern - time pattern to archive log files | |
:max-log-size - the max size in bytes of the logfile before it gets rolled" | |
[& {:keys [path pattern max-log-size] | |
:or {path "./timbre-rolling.log" | |
max-log-size 10485760 ;;10 mb in bytes | |
pattern "yyyyMMdd'T'HHmmss"}}] | |
{:enabled? true | |
:async? false | |
:min-level nil | |
:rate-limit nil | |
:output-fn :inherit | |
:fn (fn [data] | |
(let [{:keys [output_]} data | |
output-str (force output_)] | |
(when-let [log (io/file path)] | |
(try | |
(when-not (.exists log) | |
(io/make-parents log)) | |
(if (.exists log) | |
(if (>= (.length log) max-log-size) | |
(roll-log log path (archive-piece pattern (System/currentTimeMillis)))) | |
(.createNewFile log)) | |
(spit path (with-out-str (println output-str)) :append true) | |
(catch java.io.IOException _)))))}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment