diff --git a/R/layouts.R b/R/layouts.R index bd852dca..adc8cd40 100644 --- a/R/layouts.R +++ b/R/layouts.R @@ -283,7 +283,7 @@ layout_json <- function(fields = default_fields()) { #' Generate log layout function rendering JSON after merging meta #' fields with parsed list from JSON message #' @param fields character vector of field names to be included in the -#' JSON +#' JSON. If named, the names will be used as field names in the JSON. #' @export #' @note This functionality depends on the \pkg{jsonlite} package. #' @family log_layouts @@ -297,6 +297,14 @@ layout_json <- function(fields = default_fields()) { #' #' log_layout(layout_json_parser(fields = c("time", "node"))) #' log_info(cars = row.names(mtcars), species = unique(iris$Species)) +#' +#' log_layout(layout_json_parser(fields = c(timestamp = "time", "node"))) +#' log_info( +#' message = paste( +#' "Compared to the previous example, +#' the 'time' field is renamed to 'timestamp'" +#' ) +#' ) #' \dontshow{logger:::namespaces_set(old)} layout_json_parser <- function(fields = default_fields()) { force(fields) @@ -317,6 +325,12 @@ layout_json_parser <- function(fields = default_fields()) { .topenv = .topenv ) meta <- mget(fields, meta) + field_names <- names(fields) + if (!is.null(field_names)) { + norename <- field_names == "" + field_names[norename] <- fields[norename] + meta <- setNames(meta, field_names) + } msg <- jsonlite::fromJSON(msg) jsonlite::toJSON(c(meta, msg), auto_unbox = TRUE, null = "null") diff --git a/man/layout_json_parser.Rd b/man/layout_json_parser.Rd index 390ea591..33489730 100644 --- a/man/layout_json_parser.Rd +++ b/man/layout_json_parser.Rd @@ -9,7 +9,7 @@ layout_json_parser(fields = default_fields()) } \arguments{ \item{fields}{character vector of field names to be included in the -JSON} +JSON. If named, the names will be used as field names in the JSON.} } \description{ Generate log layout function rendering JSON after merging meta @@ -28,6 +28,14 @@ log_info(everything = 42) log_layout(layout_json_parser(fields = c("time", "node"))) log_info(cars = row.names(mtcars), species = unique(iris$Species)) + +log_layout(layout_json_parser(fields = c(timestamp = "time", "node"))) +log_info( + message = paste( + "Compared to the previous example, + the 'time' field is renamed to 'timestamp'" + ) +) \dontshow{logger:::namespaces_set(old)} } \seealso{ diff --git a/tests/testthat/test-layouts.R b/tests/testthat/test-layouts.R index a42c11e5..e8d6e1d0 100644 --- a/tests/testthat/test-layouts.R +++ b/tests/testthat/test-layouts.R @@ -41,6 +41,11 @@ test_that("JSON parser layout", { expect_output(log_info(skip_formatter('{"x": 4}')), '{"x":4}', fixed = TRUE) }) +test_that("JSON parser layout can be renamed", { + local_test_logger(layout = layout_json_parser(c(LEVEL = "level"))) + expect_output(log_info(skip_formatter('{"x": 4}')), '{"LEVEL":"INFO","x":4}', fixed = TRUE) +}) + test_that("must throw errors", { skip_if_not(getRversion() >= "4.3") # error call changed