Provides a flexible logging system with support for multiple output destinations, customisable formatting, and contextual logging. Features include:
* Multiple log levels (ERROR, WARNING, INFO) * File-based logging * Database logging support * Customisable message formatting * Contextual data attachment * Coloured console output
Methods
Method new()
Create a new Stenographer instance
Usage
Stenographer$new(
level = LogLevel$INFO,
file_path = NULL,
db_conn = NULL,
table_name = "LOGS",
print_fn = function(x) cat(x, "\n"),
format_fn = function(level, msg) msg,
context = list()
)
Arguments
level
The minimum log level to output. Default is LogLevel$INFO.
file_path
Character; the path to a file to save log entries to. Default is NULL.
db_conn
DBI connection object; an existing database connection. Default is NULL.
table_name
Character; the name of the table to log to in the database. Default is "LOGS".
print_fn
Function; custom print function to use for console output. Should accept a single character string as input. Default uses cat with a newline.
format_fn
Function; custom format function to modify the log message. Should accept level and msg as inputs and return a formatted string.
context
List; initial context for the logger. Default is an empty list.
Examples
# Create a basic Stenographer
steno <- Stenographer$new()
steno$info("This is an info message")
#> 2025-01-16T21:44:42.988Z INFO This is an info message
steno$warn("This is a warning")
#> 2025-01-16T21:44:42.989Z WARNING This is a warning
steno$error("This is an error")
#> 2025-01-16T21:44:43.014Z ERROR This is an error
# Disable all logging
steno$set_level(LogLevel$OFF)
steno$info("This won't be logged")
steno$warn("This won't be logged either")
steno$error("This also won't be logged")
# Create a logger with custom settings, message formatting, and context
custom_steno <- Stenographer$new(
level = LogLevel$WARNING,
file_path = tempfile("log_"),
print_fn = function(x) message(paste0("Custom: ", x)),
format_fn = function(level, msg) paste0("Hello prefix: ", msg),
context = list(program = "MyApp")
)
custom_steno$info("This won't be logged")
custom_steno$warn("This will be logged with a custom prefix")
#> Custom: 2025-01-16T21:44:43.019Z WARNING Hello prefix: This will be logged with a custom prefix
#> Context:
#> {
#> "program": "MyApp"
#> }
# Change log level and update context
custom_steno$set_level(LogLevel$INFO)
custom_steno$update_context(list(user = "John"))
custom_steno$info("Now this will be logged with a custom prefix and context")
#> Custom: 2025-01-16T21:44:43.023Z INFO Hello prefix: Now this will be logged with a custom prefix and context
#> Context:
#> {
#> "program": "MyApp",
#> "user": "John"
#> }