Title: Easy-to-Use, Dependencyless Logger
Description: An easy-to-use 'ndjson' (newline-delimited 'JSON') logger. It provides a set of wrappers for base R's message(), warning(), and stop() functions that maintain identical functionality, but also log the handler message to an 'ndjson' log file. No change in existing code is necessary to use this package, and only a few additional adjustments are needed to fully utilize its potential.
Version: 2.4.0
License: MIT + file LICENSE
Depends: R (≥ 4.0)
Suggests: knitr (≥ 1.19), rmarkdown (≥ 1.8), testthat (≥ 3.0), utils
URL: https://github.com/MEO265/loggit2, https://r-loggit.org/
BugReports: https://github.com/MEO265/loggit2/issues
RoxygenNote: 7.3.2
Encoding: UTF-8
VignetteBuilder: knitr
Config/testthat/edition: 3
NeedsCompilation: yes
Packaged: 2025-06-01 18:18:51 UTC; a501562
Author: Matthias Ollech [cre, aut], Ryan Price [fnd, aut]
Maintainer: Matthias Ollech <ollech@gmx.com>
Repository: CRAN
Date/Publication: 2025-06-01 23:20:10 UTC

Convert Call to String

Description

Converts a call object to a string and optionally determines the full call stack.

Usage

call_2_string(call, full_stack = FALSE, default_cutoff = 4L)

Arguments

call

Call object.

full_stack

Include the full call stack?

default_cutoff

Number of calls to cut from the end of the call stack if no matching call is found.

Details

The full call stack can only be determined if the call is in the current context. The default cutoff is 4 because the only known case is an primitive error in with_loggit() which adds 4 calls to the stack.

Value

Deparsed call as string.


Convert Log Level Input to Integer

Description

Convert Log Level Input to Integer

Usage

convert_lvl_input(level)

Arguments

level

Log level as character or numeric.

Value

The log level integer.


Write log to csv file

Description

Creates a csv file from the ndjson log file.

Usage

convert_to_csv(
  file,
  logfile = get_logfile(),
  unsanitize = FALSE,
  last_first = FALSE,
  ...
)

Arguments

file

Path to write csv file to.

logfile

Path to log file to read from.

unsanitize

Should escaped special characters be unescaped?

last_first

Should the last log entry be the first row of the data frame?

...

Additional arguments to pass to utils::write.csv().

Details

Unescaping of special characters can lead to unexpected results. Use unsanitize = TRUE with caution.

Value

Invisible NULL.

Examples

## Not run: 
  convert_to_csv("my_log.csv")

  convert_to_csv("my_log.csv", logfile = "my_log.log", last_first = TRUE)

## End(Not run)


Debug Log Handler

Description

This function works like base R's warning , but is silent, includes logging of the exception message via loggit() and does not allow conditions as input.

Usage

debuginfo(..., call. = TRUE, .loggit = NA, echo = get_echo())

Arguments

...

zero or more objects which can be coerced to character (and which are pasted together with no separator) or a single condition object.

call.

logical, indicating if the call should become part of the warning message.

.loggit

Should the condition message be added to the log? If NA the log level set by set_log_level() is used to determine if the condition should be logged.

echo

Should the log entry (json) be echoed to stdout as well?

Details

This function is more than just a wrapper around loggit() with a log level of "DEBUG". It has the ability to track the call stack and log it if call. is set to TRUE and to automatically translate the input into a message using .makeMessage(), like warning() does.

Value

No return value.

See Also

Other handlers: message(), stop(), stopifnot(), warning()

Examples

## Not run: 
  debuginfo("This is a completely false condition")

  debuginfo("This is a completely false condition", echo = FALSE)

## End(Not run)


Find the Call of a Parent Function in the Call Hierarchy

Description

This function is designed to inspect the call hierarchy and identify the call of a parent function. Any wrapper environments above the global R environment that some IDEs cause are ignored.

Usage

find_call()

Value

Returns the call of the parent function, or NULL if no such call is found.


Get Call Options

Description

Get Call Options

Usage

get_call_options()

Value

The call options.


Get echo

Description

Get echo

Usage

get_echo()

