---
title: "Getting Started"
description: "An introduction to the basic functionality of `loggit2`."
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting Started}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set( #nolint
  collapse = TRUE,
  comment = "#>"
)
old <- options(width = 200L)
```

`loggit2` is an easy-to-use, yet powerful, [`ndjson`](https://github.com/ndjson)
logger. It is very fast, has zero external dependencies, and can be as
straightforward or as integral as you want to make it.

## Preparation
No preparations are needed to use `loggit2`. However, it is recommended to explicitly set a log file using
`loggit2::set_logfile("path/to/your/file")`, as `loggit2` defaults to creating a file in your temporary directory.[^1]

In order to use the full potential of `loggit2`, it is advisable to take a look at the
[further configurations](further_configurations.html) after reading this vignette.

## Logging
There are three ways to populate the log in `loggit2`. First, through wrapper functions of the base `R` condition
handler, second, via the `loggit()` log function, and third, by logging (external) expressions using `with_loggit()`.

Each function of these three methods has the parameter `echo`, which determines whether the log entries should also
be echoed to `stdout`.

### Condition Log Handling

`loggit2` provides a set of wrappings for base R’s `message()`, `warning()`, `stop()` and
`stopifnot()` functions that maintain identical functionality[^2], except the additional logging.
Thus, it is sufficient to import the `loggit2` namespace, for example by using `library("loggit2")`,
or by prefixing `loggit2::` at the desired locations.

```{r, error = TRUE}
base::message("This is another message")
loggit2::message("This is a message")

base::warning("This is another warning")
loggit2::warning("This is a warning")

base::stop("This is another error")
loggit2::stop("This is an error")

base::stopifnot("This is another condition" = FALSE)
loggit2::stopifnot("This is another condition" = FALSE)
```

Besides the `echo` parameter, the functions have an additional parameter `.loggit`, which allows to deactivate
the logging such that the function behaves exactly like the base `R` equivalents.
```{r}
loggit2::warning("This is a alternative warning", echo = FALSE)

loggit2::warning("This is not part of the log", .loggit = FALSE)
```

<details>
<summary>Click here to see the generated log</summary>
```{r, echo = FALSE}
loggit2::read_logs()
loggit2::rotate_logs(0L)
```
</details>

### Explicit Log Function

`loggit2` allows direct access to the core logging function `loggit()`.
This enables setting the log level directly during the call and creating arbitrary fields in the log.

This function does not trigger any conditions; it only populates the log.

```{r}
loggit2::loggit("INFO", "This is a message", ID = 1L, boole = TRUE)

loggit2::loggit("WARN", "This is a alternative warning", echo = FALSE)

loggit2::loggit("DEBUG", "This is a message", Why = "Because", echo = FALSE)
```

To allow log levels other than "DEBUG", "INFO", "WARN" or "ERROR" the `custom_log_lvl` parameter must be set.

```{r, error = TRUE}
loggit2::loggit("CRITICAL", "Critical error")

loggit2::loggit("CRITICAL", "Critical error 2", custom_log_lvl = TRUE)
```

<details>
<summary>Click here to see the generated log</summary>
```{r, echo = FALSE}
loggit2::read_logs()
loggit2::rotate_logs(0L)
```
</details>

### Log Expressions

One will repeatedly encounter situations where conditions need to be logged from code without wanting to or being able
to modify it (e.g., when dealing with functions from external packages).
In this case, `with_loggit()` comes into play. This function allows logging conditions from arbitrary expressions
without restricting functionality[^3] or needing to modify the code.

```{r, error = TRUE}
fun_a <- function(x) {
  base::warning("This is a warning")
  base::message("This is a message")
  base::stopifnot("This is true" = 3L == 1L + 2L, "This is not TRUE" = FALSE)
}

fun_b <- function(x) {
  base::warning("This is a second warning")
  5L + 5L
}
```

```{r, error = TRUE}
x <- loggit2::with_loggit(fun_b())
print(x)
```


```{r, error = TRUE}
loggit2::with_loggit({
  x <- fun_b()
  fun_a()
}, echo = FALSE)
```
Additionally, `with_loggit()` allows alternative settings (logfile, echo, etc.) to be used for a specific section of code.

<details>
<summary>Click here to see the generated log</summary>
```{r, echo = FALSE}
loggit2::read_logs()
```
</details>


## Post-Processing

A log is of little use without the ability to access and modify it. Here are a few possibilities.

### Accessing the Log

As seen above, the log can be queried as a `data.frame` using `read_logs()`.

```{r}
loggit2::read_logs()
```

Alternatively, the log can also be saved as a CSV file using `convert_to_csv()`.

```{r, eval = FALSE}
loggit2::convert_to_csv("path/to/your/file.csv")
```

### Rotating the Log

To maintain a clear log even in long-running sessions (e.g., in a Shiny app hosted on a server),
the log can be restricted to the last `n` entries using `rotate_logs(n)`.

```{r}
loggit2::rotate_logs(2L)
```

<details>
<summary>Click here to see the generated log</summary>
```{r, echo = FALSE}
loggit2::read_logs()
```
</details>

```{r}
loggit2::rotate_logs(0L)
```

<details>
<summary>Click here to see the generated log</summary>
```{r, echo = FALSE}
loggit2::read_logs()
```
</details>


```{r, include = FALSE}
options(old)
```


[^1]: This is done to [CRAN Repository Policy](https://cran.r-project.org/web/packages/policies.html):

    > Packages should not write in the user’s home filespace (including clipboards), nor anywhere else on the file
    > system apart from the R session’s temporary directory `[...]`.

[^2]: This means in particular that `tryCatch` and similar functions can be used as usual.

[^3]: Just like with the direct use of the wrappers for condition handlers, `tryCatch` and similar mechanisms
can be used as usual.
