lg_new_logger <- function() {
  lg <- lgr::LoggerGlue$new("nc-campaign-finance")
  if (!interactive()) {
    lg$add_appender(
      lgr::AppenderFile$new(here::here("nc-campaign-finance.log")),
      name = "file"
    )
    lg$set_threshold("info")
  }
  lg
}

lg_get_logger <- function() {
  if (is.null(.globals$logger)) {
    .globals$logger <- lg_new_logger()
  }

  .globals$logger
}

lg_inject_target_name <- function(lg = .globals$logger) {
  target_name <- targets::tar_name()
  if (target_name == "target") return()
  lg$add_filter(lgr::FilterInject$new(target = target_name), name = "target_name")
  withr::defer_parent(lg$remove_filter("target_name"))
  invisible(lg)
}

lg_info_target <- function(lg = .globals$logger) {
  target_name <- targets::tar_name()
  if (target_name == "target") return()

  lg$info("------ start: {target_name} ------")
  withr::defer_parent({
    lg$info("------ done: {target_name} ------")
  })

  invisible(lg)
}