Value

Logical. Are log messages echoed to stdout?


Get file location

Description

Get the file location of a call object.

Usage

get_file_loc(x)

Arguments

x

Call object.

Value

The file location as string.


Get Log Level

Description

Get Log Level

Usage

get_log_level()

Value

The log level.


Get Log File

Description

Return the log file that loggit() will write to by default.

Usage

get_logfile()

Value

The log file path.

Examples

get_logfile()


Get Log Level Integer

Description

Get Log Level Integer

Usage

get_lvl_int(level)

Arguments

level

Log level as character.

Value

The log level integer.


Get Log Level Name

Description

Get Log Level Name

Usage

get_lvl_name(level)

Arguments

level

Log level as integer.

Value

The log level name.


Get package name

Description

Get the package name of a function.

Usage

get_package_name(x)

Arguments

x

Function.

Value

The package location as string.


Get Timestamp Format

Description

Get timestamp format for use in output logs.

Usage

get_timestamp_format()

Value

The timestamp format.

Examples

get_timestamp_format()


Log messages and R objects

Description

Log messages and R objects to a ndjson log file.

Usage

loggit(
  log_lvl,
  log_msg,
  ...,
  echo = get_echo(),
  custom_log_lvl = FALSE,
  logfile = get_logfile(),
  ignore_log_level = FALSE
)

Arguments

log_lvl

Log level. A atomic vector of length one (usually character). Will be coerced to character.

log_msg

Log message. A atomic vector of length one (usually character). Will be coerced to character.

...

Named arguments, each a atomic vector of length one, you wish to log. Will be coerced to character. The names of the arguments are treated as column names in the log.

echo

Should the log entry (json) be echoed to stdout as well?

custom_log_lvl

Allow log levels other than "DEBUG", "INFO", "WARN", and "ERROR"?

logfile

Path of log file to write to.

ignore_log_level

Ignore the log level set by set_log_level()?

Value

Invisible NULL.

Examples

## Not run: 
  loggit("DEBUG", "This is a message")

  loggit("INFO", "This is a message", echo = FALSE)

  loggit("CUSTOM", "This is a message of a custom log_lvl", custom_log_lvl = TRUE)

  loggit(
   "INFO", "This is a message", but_maybe = "you want more fields?",
    sure = "why not?", like = 2, or = 10, what = "ever"
  )

## End(Not run)

Internal logging function for custom log fields

Description

This function is used internally by the loggit function to log messages, levels, and custom fields. Similar to loggit_internal, but with additional custom fields, and checks on those fields.

Usage

loggit_dots(log_lvl, log_msg, ..., echo, logfile = get_logfile())

Arguments

log_lvl

Log level. A atomic vector of length one (usually character). Will be coerced to character.

log_msg

Log message. A atomic vector of length one (usually character). Will be coerced to character.

...

Named arguments, each a atomic vector of length one, you wish to log. Will be coerced to character. The names of the arguments are treated as column names in the log.

echo

Should the log entry (json) be echoed to stdout as well?

logfile

A connection, or a character string naming the file to write to.

Value

Invisible NULL.


Internal logging function

Description

This function is used internally by the loggit function to log messages and levels. No checks are performed on the input, so it should used with caution.

Usage

loggit_internal(
  log_lvl,
  log_msg,
  log_call = NULL,
  echo = get_echo(),
  logfile = get_logfile(),
  call_options = get_call_options()
)

Arguments

log_lvl

Log level. A atomic vector of length one (usually character). Will be coerced to character.

log_msg

Log message. A atomic vector of length one (usually character). Will be coerced to character.

log_call

Call object to log as call leading to the log message.

echo

Should the log entry (json) be echoed to stdout as well?

logfile

A connection, or a character string naming the file to write to.

call_options

List of options regarding logging of call objects. As set by set_call_options().

Value

Invisible NULL.


Message Log Handler

Description

This function is identical to base R's message, but it includes logging of the exception message via loggit().

Usage

message(..., domain = NULL, appendLF = TRUE, .loggit = NA, echo = get_echo())

Arguments

...

zero or more objects which can be coerced to character (and which are pasted together with no separator) or (for message only) a single condition object.

