-
Notifications
You must be signed in to change notification settings - Fork 2
/
logger.clj
454 lines (369 loc) · 11.7 KB
/
logger.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
(ns dialog.logger
"Logging implementation logic and integration with SLF4J."
(:require
[clojure.string :as str]
[dialog.config :as config]
[dialog.util :as u])
(:import
(dialog.logger
DialogLogger
Level)
java.time.Instant))
;; What do log events look like?
#_
{;; Time the event occurred, as a java.time.Instant
:time #inst "2021-12-25T10:56:32Z"
;; Event severity level.
:level :info
;; Human-friendly message for the event.
:message "foo bar baz"
;; Logger this event is for - usually the namespace or class file.
:logger "com.acme.foo"
;; (optional) Line the log statement was sent from.
:line 123
;; (optional) Hostname this event was generated on.
:host "foo.acme.systems"
;; (optional) Process identifier.
:proc "app.0"
;; (optional) Application system name.
:sys "app"
;; (optional) Thread this event was generated in.
:thread "main"
;; (optional) Duration in milliseconds for this event
:duration 0.123
;; (optional) Throwable error associated with this event.
:error (ex-info "..." {,,,})
;; (optional) Any other fields
,,,}
;; ## Logging Configuration
(def config
"Global logging configuration reference."
nil)
(defn initialize!
"Load and initialize the logging system configuration."
[]
(let [cfg (config/load-config)]
(alter-var-root #'config (constantly cfg))
nil))
;; ## Logger Levels
(def ^:private level-cache
"Stateful cache of computed levels for specific loggers."
(atom {} :validator map?))
(defn- reset-level-cache!
"Reset the cache of logger levels and increment the Java cache version so
loggers re-check."
[]
(swap! level-cache empty)
(DialogLogger/bumpCache)
nil)
(defn- prefixed?
"True if `logger-name` is equal to or prefixed by `prefix`. Here 'prefixing'
means adding a period to the end of `prefix` to ensure the logger is a
descendant and not merely a similarly-named logger.
For example, if we're given the prefix `\"foo.bar\"` then the following
logger-names evaluate to:
\"foo.bar\" => true
\"foo.bar.baz\" => true
\"foo.bartle\" => false
"
[logger prefix]
(or (= logger prefix)
(str/starts-with? logger (str prefix \.))))
(defn blocked?
"True if the logger is blocked by configuration, otherwise false."
[logger]
(boolean
(and (string? logger)
(some #(prefixed? logger %)
(:blocked config)))))
(defn- match-block
"Return `:off` if there is a blocking prefix matching this logger."
[logger]
(when (blocked? logger)
:off))
(defn- match-level
"Get the value for the key which is the deepest prefix of the given logger
name, or nil if no keys prefix the logger."
[logger]
(when-let [match (->> (:levels config)
(sort-by (comp count key) (comp - compare))
(filter #(prefixed? logger (key %)))
(first))]
(val match)))
(defn valid-level?
"True if the provided value is a valid logger level keyword."
[k]
(Level/isValid k))
(defn get-levels
"Return a map of all configured logger names to level keywords."
[]
(:levels config))
(defn get-level
"Get the current level setting for a logger. If no logger name is provided,
this returns the root logger's level."
([]
(or (:level config) :info))
([logger]
(or (get @level-cache logger)
(let [level (or (match-block logger)
(match-level logger)
(get-level))]
(swap! level-cache assoc logger level)
level))))
(defn set-level!
"Dynamically adjust the level for the named logger. If no name is provided,
adjusts the level of the root logger. Returns nil."
([level]
(when-not (valid-level? level)
(throw (IllegalArgumentException.
(str "Provided level " (pr-str level) " is not valid"))))
(alter-var-root #'config assoc :level level)
(reset-level-cache!))
([logger level]
(when-not (string? logger)
(throw (IllegalArgumentException.
(str "Provided logger must be a string, got: " (pr-str logger)))))
(when-not (valid-level? level)
(throw (IllegalArgumentException.
(str "Provided level " (pr-str level) " is not valid"))))
(alter-var-root #'config assoc-in [:levels logger] level)
(reset-level-cache!)))
(defn clear-levels!
"Dynamically adjust the configuration to remove all logger levels. Does not
change the root level. Returns nil."
[]
(alter-var-root #'config assoc :levels {})
(reset-level-cache!))
(defn enabled?
"True if the given logger is enabled at the provided level."
[logger level]
(Level/isAllowed
(Level/ofKeyword (get-level logger))
(Level/ofKeyword level)))
;; ## Event Logging
(defn- apply-defaults
"Apply defaults to the given event, efficiently inserting information that is
not present."
[event]
(cond-> event
(nil? (:time event))
(assoc :time (Instant/now))
(nil? (:thread event))
(assoc :thread (.getName (Thread/currentThread)))
(nil? (:host event))
(assoc :host (u/get-hostname))
(nil? (:error event))
(dissoc :error)))
(defn- apply-middleware
"Apply a sequence of middleware functions to an event."
[event middleware]
(reduce
(fn [event f]
(when event
(try
(f config event)
(catch Exception ex
(u/print-err :middleware
"Failed to apply middleware function %s: %s"
(.getName (class f))
(ex-message ex))
event))))
event
middleware))
(defn- write-output!
"Write an event to an output, applying any configured formatter."
[id output event]
(when-let [write! (:writer output)]
(try
(let [format-message (or (:formatter output) :message)
message (format-message event)]
(write! event message)
nil)
(catch Exception ex
(u/print-err :output
"Failed to write to output %s: %s"
(name id)
(ex-message ex))))))
(defn log-event
"Pass an event into the logging system."
[event]
(when-not config
(initialize!))
(when-let [event (and (string? (:logger event))
(keyword? (:level event))
(enabled? (:logger event) (:level event))
(-> event
(apply-defaults)
(apply-middleware (:middleware config))))]
(run!
(fn write-event
[[id output]]
(when-let [event (apply-middleware event (:middleware output))]
(write-output! id output event)))
(:outputs config))))
(defn ^:no-doc -log-slf4j
"Pass a message into the logging system. Used by the SLF4J logging
integration - consumers should call `log-event` directly."
[logger level msg err]
(log-event {:level level
:logger logger
:message msg
:error err}))
(defn ^:no-doc -log-macro
"Pass a message into the logging system. Used by the logging macro
expansion - consumers should call `log-event` directly."
[event f x & more]
(log-event
(if (instance? Throwable x)
(assoc event
:message (apply f more)
:error x)
(assoc event
:message (apply f x more)))))
;; ## Logging APIs
(defn- coverage-mode?
"True if the log macros should emit code in a 'coverage-friendly' mode."
[]
(= "true" (or (System/getenv "DIALOG_COVERAGE")
(System/getProperty "dialog.coverage"))))
(defmacro logp
"Log a message using print style args. Can optionally take a throwable as its
second arg."
{:arglists '([level message & more] [level throwable message & more])}
[level x & more]
(let [logger (str (ns-name *ns*))
line (:line (meta &form))]
(cond
;; Coverage-friendly form. Args are always evaluated and passed to the
;; helper function.
(coverage-mode?)
`(-log-macro
{:logger ~logger
:level ~level
:line ~line}
print-str
~x
~@more)
;; First argument can't be an error, use simpler form.
(or (string? x) (nil? more))
`(let [logger# ~logger
level# ~level]
(when (enabled? logger# level#)
(log-event
{:logger logger#
:level level#
:line ~line
:message (print-str ~x ~@more)})))
;; General form.
:else
`(let [logger# ~logger
level# ~level]
(when (enabled? logger# level#)
(-log-macro
{:logger logger#
:level level#
:line ~line}
print-str
~x
~@more))))))
(defmacro logf
"Log a message using a format string and args. Can optionally take a
throwable as its second arg."
{:arglists '([level fmt & fmt-args] [level throwable fmt & fmt-args])}
[level x & more]
(let [logger (str (ns-name *ns*))
line (:line (meta &form))]
(cond
;; Coverage-friendly form. Args are always evaluated and passed to the
;; helper function.
(coverage-mode?)
`(-log-macro
{:logger ~logger
:level ~level
:line ~line}
format
~x
~@more)
;; First argument can't be an error, use simpler form.
(or (string? x) (nil? more))
`(let [logger# ~logger
level# ~level]
(when (enabled? logger# level#)
(log-event
{:logger logger#
:level level#
:line ~line
:message (format ~x ~@more)})))
;; General form.
:else
`(let [logger# ~logger
level# ~level]
(when (enabled? logger# level#)
(-log-macro
{:logger logger#
:level level#
:line ~line}
format
~x
~@more))))))
(defmacro trace
"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 tracef
"Trace level logging using format."
{:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])}
[& args]
`(logf :trace ~@args))
(defmacro debug
"Debug level logging using print-style args."
{:arglists '([message & more] [throwable message & more])}
[& args]
`(logp :debug ~@args))
(defmacro debugf
"Debug level logging using format."
{:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])}
[& args]
`(logf :debug ~@args))
(defmacro info
"Info level logging using print-style args."
{:arglists '([message & more] [throwable message & more])}
[& args]
`(logp :info ~@args))
(defmacro infof
"Info level logging using format."
{:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])}
[& args]
`(logf :info ~@args))
(defmacro warn
"Warn level logging using print-style args."
{:arglists '([message & more] [throwable message & more])}
[& args]
`(logp :warn ~@args))
(defmacro warnf
"Warn level logging using format."
{:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])}
[& args]
`(logf :warn ~@args))
(defmacro error
"Error level logging using print-style args."
{:arglists '([message & more] [throwable message & more])}
[& args]
`(logp :error ~@args))
(defmacro errorf
"Error level logging using format."
{:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])}
[& args]
`(logf :error ~@args))
(defmacro fatal
"Fatal level logging using print-style args."
{:arglists '([message & more] [throwable message & more])}
[& args]
`(logp :fatal ~@args))
(defmacro fatalf
"Fatal level logging using format."
{:arglists '([fmt & fmt-args] [throwable fmt & fmt-args])}
[& args]
`(logf :fatal ~@args))