I'm using logger for logging. Now I want to log the contents of a data.frame
, currently, this yields something like this:
> logger::log_formatter(logger::formatter_paste)
> logger::log_info(data.frame(a = 1:3, b = 4:6))
INFO [2019-05-03 14:36:29] 1:3
INFO [2019-05-03 14:36:29] 4:6
This is not what I want, is it possible to get something like below
INFO [2019-05-03 14:36:29] a b
INFO [2019-05-03 14:36:29] 1 1 4
INFO [2019-05-03 14:36:29] 2 2 5
INFO [2019-05-03 14:36:29] 3 3 6
as print()
would give?
The default formatter in logger
is glue
(or sprintf
if the glue
package is not installed), which yields an error on passing data frames:
glue::glue(data.frame(a = 1:3, b = 4:6))
#> Error: All unnamed arguments must be length 1
sprintf(data.frame(a = 1:3, b = 4:6))
#> Error in sprintf(data.frame(a = 1:3, b = 4:6)) :
#> 'fmt' is not a character vector
So if you want logger
to work with data frames, you need a custom formatter, eg
formatter_data_frame <- function(df, ...) {
pander::pander_return(df, style = 'simple')
}
library(logger)
log_formatter(formatter_data_frame)
log_info(data.frame(a = 1:3, b = 4:6))
#> INFO [2019-05-04 11:33:47]
#> INFO [2019-05-04 11:33:47] a b
#> INFO [2019-05-04 11:33:47] --- ---
#> INFO [2019-05-04 11:33:47] 1 4
#> INFO [2019-05-04 11:33:47] 2 5
#> INFO [2019-05-04 11:33:47] 3 6
#> INFO [2019-05-04 11:33:47]
Or with what you tried to achieve with calling paste
on each line:
formatter_data_frame <- function(df, ...) {
apply(df, 1, paste, collapse = ' ')
}
log_formatter(formatter_data_frame)
log_info(data.frame(a = 1:3, b = 4:6))
#> INFO [2019-05-04 11:35:03] 1 4
#> INFO [2019-05-04 11:35:03] 2 5
#> INFO [2019-05-04 11:35:03] 3 6
Of course, you could tweak this further, eg to do this for a data.frame
and fall back to glue
on other objects etc
Another approach is using an eval helper:
df <- data.frame(a = 1:3, b = 4:6)
log_eval(df)
#> TRACE [2019-05-04 11:37:12] 'df' => 'structure(list(a = 1:3, b = 4:6), class = "data.frame", row.names = c(NA, -3L))'
If you think there's something missing from the package that would be useful, please open a ticket in the GitHub repo at https://github.com/daroczig/logger
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.