domain

see gettext. If NA, messages will not be translated, see also the note in stop.

appendLF

logical: should messages given as a character string have a newline appended?

.loggit

Should the condition message be added to the log? If NA the log level set by set_log_level() is used to determine if the condition should be logged.

echo

Should the log entry (json) be echoed to stdout as well?

Value

Invisible NULL.

See Also

Other handlers: debuginfo(), stop(), stopifnot(), warning()

Examples

## Not run: 
  message("Don't say such silly things!")

  message("Don't say such silly things!", appendLF = FALSE, echo = FALSE)

## End(Not run)

Get log as data.frame

Description

Returns a data.frame containing all the logs in the provided ndjson log file.

Usage

read_logs(logfile = get_logfile(), unsanitize = TRUE, last_first = FALSE)

Arguments

logfile

Path to log file to read from.

unsanitize

Should escaped special characters be unescaped?

last_first

Should the last log entry be the first row of the data frame?

Details

read_logs() returns a data.frame with the empty character columns "timestamp", "log_lvl" and "log_msg" if the log file has no entries.

Value

A data.frame, with the columns as the fields in the log file.

Examples

## Not run: 
  read_logs()

  read_logs(last_first = TRUE)

## End(Not run)

Read ndJSON-formatted log file

Description

Read ndJSON-formatted log file

Usage

read_ndjson(logfile, unsanitize = TRUE, last_first = FALSE)

Arguments

logfile

Path to log file to read from.

unsanitize

Should escaped special characters be unescaped?

last_first

Should the last log entry be the first row of the data frame?

Value

A data.frame, with the columns as the fields in the log file.


Rotate log file

Description

Truncates the log file to the line count provided as rotate_lines.

Usage

rotate_logs(rotate_lines = 100000L, logfile = get_logfile())

Arguments

rotate_lines

The number of log entries to keep in the logfile.

logfile

Log file to truncate.

Value

Invisible NULL.

Examples

## Not run: 
  rotate_logs()

  rotate_logs(rotate_lines = 0L)

  rotate_logs(rotate_lines = 1000L, logfile = "my_log.log")

## End(Not run)

Sanitization for ndJSON.

Description

Sanitizer and unsanitizer are needed because the ndjson format requires that each line be a valid JSON object, thus special characters must be escaped. The functions worke in such a way that the concatenation unsanitizer(sanitizer()) corresponds to the identity function.

Usage

default_ndjson_sanitizer(string)

default_ndjson_unsanitizer(string)

Arguments

string

A character vector.

Details

The default sanatizer and unsanatizer are based on the following mapping:

Character Replacement
⁠\⁠ ⁠\\⁠
⁠"⁠ ⁠\"⁠
⁠\r⁠ ⁠\\r⁠
⁠\n⁠ ⁠\\n⁠

Value

A character vector.

Examples

## Not run: 
  default_ndjson_sanitizer('This is \n an "example"')
  default_ndjson_unsanitizer('This is \\n an \\"example\\"')

## End(Not run)


Set Call Options

Description

Set Call Options

Usage

set_call_options(..., .arg_list, confirm = TRUE)

Arguments

...

Named arguments to set.

.arg_list

A list of named arguments to set.

confirm

Print confirmation message of call options setting?

Details

Call options are as follows:

Only one of ... or .arg_list can be provided.

Value

Invisible the previous call options.


Set echo

Description

Set echo

Usage

set_echo(echo = TRUE, confirm = TRUE)

Arguments

echo

Should log messages be echoed to stdout?

confirm

Print confirmation message of echo setting?

Value

Invisible the previous echo setting.

Examples

## Not run: 
 set_echo(TRUE)
 set_echo(FALSE)

## End(Not run)


Set Log Level

Description

Set Log Level

Usage

set_log_level(level = "DEBUG", confirm = TRUE)

Arguments

level

Log level to set, as a string or integer.

confirm

Print confirmation message of log level?

Details

Log levels are as follows: DEBUG: 4 INFO: 3 WARNING: 2 ERROR: 1 NONE: 0

Value

Invisible the previous log level.

Examples

