Debian Codegraph @

R/LayoutJson.R

raw
1 # LayoutJson --------------------------------------------------------------
2
3 #' Format LogEvents as JSON
4 #'
5 #' @description
6 #' A format for formatting LogEvents as
7 #' [jsonlines](https://jsonlines.org/) log files. This provides a
8 #' nice balance between human- an machine-readability.
9 #'
10 #' @family Layouts
11 #' @seealso [read_json_lines()], [https://jsonlines.org/](https://jsonlines.org/)
12 #' @export
13 #' @examples
14 #' # setup a dummy LogEvent
15 #' event <- LogEvent$new(
16 #' logger = Logger$new("dummy logger"),
17 #' level = 200,
18 #' timestamp = Sys.time(),
19 #' caller = NA_character_,
20 #' msg = "a test message",
21 #' custom_field = "LayoutJson can handle arbitrary fields"
22 #' )
23 #'
24 #' lo <- LayoutJson$new()
25 #' lo$format_event(event)
26 #'
27 #' lo <- LayoutJson$new(
28 #' transform_event_names = toupper,
29 #' excluded_fields = c("RAWMSG", "CALLER"))
30 #'
31 #' lo$format_event(event)
32 #'
33 #' lo <- LayoutJson$new(
34 #' transform_event = function(e) {
35 #' values <- e$values
36 #' values$msg <- toupper(values$msg)
37 #' values
38 #' },
39 #' timestamp_fmt = "%a %b %d %H:%M:%S %Y",
40 #' excluded_fields = c("RAWMSG", "CALLER"))
41 #'
42 #' lo$format_event(event)
43 LayoutJson <- R6::R6Class(
44 "LayoutJson",
45 inherit = Layout,
46 public = list(
47
48 #' @description
49 #' Creates a new instance of this [R6][R6::R6Class] class.
50 #'
51 #' @param toJSON_args a list of arguments passed to [jsonlite::toJSON()],
52 #'
53 #' @param transform_event a `function` with a single argument that
54 #' takes a [LogEvent] object and returns a `list` of values.
55 #'
56 #' @param timestamp_fmt Format to be applied to the timestamp. This is
57 #' applied after `transform_event` but `before transform_event_names`
58 #' * `NULL`: formatting of the timestamp is left to [jsonlite::toJSON()],
59 #' * a `character` scalar as for [format.POSIXct()], or
60 #' * a `function` that returns a vector of the same length as its
61 #' ([POSIXct]) input. The returned vector can be of any type
62 #' supported by [jsonlite::toJSON()].
63 #'
64 #' @param transform_event_names
65 #' * `NULL`: don't process names
66 #' * a named `character` vector of the format `new_name = old_name`
67 #' * or a `function` with a single mandatory argument that accepts a
68 #' `character` vector of field names. Applied after `transform_event`.
69 #'
70 #' @param excluded_fields A `character` vector of field names to exclude
71 #' from the final output. Applied after `transform_event_names`.
72 initialize = function(
73 toJSON_args = list(auto_unbox = TRUE),
74 timestamp_fmt = NULL,
75 transform_event = function(event) event[["values"]],
76 transform_event_names = NULL,
77 excluded_fields = "rawMsg"
78 ){
79 self$set_toJSON_args(toJSON_args)
80 self$set_timestamp_fmt(timestamp_fmt)
81 self$set_transform_event(transform_event)
82 self$set_transform_event_names(transform_event_names)
83 self$set_excluded_fields(excluded_fields)
84 },
85
86 format_event = function(event) {
87 values <- get(".transform_event", private)(event)
88 values[["timestamp"]] <- apply_timestamp_formatter(values[["timestamp"]], get(".timestamp_fmt", private))
89 names(values) <- apply_event_name_transformer(names(values), get(".transform_event_names", private))
90 values <- apply_field_exclusion(values, self$excluded_fields)
91
92 do.call(
93 jsonlite::toJSON,
94 args = c(list(x = values), get(".toJSON_args", private))
95 )
96 },
97
98 # . . setters -------------------------------------------------------------
99
100 #' @param x a `list`
101 set_toJSON_args = function(x){
102 assert(is.list(x))
103 assert(identical(length(names(x)), length(x)))
104 private$.toJSON_args <- x
105 invisible(self)
106 },
107
108 #' @param x a `character` scalar or a `function` that accepts a `POSIXct`
109 #' as its single argument
110 set_timestamp_fmt = function(x){
111 assert(is.null(x) || is_scalar_character(x) || is.function(x))
112 private[[".timestamp_fmt"]] <- x
113 invisible(self)
114 },
115
116 #' @param x a `function` that accepts a `LogEvent` as its single argument
117 set_transform_event = function(x){
118 assert(
119 is.function(x) && length(formals(x)) >= 1L,
120 "`transform_event` must be a function a single argument (optional arguments are OK)")
121
122 private[[".transform_event"]] <- x
123 invisible(self)
124 },
125
126 #' @param x a named `character` vector or a function that accepts a
127 #' `character` vector of field names as its single argument.
128 set_transform_event_names = function(x){
129 assert(
130 is.null(x) || is_field_name_map(x) || (is.function(x) && length(formals(x)) >= 1L),
131 "`transform_event_names` must be a named character vector or function with a single mandatory argument (optional arguments are OK)")
132
133 private[[".transform_event_names"]] <- x
134 },
135
136 # . . methods ----------------------------------------------------------------
137
138 #' @description Represent the `LayoutJson` class as a string
139 toString = function() {
140 fmt_class(class(self)[[1]])
141 },
142
143 #' @description Read and parse file written using this Layout
144 #'
145 #' This can be used by the `$data` active binding of an [Appender]
146 #'
147 #' @param file `character` scalar: path to a file
148 parse = function(file){
149 read_json_lines(file)
150 },
151
152 #' @description Read a file written using this Layout (without parsing)
153 #'
154 #' This can be used by the `$show()` method of an [Appender]
155 #'
156 #' @param file `character` scalar: path to a file
157 #' @param threshold `character` Minimum log level to show. Requires parsing
158 #' of the log file (but will still display unparsed output)
159 #' @param n `integer` number of lines to show
160 read = function(
161 file,
162 threshold = NA_integer_,
163 n = 20L
164 ){
165 assert(is_scalar_integerish(n))
166 threshold <- standardize_threshold(threshold)
167
168 dd <- readLines(file)
169 if (!is.na(threshold)){
170 sel <- self$parse(file)$level <= threshold
171 } else {
172 sel <- TRUE
173 }
174
175 dd <- tail(dd[sel], n)
176 dd
177 }
178 ),
179
180
181 # . . active fields ------------------------------------------------------
182
183 active = list(
184
185 #' @field toJSON_args a `list`
186 toJSON_args = function() {
187 get(".toJSON_args", private)
188 },
189
190 #' @field timestamp_fmt a `character` scalar or a `function` that accepts a `POSIXct`
191 #' as its single argument
192 timestamp_fmt = function() {
193 get(".timestamp_fmt", private)
194 },
195
196 #' @field transform_event a `function` that accepts a `LogEvent` as its single argument
197 transform_event = function(){
198 get(".transform_event", private)
199 },
200
201 #' @field transform_event_names a named `character` vector or a function that accepts a
202 #' `character` vector of field names as its single argument.
203 transform_event_names = function() {
204 get(".transform_event_names", private)
205 }
206 ),
207
208 # . . private --------------------------------------------------------------
209 private = list(
210 .toJSON_args = NULL,
211 .timestamp_fmt = NULL,
212 .transform_event = NULL,
213 .transform_event_names = NULL
214 )
215 )
216
217
218 # utils -------------------------------------------------------------------
219
220 apply_timestamp_formatter = function(x, f){
221 if (is.null(f)){
222 return(x)
223 }
224
225 if (is.character(f)){
226 return(format(x, f))
227 }
228
229 if (is.function(f)){
230 return(f(x))
231 }
232
233 warning("`f` must be a character scalar or a function")
234 }
235
236
237 apply_event_name_transformer = function(x, f){
238 if (is.null(f)){
239 return(x)
240 }
241
242 if (is.character(f)){
243 rename_idx <- match(x, f, nomatch = 0L)
244 x[rename_idx > 0L] <- names(f)[rename_idx[rename_idx > 0L]]
245 return(x)
246 }
247
248 if(is.function(f)){
249 return(f(x))
250 }
251
252 warning("`f` must be a named character vector or a function")
253 x
254 }
255
256
257 apply_field_exclusion <- function(x, f){
258 if (is.null(f)){
259 return(x)
260 }
261
262 x[!names(x) %in% f]
263 }
264
265
266 is_field_name_map <- function(x){
267 is.character(x) && !is.null(names(x)) && all(nzchar(names(x)))
268 }