-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathLogEvent.R
527 lines (444 loc) · 14.4 KB
/
LogEvent.R
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# LogEvent ----------------------------------------------------------------
#' LogEvents - The atomic unit of logging
#'
#' @description
#' A `LogEvent` is a single unit of data that should be logged. `LogEvents` are
#' usually created by a [Logger], and then processed by one more [Appenders].
#' They do not need to be instantiated manually except for testing and
#' experimentation; however, if you plan on writing your own Appenders or
#' Layouts you need to understand LogEvents.
#'
#' @seealso [as.data.frame.LogEvent()]
#' @family docs relevant for extending lgr
#' @aliases LogEvents
#' @examples
#' lg <- get_logger("test")
#' lg$error("foo bar")
#'
#' # The last LogEvent produced by a Logger is stored in its `last_event` field
#' lg$last_event # formatted console output
#' lg$last_event$values # values stored in the event
#'
#' # Also contains the Logger that created it as .logger
#' lg$last_event$logger
#' # equivalent to
#' lg$last_event$.logger$name
#'
#' # This is really a reference to the complete Logger, so the following is
#' # possible (though nonsensical)
#' lg$last_event$.logger$last_event$msg
#' identical(lg, lg$last_event$.logger)
#' lg$config(NULL) # reset logger config
#' @export
LogEvent <- R6::R6Class(
"LogEvent",
lock_objects = FALSE,
public = list(
#' @description
#' The arguments to `LogEvent$new()` directly translate to the fields stored
#' in the `LogEvent`. Usually these values will be scalars, but (except for
#' `"logger"`) they can also be vectors if they are all of the same length (or
#' scalars that will be recycled). In this case the event will be treated by
#' the [Appenders] and [Layouts] as if several separate events.
#'
#' @param ... All named arguments in `...` will be added to the LogEvent
#' as **custom fields**. You can store arbitrary \R objects in LogEvents
#' this way, but not all Appenders will support them. See [AppenderJson] for
#' @param logger,level,timestamp,caller,msg see **Public fields**.
initialize = function(
logger,
level = 400,
timestamp = Sys.time(),
caller = NA,
msg = NA,
...
){
assert(inherits(logger, "Logger"))
# assign has less overhead than [[ and event creation needs to be as fast
# as possible
assign(".logger", logger, self)
assign("level", level, self)
assign("timestamp", timestamp, self)
assign("caller", caller, self)
assign("msg", msg, self)
# custom values
if (!missing(...)){
dots <- list(...)
assert(identical(length(names(dots)), length(dots)))
# the rev() ensures that the values get added int eh same order as
# the user entered them
for (nm in rev(names(dots))){
assign(nm, dots[[nm]], self)
}
}
},
#' @field level `integer`. The [log_level] / priority of the LogEvent. Use the
#' active binding `level_name` to get the `character` representation
#' instead.
level = NULL,
#' @field timestamp [`POSIXct`][base::POSIXct]. The time when then the
#' LogEvent was created.
timestamp = NULL,
#' @field caller `character`. The name of the calling function.
caller = NULL,
#' @field msg `character`. The log message.
msg = NULL,
#' @field .logger [Logger]. A reference to the Logger that created the
#' event (equivalent to `get_logger(event$logger)`).
.logger = NULL
),
active = list(
#' @field values `list`. All values stored in the `LogEvent`, including
#' all *custom fields*, but not including `event$.logger`.
values = function(){
fixed_vals <- c("level", "timestamp", "logger", "caller", "msg")
custom_vals <- setdiff(
names(get(".__enclos_env__", self)[["self"]]),
c(".__enclos_env__", "level_name", "initialize", "clone", "values",
".logger")
)
valnames <- union(fixed_vals, custom_vals) # to enforce order of fixed_vals
mget(valnames, envir = self)
},
#' @field level_name `character`. The [log_level] / priority of the LogEvent labelled
#' according to `getOption("lgr.log_levels")`
level_name = function(){
label_levels(get("level", envir = self))
},
#' @field logger `character` scalar. The name of the Logger that
#' created this event, equivalent to `event$.logger$name`)
logger = function(){
get("name", envir = get(".logger", envir = self))
}
)
)
# coercion ---------------------------------------------------
#' Coerce LogEvents to Data Frames
#'
#' Coerce LogEvents to `data.frames`, [`data.tables`][data.table::data.table],
#' or [`tibbles`][tibble::tibble].
#'
#' @inheritParams base::as.data.frame
#' @param stringsAsFactors `logical` scalar: should `character` vectors be
#' converted to factors? Defaults to `FALSE` (as opposed to
#' [base::as.data.frame()]) and is only included for compatibility.
#' @param ... passed on to `data.frame()`
#' @param optional currently ignored and only included for compatibility.
#' @param box_if a `function` that returns `TRUE` or `FALSE` to determine
#' which values are to be boxed (i.e. placed as single elements in a list
#' column). See example
#' @param cols_expand `character` vector. Columns to *not* box (even if
#' `box_if()` returns `TRUE`). Vectors in these columns will result in multiple
#' rows in the result (rather than a single list-column row). This defaults to
#' `"msg"` for vectorized logging over the log message.
#' @export
#' @seealso [data.table::data.table], [tibble::tibble]
#'
#' @examples
#' lg <- get_logger("test")
#' lg$info("lorem ipsum")
#' as.data.frame(lg$last_event)
#'
#' lg$info("LogEvents can store any custom log values", df = iris)
#' as.data.frame(lg$last_event)
#' head(as.data.frame(lg$last_event)$df[[1]])
#'
#' # how boxing works
#'
#' # by default non-scalars are boxed
#' lg$info("letters", letters = letters)
#' as.data.frame(lg$last_event)
#'
#' # this behaviour can be modified by supplying a custom boxing function
#' as.data.frame(lg$last_event, box_if = function(.) FALSE)
#' as.data.frame(lg$last_event, cols_expand = "letters")
#'
#' # The `msg` argument of a log event is always vectorized
#' lg$info(c("a vectorized", "log message"))
#' as.data.frame(lg$last_event)
#'
#' lg$config(NULL)
as.data.frame.LogEvent <- function(
x,
row.names = NULL,
optional = FALSE,
stringsAsFactors = FALSE,
...,
box_if = function(.) !(is.atomic(.) && identical(length(.), 1L)),
cols_expand = NULL
){
assert(is.null(cols_expand) || is.character(cols_expand))
boxer <- function(.) I(list(.))
values <- do_box_if(x$values, box_if, except = cols_expand, boxer = boxer)
msg_len <- length(x[["msg"]])
cols_expand <- c("msg", cols_expand)
# as.data.frame requires manual recycling
if (msg_len > 1){
for (i in seq_along(values)){
if (identical(length(values[[i]]), 1L))
values[[i]] <- rep(values[[i]], msg_len)
}
values <- do_box_if(values, box_if, except = cols_expand, boxer = I)
}
do.call(
data.frame,
c(values,
stringsAsFactors = stringsAsFactors,
row.names = row.names,
...
)
)
}
#' @rdname as.data.frame.LogEvent
as.data.table.LogEvent <- function(
x,
...,
box_if = function(.) !(is.atomic(.) && identical(length(.), 1L)),
cols_expand = "msg"
){
values <- do_box_if(x$values, box_if, cols_expand)
data.table::as.data.table(values)
}
#' @rdname as.data.frame.LogEvent
as_tibble.LogEvent <- function(
x,
...,
box_if = function(.) !(is.atomic(.) && identical(length(.), 1L)),
cols_expand = "msg"
){
values <- do_box_if(x$values, box_if, cols_expand)
tibble::as_tibble(values)
}
# printing ---------------------------------------------------
#' Print or Format Logging Data
#'
#' @param x a [LogEvent]
#' @param timestamp_fmt see [format.POSIXct()]
#' @param fmt A `character` scalar that may contain any of the tokens listed
#' bellow in the section Format Tokens.
#' @param colors A `list` of `functions` that will be used to color the
#' log levels (likely from [crayon::crayon]).
#' @inheritParams standardize_threshold
#' @param pad_levels `right`, `left` or `NULL`. Whether or not to pad the log
#' level names to the same width on the left or right side, or not at all.
#' @param ... ignored
#'
#' @section Format Tokens:
#' \describe{
#' \item{`%t`}{The timestamp of the message, formatted according to
#' `timestamp_fmt`)}
#' \item{`%l`}{the log level, lowercase `character` representation}
#' \item{`%L`}{the log level, uppercase `character` representation}
#' \item{`%k`}{the log level, first letter of lowercase `character` representation}
#' \item{`%K`}{the log level, first letter of uppercase `character` representation}
#' \item{`%n`}{the log level, `integer` representation}
#' \item{`%g`}{the name of the logger}
#' \item{`%p`}{the PID (process ID). Useful when logging code that uses
#' multiple threads.}
#' \item{`%c`}{the calling function}
#' \item{`%m`}{the log message}
#' \item{`%f`}{all custom fields of `x` in a pseudo-JSON like format that is
#' optimized for human readability and console output}
#' \item{`%j`}{all custom fields of `x` in proper JSON. This requires that you
#' have **jsonlite** installed and does not support colors as opposed to
#' `%f`
#' }
#' }
#'
#' @return `x` for `print()` and a `character` scalar for `format()`
#' @export
#'
#' @examples
#' # standard fields can be printed using special tokens
#' x <- LogEvent$new(
#' level = 300, msg = "a test event", caller = "testfun()", logger = lgr
#' )
#' print(x)
#' print(x, fmt = c("%t (%p) %c: %n - %m"))
#' print(x, colors = NULL)
#'
#' # custom values
#' y <- LogEvent$new(
#' level = 300, msg = "a gps track", logger = lgr,
#' waypoints = 10, location = "Austria"
#' )
#'
#' # default output with %f
#' print(y)
#'
#' # proper JSON output with %j
#' if (requireNamespace("jsonlite")){
#' print(y, fmt = "%L [%t] %m %j")
#' }
#'
print.LogEvent <- function(
x,
fmt = "%L [%t] %m %f",
timestamp_fmt = "%Y-%m-%d %H:%M:%S",
colors = getOption("lgr.colors"),
log_levels = getOption("lgr.log_levels"),
pad_levels = "right",
...
){
cat(format(
x,
fmt = fmt,
timestamp_fmt = timestamp_fmt,
colors = colors,
log_levels = log_levels,
pad_levels = pad_levels
), sep = "\n")
invisible(x)
}
#' @rdname print.LogEvent
#' @export
format.LogEvent <- function(
x,
fmt = "%L [%t] %m %f",
timestamp_fmt = "%Y-%m-%d %H:%M:%S",
colors = NULL,
log_levels = getOption("lgr.log_levels"),
pad_levels = "right",
...
){
stopifnot(
is_scalar_character(fmt),
is_scalar_character(timestamp_fmt),
is_scalar_character(pad_levels) || is.null(pad_levels)
)
# init
lvls <- label_levels(x$level, log_levels = log_levels)
lvls[is.na(lvls)] <- x$level[is.na(lvls)]
if (!is.null(pad_levels)){
nchar_max <- max(nchar(names(log_levels)))
diff <- nchar_max - nchar(lvls)
pad <- vapply(diff, function(i) paste(rep.int(" ", i), collapse = ""), character(1))
if (pad_levels == "right"){
lvls <- paste0(lvls, pad)
} else {
lvls <- paste0(pad, lvls)
}
} else {
lvls <- x$level
}
# tokenize
tokens <- tokenize_format(
fmt,
valid_tokens = paste0(
"%",
c("t", "p", "c", "m", "l", "L", "n", "f", "j", "k", "K", "g"))
)
# format
len <- length(tokens)
res <- vector("list", length(tokens))
for(i in seq_len(len)){
res[[i]] <- switch(
tokens[[i]],
"%n" = colorize_levels(x$level, colors),
"%l" = colorize_levels(lvls, colors),
"%L" = colorize_levels(toupper(lvls), colors),
"%k" = colorize_levels(substr(lvls, 1, 1), colors),
"%K" = colorize_levels(substr(toupper(lvls), 1, 1), colors),
"%t" = format(get("timestamp", envir = x), format = timestamp_fmt),
"%m" = get("msg", envir = x),
"%c" = get("caller", envir = x),
"%g" = get("logger", envir = x),
"%p" = Sys.getpid(),
"%f" = format_custom_fields(get_custom_fields(x), color = length(colors)),
"%j" = jsonlite::toJSON(get_custom_fields(x), auto_unbox = TRUE),
tokens[[i]]
)
}
do.call(paste0, res)
}
#' Convert a LogEvent to a character string
#'
#' @param x a [LogEvent]
#' @param ... ignored
#'
#' @return a `character` scalar
#' @export
#'
#' @examples
#' toString(LogEvent$new(logger = lgr::lgr))
toString.LogEvent <- function(x, ...){
paste(
paste0("$", names(x$values), ": ", vapply(x$values, function(.) preview_object(.), character(1L))),
collapse = ", "
)
}
# utils -------------------------------------------------------------------
do_box_if <- function(x, predicate, except, boxer = list){
sel <-
vapply(x, predicate, TRUE, USE.NAMES = FALSE)
if (length(except)){
sel[(names(x) %in% except)] <- FALSE
}
for (i in seq_along(x))
if (sel[[i]])
x[[i]] <- boxer(x[[i]])
x
}
get_custom_fields <- function(x){
x$values[!names(x$values) %in% DEFAULT_FIELDS]
}
format_custom_fields <- function(
x,
color = TRUE
){
if (!length(x)) return("")
max_len <- max(512 / length(x) - sum(nchar(names(x))), 16)
braces <- c("{", "}")
brackets <- c("[", "]")
colon <- ": "
comma <- ", "
dots <- ".."
if (!color){
style_subtle <- identity
style_accent <- identity
} else {
braces <- style_subtle(braces)
brackets <- style_subtle(brackets)
colon <- style_subtle(colon)
comma <- style_subtle(comma)
dots <- style_subtle("..")
}
res <- lapply(
x,
preview_object,
width = max_len, brackets = brackets, dots = dots, quotes = c("", "")
)
paste0(
braces[[1L]],
paste(
style_accent(names(res)), colon, res,
sep = "",
collapse = comma
),
braces[[2L]]
)
}
tokenize_format <- function(
x,
valid_tokens = NULL
){
pos <- unlist(gregexpr("%.", x))
if (identical(pos, -1L))
return(x)
pos <- sort(unique(c(1L, pos, pos + 2L, nchar(x) + 1L)))
res <- vector("character", length(x))
for(i in seq_len(length(pos) - 1L)) {
res[[i]] <- substr(x, pos[[i]], pos[[i + 1L]] - 1L)
}
if (!is.null(valid_tokens)){
placeholders <- grep("%", res, value = TRUE, fixed = TRUE)
assert(
all(placeholders %in% valid_tokens),
"'format' contains unrecognised format specifications: ",
paste(sort(setdiff(placeholders, valid_tokens)), collapse = ", ")
)
}
res
}
# globals --------------------------------------------------------
DEFAULT_FIELDS <- c("level", "timestamp", "logger", "caller", "msg")