Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: enable renaming meta fields #217

Merged
merged 4 commits into from
Jan 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading