Debian Codegraph @

R/log.R

raw
1
2 # the log level, indicating what severity of messages will be logged
3 the$log_level <- 4L
4
5 # the file to which log messages will be written
6 the$log_file <- NULL
7
8 # the scopes for which filtering will be enabled
9 the$log_scopes <- NULL
10
11 elog <- function(scope, fmt, ...) {
12 renv_log_impl(4L, scope, fmt, ...)
13 }
14
15 wlog <- function(scope, fmt, ...) {
16 renv_log_impl(3L, scope, fmt, ...)
17 }
18
19 ilog <- function(scope, fmt, ...) {
20 renv_log_impl(2L, scope, fmt, ...)
21 }
22
23 dlog <- function(scope, fmt, ...) {
24 renv_log_impl(1L, scope, fmt, ...)
25 }
26
27
28 renv_log_impl <- function(level, scope, fmt, ...) {
29
30 # check log level
31 if (level < the$log_level)
32 return()
33
34 # only include scopes matching the scopes
35 scopes <- the$log_scopes
36 if (is.character(scopes) && !scope %in% scopes)
37 return()
38
39 # build message
40 message <- sprintf(fmt, ...)
41
42 # annotate with prefix from scope, timestamp
43 fmt <- "%sZ [renv-%i] %s: %s"
44 now <- format(Sys.time(), format = "%Y-%m-%d %H:%M:%OS6", tz = "UTC")
45 all <- sprintf(fmt, now, Sys.getpid(), scope, message)
46
47 # write it out
48 cat(all, file = the$log_file, sep = "\n", append = TRUE)
49
50 }
51
52 renv_log_init <- function(level = NULL, file = NULL, scopes = NULL) {
53 the$log_level <- renv_log_level(level)
54 the$log_file <- renv_log_file(file)
55 the$log_scopes <- renv_log_scopes(scopes)
56 }
57
58 renv_log_level <- function(level = NULL) {
59
60 level <- level %||% Sys.getenv("RENV_LOG_LEVEL", unset = NA)
61 if (is.na(level))
62 return(4L)
63
64 case(
65 level %in% c("4", "error", "ERROR") ~ 4L,
66 level %in% c("3", "warning", "WARNING") ~ 3L,
67 level %in% c("2", "info", "INFO") ~ 2L,
68 level %in% c("1", "debug", "DEBUG") ~ 1L,
69 ~ {
70 warningf("ignoring invalid RENV_LOG_LEVEL '%s'", level)
71 4L
72 }
73 )
74
75 }
76
77 renv_log_file <- function(file = NULL) {
78
79 # check for log file
80 file <- file %||% Sys.getenv("RENV_LOG_FILE", unset = NA)
81 if (!is.na(file))
82 return(file)
83
84 # default to stderr, since it's unbuffered
85 stderr()
86
87 }
88
89 renv_log_scopes <- function(scopes = NULL) {
90
91 scopes <- scopes %||% Sys.getenv("RENV_LOG_SCOPES", unset = NA)
92 if (is.na(scopes))
93 return(NULL)
94
95 strsplit(scopes, ",", fixed = TRUE)[[1L]]
96
97 }
98