Debian Codegraph @

R/use_logger.R

raw
1 #' Setup a Simple Logger for a Package
2 #'
3 #' This gives you a minimal logger with no appenders that you can use inside
4 #' your package under the name `lg` (e.g. lg$fatal("test")). `use_logger()`
5 #' does not modify any files but only prints code for you to copy and paste.
6 #'
7 #'
8 #' @param pkg `character` scalar. Name of the package. The default is to try to
9 #' get the Package name automatically using the packages **rprojroot** and
10 #' **desc**
11 #'
12 #' @return a `character` scalar containing \R code.
13 #' @export
14 #'
15 #' @examples
16 #' use_logger("testpkg")
17 #'
18 use_logger <- function(
19 pkg = desc::desc_get("Package", rprojroot::find_package_root_file("DESCRIPTION"))[[1]]
20 ){
21
22 code <- sprintf(
23 '.onLoad <- function(...){
24 assign(
25 "lg",
26 lgr::get_logger("%s"),
27 envir = parent.env(environment())
28 )
29 }', pkg
30 )
31
32
33 msg <- sprintf(
34 "Add the following to any R file in your package (usually '%s-package.R' or 'zzz.R'):",
35 pkg
36 )
37
38 message("\n", msg, "\n")
39 cat(code)
40 invisible(code)
41
42 }
43
44