Skip to contents

Echo expression or a file

Usage

echo(
  expr,
  log = echo_get_log(),
  msg = echo_get_msg(),
  level = echo_get_level(),
  file = NULL,
  exprs = NULL,
  progress = getOption("echo.progress", FALSE)
)

Arguments

expr

Expression to evaluate. This can be a single expression. expressions within braces (i.e., { ... }).

log

A connection or file name for outputs; defaults to stdout()

msg

Logical, if FALSE does not output a message; defaults to TRUE

level

Sets the echo level (see details); defaults to 0L

file

File path to evaluate (like base::source()). If file is not NULL, then expr must be missing`

exprs

Expressions to evaluate. This can be a single expression.

progress

Logical, if TRUE shows a progress bar; defaults to FALSE

Value

Nothing, called for side-effects

Details

Levels of output can be controlled with level:

0

EXP: logs expressions that were evaluated

1

OUT: logs outputs from expressions

2

MSG: logs messages

3

WRN: logs warnings

4

ERR: logs errors

When set, all outputs at the level or below are run. Errors are always logged as they will interrupt and stop the program.

Timestamps are printed in UTC by default. To control this, set the option value, such as options(echo.timezone = "EST").

Examples

# make sure to use braces for expr
echo({ letters }, level = 0) # good
#> [2025-01-01 00:12:31] [EXP] letters
echo({letters}, level = 0)   # still good
#> [2025-01-01 00:12:31] [EXP] letters
echo(letters, level = 0)     # also good
#> [2025-01-01 00:12:31] [EXP] letters

try(echo(
  expr = {
    print(1 + 1)
    Sys.sleep(2)
    head(mtcars)
    message(1)
    warning(2)
    stop(3)
  },
  level = 0
))
#> [2025-01-01 00:12:31] [EXP] print(1 + 1)
#> [2025-01-01 00:12:31] [OUT] #> [1] 2
#> [2025-01-01 00:12:31] [EXP] Sys.sleep(2)
#> [2025-01-01 00:12:33] [EXP] head(mtcars)
#> [2025-01-01 00:12:33] [EXP] message(1)
#> [2025-01-01 00:12:33] [MSG] #> 1
#> [2025-01-01 00:12:33] [EXP] warning(2)
#> [2025-01-01 00:12:33] [WRN] #> 2
#> [2025-01-01 00:12:33] [EXP] stop(3)
#> [2025-01-01 00:12:33] [ERR] #> 3
#> Error : Error in stop(3)
#>   3

# Parse lines in a file instead
try(echo(file = system.file("example-script.R", package = "echo")))
#> [2025-01-01 00:12:35] [MSG] #> 1
#> [2025-01-01 00:12:35] [WRN] #> 2
#> [2025-01-01 00:12:35] [ERR] #> 3
#> Error : Error in stop(3)
#>   3

# Note that
x <- c("example for", "writing lines")
echo({
  x
  print(x)
  writeLines(x)
}, level = 0)
#> [2025-01-01 00:12:35] [EXP] x
#> [2025-01-01 00:12:35] [ERR] #> object 'x' not found
#> Error: Error in x
#>   object 'x' not found