Debian Codegraph @

R/log_levels.R

raw
1 as_log_levels <- function(x){
2 assert(is_integerish(x) && identical(length(names(x)), length(x)))
3 assert(all_are_distinct(x))
4 assert(all_are_distinct(names(x)))
5 assert(
6 !anyNA(x) & all (x > 0),
7 "Log levels must be positive integers. The log levels `0` (off) and `NA` ",
8 "(all) are reserved."
9 )
10 x <- setNames(as.integer(x), names(x))
11 structure(sort(x), class = c("log_levels", "integer"))
12 }
13
14
15
16
17 DEFAULT_LOG_LEVELS <- c("fatal", "error", "warn", "info", "debug", "trace")
18
19
20
21
22 # manage options ----------------------------------------------------------
23
24 #' Manage Log Levels
25 #'
26 #' Display, add and remove character labels for log levels.
27 #'
28 #' @return a named `character` vector of the globally available log levels
29 #' (`add_log_levels()` and `remove_log_levels()` return invisibly).
30 #' @export
31 #'
32 #'
33 #' @section Default Log Levels:
34 #'
35 #' lgr comes with the following predefined log levels that are identical to
36 #' the log levels of log4j.
37 #'
38 #'\tabular{rll}{
39 #' Level \tab Name \tab Description \cr
40 #' `0` \tab off \tab A log level of 0/off tells a Logger or Appender to suspend all logging \cr
41 #' `100` \tab fatal \tab Critical error that leads to program abort. Should always indicate a `stop()` or similar \cr
42 #' `200` \tab error \tab A severe error that does not trigger program abort\cr
43 #' `300` \tab warn \tab A potentially harmful situation, like `warning()`\cr
44 #' `400` \tab info \tab An informational message on the progress of the application\cr
45 #' `500` \tab debug \tab Finer grained informational messages that are mostly useful for debugging\cr
46 #' `600` \tab trace \tab An even finer grained message than debug\cr
47 #' `NA` \tab all \tab A log level of NA/all tells a Logger or Appender to process all log events
48 #' }
49 #' @aliases log_levels log_level
50 #' @examples
51 #' get_log_levels()
52 #' add_log_levels(c(errorish = 250))
53 #' get_log_levels()
54 #' remove_log_levels("errorish")
55 #' get_log_levels()
56 get_log_levels <- function(){
57 getOption("lgr.log_levels")
58 }
59
60
61
62
63 #' @param levels a named `character` vector (see examples)
64 #' @rdname get_log_levels
65 #' @export
66 add_log_levels <- function(
67 levels
68 ){
69 levels_cur <- getOption("lgr.log_levels")
70 assert(
71 !is.null(levels_cur),
72 "lgr.log_levels option is not set. something is very wrong with lgr, please file a bug report"
73 )
74 assert(
75 is_integerish(levels),
76 "`levels` must be a named integer vector"
77 )
78 assert(length(names(levels)) && all_are_distinct(names(levels)))
79
80 levels_new <- setNames(as.integer(levels), names(levels))
81 levels_upd <- levels_new[levels_new %in% levels_cur]
82
83 if (length(levels_upd)){
84 message(
85 "Replacing existing log levels '",
86 fmt_log_levels(levels_new[levels_new %in% levels_cur]),
87 "' with '",
88 fmt_log_levels(levels_upd), "'"
89 )
90 }
91
92 res <- as_log_levels(named_union(levels_cur, levels_new))
93
94 options(lgr.log_levels = res)
95 invisible(get_log_levels())
96 }
97
98
99
100
101 #' union for named vectors. names of `y` override names of `x`
102 #' @noRd
103 named_union <- function(x, y){
104 assert(identical(length(names(x)), length(x)))
105 assert(identical(length(names(y)), length(y)))
106
107 r <- union(x, y)
108 names(r)[r %in% x] <- names(x[x %in% r])
109 names(r)[r %in% y] <- names(y[y %in% r])
110 r
111 }
112
113
114
115
116 #' @param level_names a `character` vector of the names of the levels to remove
117 #' @rdname get_log_levels
118 #' @export
119 remove_log_levels <- function(
120 level_names
121 ){
122 assert(is.character(level_names))
123 assert(
124 !any(DEFAULT_LOG_LEVELS %in% level_names),
125 "Cannot remove default log levels"
126 )
127 current_lvls <- getOption("lgr.log_levels")
128 assert(all(level_names %in% names(current_lvls)))
129 res <- current_lvls[!names(current_lvls) %in% level_names]
130 res <- as_log_levels(res)
131 options(lgr.log_levels = res)
132 invisible(get_log_levels())
133 }
134
135
136
137
138 # format ------------------------------------------------------------------
139
140 fmt_log_levels <- function(
141 x
142 ){
143 paste0(names(sort(x)), " (", sort(x), ")", collapse = ", ")
144 }
145
146
147
148
149 #' Colorize Levels
150 #'
151 #' @param x `numeric` or `character` levels to be colored. Unlike in many other
152 #' functions in lgr, `character` levels are *not* case sensitive in this
153 #' function and leading/trailing whitespace is ignored to make it more
154 #' comfortable to use `colorize_levels()` inside formatting functions.
155 #' @param transform a `function` to transform `x` (for example `toupper()`)
156 #' @inheritParams format.LogEvent
157 #'
158 #' @return a `character` vector wit color ANSI codes
159 #' @family formatting utils
160 #' @export
161 #'
162 #' @examples
163 #' cat(colorize_levels(c(100, 200)))
164 #' cat(colorize_levels(c("trace", "warn ", "DEBUG")))
165 #' cat(colorize_levels(c("trace", "warn ", "DEBUG"), transform = function(x) strtrim(x, 1) ))
166 colorize_levels <- function(
167 x,
168 colors = getOption("lgr.colors", NULL),
169 transform = identity
170 ){
171 if (length(x) && length(colors)){
172 if (is.character(x))
173 dd <- standardize_log_levels(trimws(tolower(x)))
174 else
175 dd <- standardize_log_levels(x)
176
177 cn <- standardize_log_levels( tolower(names(colors)))
178 for (i in seq_along(colors)){
179 sel <- dd == cn[[i]]
180 x[sel] <- colors[[i]](transform(x[sel]))
181 }
182 }
183
184 x
185 }
186
187
188
189
190 # standardize ------------------------------------------------------------
191
192 #' Standardize User-Input Log Levels to Their Integer Representation
193 #'
194 #' These are helper functions for verifying log levels and converting them from
195 #' their character to their integer representations. This is primarily useful
196 #' if you want to build your own [Loggers], [Appenders] or [Layouts] and need
197 #' to handle log levels in a way that is consistent with \pkg{lgr} .
198 #'
199 #' @param x a `character` or `integer` scalar, or vector for
200 #' standardize_log_levels
201 #' @param log_levels named `integer` vector of valid log levels
202 #'
203 #' @return An unnamed `integer` vector
204 #' @family docs relevant for extending lgr
205 #' @export
206 #' @examples
207 #'
208 #' standardize_threshold("info")
209 #' standardize_threshold("all")
210 #' is_threshold("all")
211 #' is_threshold("foobar")
212 #'
213 #' standardize_log_level("info")
214 #' # all is a valid threshold, but not a valid log level
215 #' try(is.na(standardize_log_level("all")))
216 #' is_log_level("all")
217 #'
218 #' # standardized_log_level intentionally only works with scalars, because many
219 #' # functions require scalar log level inputs
220 #' try(standardize_log_level(c("info", "fatal")))
221 #'
222 #' # You can still use standardize_log_levels() (plural) to work with vectors
223 #' standardize_log_levels(c("info", "fatal"))
224 standardize_threshold <- function(
225 x,
226 log_levels = c(getOption("lgr.log_levels"), c("all" = NA_integer_, "off" = 0L))
227 ){
228 assert(is_scalar(x), "A threshold must be a scalar (a vector of length 1)" )
229
230 if (is.na(x)){
231 return(NA_integer_)
232 }
233
234 if (is_integerish(x) && x >= 0){
235 return(as.integer(x))
236 }
237
238 if (is.character(x) && (x %in% names(log_levels)) ){
239 return(unname(log_levels[match(x, names(log_levels))]))
240 }
241
242 stop(error_msg_log_levels(deparse(substitute(x)), log_levels))
243 }
244
245
246
247
248 #' @rdname standardize_threshold
249 #' @export
250 is_threshold <- function(x){
251 tryCatch(
252 {standardize_threshold(x); TRUE},
253 error = function(...) FALSE
254 )
255 }
256
257
258
259
260 #' @rdname standardize_threshold
261 #' @export
262 standardize_log_level <- function(
263 x,
264 log_levels = getOption("lgr.log_levels")
265 ){
266 assert(is_scalar(x), "'", deparse(substitute(x)), "' must be a scalar log level")
267
268 if (is_integerish(x) && x > 0){
269 return(as.integer(x))
270 }
271
272 if (is.character(x) && (x %in% names(log_levels)) ){
273 return(unname(log_levels[match(x, names(log_levels))]))
274 }
275
276 stop(error_msg_log_levels(deparse(substitute(x)), log_levels))
277 }
278
279
280
281
282 #' @rdname standardize_threshold
283 #' @export
284 is_log_level <- function(x){
285 tryCatch(
286 {standardize_log_level(x); TRUE},
287 error = function(...) FALSE
288 )
289 }
290
291
292
293
294 #' @rdname standardize_threshold
295 #' @export
296 standardize_log_levels <- function(
297 x,
298 log_levels = getOption("lgr.log_levels")
299 ){
300
301 if (is_integerish(x) && all(x > 0)){
302 return(as.integer(x))
303 }
304
305 if (is.character(x) && all(x %in% names(log_levels)) ){
306 return(unname(log_levels[match(x, names(log_levels))]))
307 }
308
309 stop(error_msg_log_levels(deparse(substitute(x)), log_levels))
310 }
311
312
313
314
315 #' @rdname standardize_threshold
316 #' @export
317 is_log_levels <- function(x){
318 tryCatch(
319 {standardize_log_levels(x); TRUE},
320 error = function(...) FALSE
321 )
322 }
323
324
325
326
327 error_msg_log_levels <- function(varname, log_levels){
328 ll_text <-
329 paste(sprintf("%s (%s)", names(log_levels), log_levels), collapse = ", ")
330
331 paste0(
332 "'", varname, "' must either the numeric or character representation ",
333 "of one of the following log levels: ", ll_text
334 )
335 }
336
337
338
339
340 # label/unlabel -----------------------------------------------------------
341
342 #' Label/Unlabel Log Levels
343 #'
344 #' @param levels an `integer` vector of log levels
345 #' @param labels a `character` vector of log level labels. Please note that
346 #' log levels are lowercase by default, even if many appenders print them
347 #' in uppercase.
348 #' @inheritParams standardize_threshold
349 #'
350 #' @return a `character` vector for `label_levels()` and an integer vector for
351 #' `unlabel_levels`
352 #'
353 #' @seealso [get_log_levels()]
354 #' @family formatting utils
355 #' @export
356 #' @examples
357 #' x <- label_levels(c(seq(0, 600, by = 100), NA))
358 #' print(x)
359 #' unlabel_levels(x)
360 label_levels <- function(
361 levels,
362 log_levels = getOption("lgr.log_levels")
363 ){
364 if (!is.numeric(levels))
365 stop("Expected numeric 'levels'")
366
367 res <- names(log_levels)[match(levels, log_levels)]
368 res[is.na(levels)] <- "all"
369 res[levels == 0] <- "off"
370 names(res) <- levels
371
372 if (anyNA(res))
373 warning("Some `levels` were not valid numeric log levels, coercing to `NA`")
374
375 res
376 }
377
378
379
380
381 #' @rdname label_levels
382 #' @export
383 unlabel_levels <- function(
384 labels,
385 log_levels = getOption("lgr.log_levels")
386 ){
387 if (!is.character(labels))
388 stop("Expected character 'labels'")
389
390 res <- log_levels[match(labels, names(log_levels))]
391 if (!is.null(names(labels)) && anyNA(res)){
392 res[is.na(res)] <- as.integer(names(labels)[is.na(res)])
393 }
394
395 if (anyNA(labels) || any(!labels %in% c(names(log_levels), "all", "off")))
396 warning(
397 "Some `labels` were not valid character log levels. Please",
398 "consider adding them to the global log levels with `?add_log_levels`"
399 )
400
401 res[labels == "off"] <- 0L
402 names(res) <- labels
403 res
404 }