-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.Rmd
211 lines (159 loc) · 5.36 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
---
output: github_document
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
<!-- README.md is generated from README.Rmd. Please edit that file -->
<!-- <img src="./.graphics/512-20240803_logger-logo.png" align="right" height="140" /> -->
# Logger <a href="https://dereckmezquita.github.io/R-Logger"></a>
<!-- badges: start -->
[![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental)
[![Travis build status](https://travis-ci.org/dereckmezquita/kucoin.svg?branch=master)](https://travis-ci.org/dereckmezquita/kucoin)
<!-- badges: end -->
Logger is a flexible and powerful logging system for R applications. It provides a `Logger` class for creating customisable loggers, as well as helper functions for debugging and error reporting.
The latest version includes support for `SQLite` database logging and context management.
## Installation
You can install Logger from [GitHub](https://github.com/) with:
```{r, eval = FALSE}
# install.packages("remotes")
remotes::install_github("derecksprojects/R-Logger")
```
## Basic Usage
Here's a quick example of how to use Logger:
```{r example}
box::use(Logger[Logger, LogLevel])
# Create a basic logger
log <- Logger$new()
# Log some messages
log$info("This is an informational message")
log$warn("This is a warning")
log$error("This is an error")
```
## Features
### Customisable Logging
You can customise the logger by specifying the minimum log level, output file, and custom print function:
```{r}
log_file <- tempfile("app_log")
custom_log <- Logger$new(
level = LogLevel$WARNING,
file_path = log_file,
print_fn = message
)
custom_log$info("This won't be logged")
custom_log$warn("This will be logged to console and file")
custom_log$error("This is an error message", error = "Some error")
```
Logs are written to the specified file as JSON objects:
```{r}
cat(readLines(log_file), sep = "\n")
```
### Database Logging
Logger now supports logging to a SQLite database and context management so you can easily track application events. The context is useful for filtering and querying logs based on specific criteria from `SQLite`:
```{r}
box::use(RSQLite[ SQLite ])
box::use(DBI[ dbConnect, dbDisconnect, dbGetQuery ])
# Create a database connection
db <- dbConnect(SQLite(), "log.sqlite")
# Create a logger that logs to the database
db_log <- Logger$new(
context = list(app_name = "MyApp", fun = "main"),
db_conn = db,
table_name = "app_logs"
)
# Log some messages
db_log$info("This is logged to the database")
db_log$warn("This is a warning", data = list(code = 101))
db_log$error("An error occurred", error = "Division by zero")
# Example of querying the logs
query <- "SELECT * FROM app_logs WHERE level = 'ERROR'"
result <- dbGetQuery(db, query)
print(result)
# Don't forget to close the database connection when you're done
dbDisconnect(db)
```
### Helper Functions
Logger includes helper functions like `valueCoordinates` and `tableToString` to provide detailed context in log messages:
```{r}
box::use(Logger[valueCoordinates, tableToString])
# Create a sample dataset with some issues
df <- data.frame(
a = c(1, NA, 3, 4, 5),
b = c(2, 4, NA, 8, 10),
c = c(3, 6, 9, NA, 15)
)
# Find coordinates of NA values
na_coords <- valueCoordinates(df)
if (nrow(na_coords) > 0) {
log$warn(
"NA values found in the dataset",
data = list(
na_locations = na_coords,
dataset_preview = tableToString(df)
)
)
}
```
### Error Logging with Context
Logger makes it easy to log errors with context:
```{r, error = TRUE}
process_data <- function(df) {
tryCatch({
result <- df$a / df$b
if (any(is.infinite(result))) {
inf_coords <- valueCoordinates(data.frame(result), Inf)
log$error(
"Division by zero occurred",
data = list(
infinite_values = inf_coords,
dataset_preview = tableToString(df)
)
)
stop("Division by zero error")
}
return(result)
}, error = function(e) {
log$error(
paste("An error occurred while processing data:", e$message),
data = list(dataset_preview = tableToString(df)),
error = e
)
stop(e)
})
}
# Test the function with problematic data
df <- data.frame(a = c(1, 2, 3), b = c(0, 2, 0))
process_data(df)
```
### Parallel Processing Support
Logger provides support for logging in parallel environments:
```{r}
box::use(future)
box::use(future.apply[future_lapply])
box::use(Logger[messageParallel])
log <- Logger$new(print_fn = messageParallel)
future::plan(future::multisession, workers = 2)
result <- future_lapply(1:5, function(i) {
messageParallel(sprintf("Processing item %d", i))
if (i == 3) {
log$warn(sprintf("Warning for item %d", i))
}
return(i * 2)
})
future::plan(future::sequential)
```
```
#> Processing item 1
#> Processing item 2
#> Processing item 3
#> 2024-08-03T11:18:03.091Z WARNING Warning for item 3
#> Processing item 4
#> Processing item 5
```
## Contributing
Contributions to Logger are welcome! Please refer to the [CONTRIBUTING.md](CONTRIBUTING.md) file for guidelines.
## License
Logger is released under the MIT License. See the [LICENSE](LICENSE) file for details.