Skip to content

Commit

Permalink
Merge pull request #217 from atusy/rename-meta-in-json
Browse files Browse the repository at this point in the history
feat: enable renaming meta fields
  • Loading branch information
daroczig authored Jan 25, 2025
2 parents 2b2cf94 + eb536f8 commit d7b4735
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
16 changes: 15 additions & 1 deletion R/layouts.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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")
Expand Down
10 changes: 9 additions & 1 deletion man/layout_json_parser.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions tests/testthat/test-layouts.R
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit d7b4735

Please sign in to comment.