Debian Codegraph @

R/logging.r

raw symbols SCIP
1 # The primitive jupyter logging system...
2 # Per default, only error messages are shown
3 # levels: 3 = DEBUG, 2 = INFO/MSG, 1 = ERROR
4
5 #' Kernel logging functions
6 #'
7 #' A set of exported logging utilities that have the capability to be used in upstream projects.
8 #' Log level and log file can be set via R package options e.g. \code{options(jupyter.log_level = 2L)}
9 #' or from the environment variables JUPYTER_LOG_LEVEL and JUPYTER_LOGFILE.
10 #'
11 #' @param ... message to log
12 #' @name log
13 NULL
14
15 #' @rdname log
16 #' @export
17 log_debug <- function(...) {
18 if (isTRUE(getOption('jupyter.log_level') >= 3L)) {
19 log_msg('DEBUG', sprintf(...))
20 }
21 }
22
23 #' @rdname log
24 #' @export
25 log_info <- function(...) {
26 if (isTRUE(getOption('jupyter.log_level') >= 2L)) {
27 log_msg('INFO', sprintf(...))
28 }
29 }
30
31 #' @rdname log
32 #' @export
33 log_error <- function(...) {
34 if (isTRUE(getOption('jupyter.log_level') >= 1L)) {
35 log_msg('ERROR', sprintf(...))
36 }
37 }
38
39 log_msg <- function(lvl, msg) {
40 log_msg_stderror(lvl, msg)
41 log_msg_logfile(lvl, msg)
42 }
43
44
45 # Handle for stderr to even log to the console when the stderr() points to a
46 # sink'ed connection...
47 .stderror <- stderr()
48
49 log_msg_stderror <- function(lvl, msg) {
50 cat(sprintf('%s: %s\n', log_color(lvl), msg) , file = .stderror)
51 }
52
53 #' @importFrom crayon blue
54 #' @importFrom crayon green
55 #' @importFrom crayon red
56 log_color <- function(lvl) {
57 color <- switch(lvl,
58 DEBUG = green,
59 INFO = blue,
60 ERROR = red,
61 stop('unknown level: ', lvl))
62
63 color(lvl)
64 }
65
66 .is_changed_logfile <- local({
67 old_logfile <- ''
68 function(logfile) {
69 if (old_logfile != logfile) {
70 old_logfile <<- logfile
71 TRUE
72 } else {
73 FALSE
74 }
75 }
76 })
77
78 log_msg_logfile <- function(lvl, msg) {
79 cur_logfile <- getOption('jupyter.logfile')
80 if (!is.na(cur_logfile)) {
81 if (.is_changed_logfile(cur_logfile)) {
82 log_msg_stderror('INFO', sprintf('Logging to %s', cur_logfile))
83 }
84 log_con <- file(cur_logfile, open = 'ab')
85 writeBin(charToRaw(sprintf('%s %s: %s\n', format(Sys.time()), lvl, msg)), log_con, endian = 'little')
86 close(log_con)
87 }
88 }