File: logging.r

package info (click to toggle)
r-cran-irkernel 1.3.2%2Bgit20240429.124f234-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 400 kB
  • sloc: python: 242; javascript: 69; makefile: 26; sh: 15
file content (88 lines) | stat: -rw-r--r-- 2,230 bytes parent folder | download | duplicates (3)
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
# The primitive jupyter logging system...
# Per default, only error messages are shown
# levels: 3 = DEBUG, 2 = INFO/MSG, 1 = ERROR

#' Kernel logging functions
#'
#' A set of exported logging utilities that have the capability to be used in upstream projects.
#' Log level and log file can be set via R package options e.g. \code{options(jupyter.log_level = 2L)}
#' or from the environment variables JUPYTER_LOG_LEVEL and JUPYTER_LOGFILE.
#'
#' @param ...  message to log
#' @name log
NULL

#' @rdname log
#' @export
log_debug <- function(...) {
    if (isTRUE(getOption('jupyter.log_level') >= 3L)) {
        log_msg('DEBUG', sprintf(...))
    }
}

#' @rdname log
#' @export
log_info <- function(...) {
    if (isTRUE(getOption('jupyter.log_level') >= 2L)) {
        log_msg('INFO', sprintf(...))
    }
}

#' @rdname log
#' @export
log_error <- function(...) {
    if (isTRUE(getOption('jupyter.log_level') >= 1L)) {
        log_msg('ERROR', sprintf(...))
    }
}

log_msg <- function(lvl, msg) {
    log_msg_stderror(lvl, msg)
    log_msg_logfile(lvl, msg)
}


# Handle for stderr to even log to the console when the stderr() points to a
# sink'ed connection...
.stderror <- stderr()

log_msg_stderror <- function(lvl, msg) {
    cat(sprintf('%s: %s\n', log_color(lvl), msg) , file = .stderror)
}

#' @importFrom crayon blue
#' @importFrom crayon green
#' @importFrom crayon red
log_color <- function(lvl) {
    color <- switch(lvl,
        DEBUG = green,
        INFO  = blue,
        ERROR = red,
        stop('unknown level: ', lvl))
    
    color(lvl)
}

.is_changed_logfile <- local({
    old_logfile <- ''
    function(logfile) {
        if (old_logfile != logfile) {
            old_logfile <<- logfile
            TRUE
        } else {
            FALSE
        }
    }
})

log_msg_logfile <- function(lvl, msg) {
    cur_logfile <- getOption('jupyter.logfile')
    if (!is.na(cur_logfile)) {
        if (.is_changed_logfile(cur_logfile)) {
            log_msg_stderror('INFO', sprintf('Logging to %s', cur_logfile))
        }
        log_con <- file(cur_logfile, open = 'ab')
        writeBin(charToRaw(sprintf('%s %s: %s\n', format(Sys.time()), lvl, msg)), log_con, endian = 'little')
        close(log_con)
    }
}