## Not run: 
 set_log_level("DEBUG")
 set_log_level("INFO")

 set_log_level(4)
 set_log_level(3)

## End(Not run)


Set Log File

Description

Set the log file that loggit will write to by default.

Usage

set_logfile(logfile = NULL, confirm = TRUE, create = TRUE)

Arguments

logfile

Absolut or relative path to log file. An attempt is made to convert the path into a canonical absolute form using normalizePath(). If NULL will set to ⁠<tmpdir>/loggit.log⁠.

confirm

Print confirmation of log file setting?

create

Create the log file if it does not exist?

Details

No logs outside of a temporary directory will be written until this is set explicitly, as per CRAN policy. Therefore, the default behavior is to create a file named loggit.log in your system's temporary directory.

Value

Invisible the previous log file path.

Examples

## Not run: 
  set_logfile("path/to/logfile.log")

## End(Not run)

Set Timestamp Format

Description

Set timestamp format for use in output logs.

Usage

set_timestamp_format(ts_format = "%Y-%m-%dT%H:%M:%S%z", confirm = TRUE)

Arguments

ts_format

ISO date format.

confirm

Print confirmation message of timestamp format?

Details

This function performs no time format validations, but will echo out the current time in the provided format for manual validation.

This function provides no means of setting a timezone, and instead relies on the host system's time configuration to provide this. This is to enforce consistency across software running on the host.

Value

Invisible the previous timestamp format.

Examples

## Not run: 
  set_timestamp_format("%Y-%m-%d %H:%M:%S")

## End(Not run)


Set up the call options for the application

Description

This function sets the call options for the application.

Usage

setup_call_options()

Value

Invisible the previous call options.


Set up the echo for the application

Description

This function retrieves the echo setting from the environment variable "ECHO_LOGGIT2". If the environment variable is set, it will be used as the echo setting. If the environment variable is not set, the echo setting will be set to the default value.

Usage

setup_echo()

Details

The environment variable must be set to one of: "TRUE" or "FALSE".

Value

Invisible the previous echo setting.


Set up the log level for the application

Description

This function retrieves the log level from the environment variable "LEVEL_LOGGIT2". If the environment variable is set, it will be used as the log level. If the environment variable is not set, the log level will be set to the default value.

Usage

setup_log_level()

Details

The environment variable must be set to one of: "DEBUG", "INFO", "WARN", "ERROR" or "NONE".

Value

Invisible the previous log level.


Set up the logfile for the application

Description

This function retrieves the logfile path from the environment variable "FILE_LOGGIT2". If the environment variable is set, it will be used as the logfile path. If the environment variable is not set, the logfile path will be set to the default value.

Usage

setup_logfile()

Value

Invisible the previous log file path.


Set up the timestamp format for the application

Description

This function retrieves the timestamp format from the environment variable "TIMESTAMP_LOGGIT2". If the environment variable is set, it will be used as the timestamp format. If the environment variable is not set, the timestamp format will be set to the default value.

Usage

setup_timestamp_format()

Value

Invisible the previous timestamp format.


Convert a ndJSON object

Description

Split a vector of JSON strings into a list of R objects.

Usage

split_ndjson(x)

Arguments

x

A vector of JSON strings.

Value

A list with the same length as x, each containing two character vectors: keys and values.

Examples

## Not run: 
  split_ndjson(c('{"a": "1", "b": "2"}', '{"a": "3", "b": "4", "c": "5"}'))

## End(Not run)

Stop Log Handler

Description

This function is identical to base R's stop, but it includes logging of the exception message via loggit().

Usage

stop(..., call. = TRUE, domain = NULL, .loggit = NA, echo = get_echo())

Arguments

...

zero or more objects which can be coerced to character (and which are pasted together with no separator) or a single condition object.

call.

logical, indicating if the call should become part of the error message.

domain

see gettext. If NA, messages will not be translated.

.loggit

Should the condition message be added to the log? If NA the log level set by set_log_level() is used to determine if the condition should be logged.

echo

Should the log entry (json) be echoed to stdout as well?

Value

No return value.

See Also

Other handlers: debuginfo(), message(), stopifnot(), warning()

