Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 登录到数据库_R_Logging - Fatal编程技术网

R 登录到数据库

R 登录到数据库,r,logging,R,Logging,试图将消息、警告和错误重定向到数据库,我想出了一种装饰函数: with_db_log <- function(expr, con=NULL) { stopifnot(!is.null(con)) do_log <- function(lvl, cnd) { if(inherits(con, "try-error")) return() dat <- data.frame( ts=strf

试图将
消息
警告
错误
重定向到数据库,我想出了一种装饰函数:

with_db_log <- function(expr, con=NULL) {
    stopifnot(!is.null(con))
    do_log <- function(lvl, cnd) {
        if(inherits(con, "try-error")) return()
        dat <- data.frame(
            ts=strftime(Sys.time(), "%Y-%m-%d %H:%M:%S"),
            lvl=lvl,
            msg=trimws(conditionMessage(cnd)),
            stringsAsFactors=FALSE
        )
        DBI::dbWriteTable(con, name="log", value=dat, append=TRUE) 
    }
    
    tryCatch(
        error = function(cnd) {
            do_log(lvl="error", cnd=cnd)
            invisible(structure(conditionMessage(cnd), class = "try-error", condition = cnd))
        },
        withCallingHandlers(
            message = function(cnd) {do_log(lvl="message", cnd=cnd)},
            warning = function(cnd) {do_log(lvl="warning", cnd=cnd)},
            expr
        )
    )
}
    
数据库表
log
和列
ts
lvl
msg
得到更新

(我使用stackoverflow编写代码,但再也找不到链接了。)

但是,它似乎并非在所有情况下都有效:有时
msg
字段仍然为空。对我来说,要弄清楚这些案件是什么并不容易。我怀疑上面的代码有问题:

msg=trimws(conditionMessage(cnd))
但我找不到问题所在

是否有更好的方法从条件中提取日志消息?任何提示,不胜感激

msg=trimws(conditionMessage(cnd))