rfunctionr-glue

Nesting glue function in custom function


I want to create a custom log function, that would get used in other functions. I am having issues with the custom function where arguments don't seem to flow through to the inner log function. My custom log function is inspired by the logger package but I am planning to expand this usage a bit further (so logger doesn't quite meet my needs)

log_fc <- function(type = c("INFO", "ERROR"), ...) {
  
  print(
    glue::glue("[{type} {Sys.time()}] ", ...)
  )
  
}

Next I am planning to use log_fc in various other custom functions, one example:

test_fc <- function(forecast) {

  log_fc(type = "INFO", "{forecast} is here")
  
  #print(forecast)
}

If I test this, I get the following error:

> test_fc(forecast = "d")
 Error in eval(parse(text = text, keep.source = FALSE), envir) : 
object 'forecast' not found

I am not sure why argument forecast is not being picked up by the inner test_fc function. TIA


Solution

  • You could use the .envir argument:

    log_fc <- function(type = c("INFO", "ERROR"), ...) {
      env <- new.env(parent=parent.frame())
      assign("type",type,env)
      print(
        glue::glue("[{type} {Sys.time()}] ", ...,.envir = env)
      )
    }
    
    
      
    test_fc <- function(forecast) {
        
        log_fc(type = "INFO", "{forecast} is here")
        
    }
    
      
    test_fc("My forecast")
    #> [INFO 2022-12-18 12:44:11] My forecast is here