Skip to content

Commit d7b4735

Browse files
authored
Merge pull request #217 from atusy/rename-meta-in-json
feat: enable renaming meta fields
2 parents 2b2cf94 + eb536f8 commit d7b4735

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

R/layouts.R

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ layout_json <- function(fields = default_fields()) {
283283
#' Generate log layout function rendering JSON after merging meta
284284
#' fields with parsed list from JSON message
285285
#' @param fields character vector of field names to be included in the
286-
#' JSON
286+
#' JSON. If named, the names will be used as field names in the JSON.
287287
#' @export
288288
#' @note This functionality depends on the \pkg{jsonlite} package.
289289
#' @family log_layouts
@@ -297,6 +297,14 @@ layout_json <- function(fields = default_fields()) {
297297
#'
298298
#' log_layout(layout_json_parser(fields = c("time", "node")))
299299
#' log_info(cars = row.names(mtcars), species = unique(iris$Species))
300+
#'
301+
#' log_layout(layout_json_parser(fields = c(timestamp = "time", "node")))
302+
#' log_info(
303+
#' message = paste(
304+
#' "Compared to the previous example,
305+
#' the 'time' field is renamed to 'timestamp'"
306+
#' )
307+
#' )
300308
#' \dontshow{logger:::namespaces_set(old)}
301309
layout_json_parser <- function(fields = default_fields()) {
302310
force(fields)
@@ -317,6 +325,12 @@ layout_json_parser <- function(fields = default_fields()) {
317325
.topenv = .topenv
318326
)
319327
meta <- mget(fields, meta)
328+
field_names <- names(fields)
329+
if (!is.null(field_names)) {
330+
norename <- field_names == ""
331+
field_names[norename] <- fields[norename]
332+
meta <- setNames(meta, field_names)
333+
}
320334
msg <- jsonlite::fromJSON(msg)
321335

322336
jsonlite::toJSON(c(meta, msg), auto_unbox = TRUE, null = "null")

man/layout_json_parser.Rd

Lines changed: 9 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/testthat/test-layouts.R

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ test_that("JSON parser layout", {
4141
expect_output(log_info(skip_formatter('{"x": 4}')), '{"x":4}', fixed = TRUE)
4242
})
4343

44+
test_that("JSON parser layout can be renamed", {
45+
local_test_logger(layout = layout_json_parser(c(LEVEL = "level")))
46+
expect_output(log_info(skip_formatter('{"x": 4}')), '{"LEVEL":"INFO","x":4}', fixed = TRUE)
47+
})
48+
4449
test_that("must throw errors", {
4550
skip_if_not(getRversion() >= "4.3") # error call changed
4651

0 commit comments

Comments
 (0)