Examples

## Not run: 
  stop("This is a completely false condition")

  stop("This is a completely false condition", echo = FALSE)

## End(Not run)


Conditional Stop Log Handler

Description

This function is identical to base R's stopifnot, but it includes logging of the exception message via loggit().

Usage

stopifnot(..., exprs, exprObject, local, .loggit = NA, echo = get_echo())

Arguments

..., exprs

any number of R expressions, which should each evaluate to (a logical vector of all) TRUE. Use either ... or exprs, the latter typically an unevaluated expression of the form

{
  expr1
  expr2
  ....
}

Note that e.g., positive numbers are not TRUE, even when they are coerced to TRUE, e.g., inside ⁠if(.)⁠ or in arithmetic computations in R. If names are provided to ..., they will be used in lieu of the default error message.

exprObject

alternative to exprs or ...: an ‘expression-like’ object, typically an expression, but also a call, a name, or atomic constant such as TRUE.

local

(only when exprs is used:) indicates the environment in which the expressions should be evaluated; by default the one from where stopifnot() has been called.

.loggit

Should the condition message be added to the log? If NA the log level set by set_log_level() is used to determine if the condition should be logged.

echo

Should the log entry (json) be echoed to stdout as well?

See Also

Other handlers: debuginfo(), message(), stop(), warning()

Examples

## Not run: 
 stopifnot("This is a completely false condition" = FALSE)

 stopifnot(5L == 5L, "This is a completely false condition" = FALSE, echo = FALSE)

## End(Not run)


Warning Log Handler

Description

This function is identical to base R's warning, but it includes logging of the exception message via loggit().

Usage

warning(
  ...,
  call. = TRUE,
  immediate. = FALSE,
  noBreaks. = FALSE,
  domain = NULL,
  .loggit = NA,
  echo = get_echo()
)

Arguments

...

zero or more objects which can be coerced to character (and which are pasted together with no separator) or a single condition object.

call.

logical, indicating if the call should become part of the warning message.

immediate.

logical, indicating if the call should be output immediately, even if getOption("warn") <= 0.

noBreaks.

logical, indicating as far as possible the message should be output as a single line when options(warn = 1).

domain

see gettext. If NA, messages will not be translated, see also the note in stop.

.loggit

Should the condition message be added to the log? If NA the log level set by set_log_level() is used to determine if the condition should be logged.

echo

Should the log entry (json) be echoed to stdout as well?

Value

The warning message as character string, invisibly.

See Also

Other handlers: debuginfo(), message(), stop(), stopifnot()

Examples

## Not run: 
  warning("You may want to review that math")

  warning("You may want to review that math", immediate = FALSE, echo = FALSE)

## End(Not run)


Log any expressions

Description

Log code without having to explicitly use the loggit2 handlers. This is particularly useful for code that cannot be customized, e.g. from third-party packages.

Usage

with_loggit(
  exp,
  logfile = get_logfile(),
  echo = get_echo(),
  log_level = get_log_level()
)

Arguments

exp

An expression to evaluate.

logfile

Path of log file to write to.

echo

Should the log entry (json) be echoed to stdout as well?

log_level

The log level to use.

Details

If loggit2 handlers are already used in the expression, this can lead to conditions being logged twice (in the same or different files).

Value

The result of the expression.

Examples

## Not run: 
 x <- with_loggit(5L + 5L)

 with_loggit(base::message("Test log message"))

 with_loggit(base::warning("Test log message"), echo = FALSE, logfile = "my_log.log")

 x <- with_loggit({
    y <- 5L
    base::message("Test log message")
    base::warning("Test log message")
    1L + y
 })

## End(Not run)


Write ndJSON-formatted log file

Description

Write ndJSON-formatted log file

Usage

write_ndjson(
  log_df,
  logfile = get_logfile(),
  echo = get_echo(),
  overwrite = FALSE
)

Arguments

log_df

A data.frame. Entries are converted to ndjson, with the columns as the fields.

logfile

A connection, or a character string naming the file to write to.

echo

Should the log entry (json) be echoed to stdout as well?

overwrite

Overwrite previous log file?

Value

Invisible NULL.