tobogganSe connecter

packages

The Louise packages, each released on its own

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

241 lignes · 6229 octetsBrut · Historique
1/// Logging as an effect: an entry has a level, a message and key=value
2/// fields, and the handler decides where it goes and which levels pass.
3///
4/// log.info "webhooks: delivered {n}" []
5/// log.warn "api: refused" [("reason", reason), ("client", address)]
6///
7/// use <- log.to_console Info // in `main`: info and above, timestamped
8/// use <- log.silently // in a test: nothing
9///
10/// A line is `{time} {level} {message}` then ` key=value` per field, for
11/// example `2026-11-05T14:02:11.000Z info GET / 200 8ms client=127.0.0.1`.
12/// A value that is empty or has a space, `"`, `=`, a backslash or a
13/// newline is quoted, and a newline in a message is written `\n`, so an
14/// entry is always one line that splits the same way. Keys are written as
15/// they are: use plain words.
16
17import std/io
18import std/list
19import std/ref.{type Ref, type st}
20import std/string
21import std/time.{type Timestamp, type clock}
22
23/// How much an entry matters, least first: `Debug < Info < Warn < Error`.
24@derive Eq Ord Show Debug
25pub type Level { Debug, Info, Warn, Error }
26
27/// One logged entry.
28@derive Eq Show Debug
29pub type Entry
30{ Entry(level: Level, message: String, fields: List<(String, String)>) }
31
32/// Writing an entry to the log.
33pub effect log
34{
35 fn emit :: level: Level message: String fields: List<(String, String)> -> ()
36}
37
38/// Logs `message` at `Debug`.
39pub fn debug :: message: String fields: List<(String, String)> -> () / <log>
40{
41 emit Debug message fields
42}
43
44/// Logs `message` at `Info`.
45pub fn info :: message: String fields: List<(String, String)> -> () / <log>
46{
47 emit Info message fields
48}
49
50/// Logs `message` at `Warn`.
51pub fn warn :: message: String fields: List<(String, String)> -> () / <log>
52{
53 emit Warn message fields
54}
55
56/// Logs `message` at `Error`.
57pub fn error :: message: String fields: List<(String, String)> -> () / <log>
58{
59 emit Error message fields
60}
61
62/// The level's name, lower case: `"debug"`, `"info"`, `"warn"`, `"error"`.
63pub fn name :: level: Level -> String
64{
65 match level
66 { Debug -> "debug", Info -> "info", Warn -> "warn", Error -> "error" }
67}
68
69/// The level `text` names, in any case and around spaces (`"WARN"`,
70/// `" info"`), for a `LOG_LEVEL` setting; `None` for any other text.
71pub fn level_named :: text: String -> Option<Level>
72{
73 match string.to_lower (string.trim text)
74 { "debug" -> Some(Debug)
75 , "info" -> Some(Info)
76 , "warn" -> Some(Warn)
77 , "error" -> Some(Error)
78 , _ -> None
79 }
80}
81
82// ---- handlers ----------------------------------------------------------------------
83
84/// Runs `action`, writing each entry at `least` or above as a line
85/// stamped with `time.now`: `Warn` and `Error` to stderr, the others to
86/// stdout. Both go through one queue, so they stay in order (ADR 0022).
87pub fn to_console ::
88 least: Level
89 action: fn() -> a / <log, clock, io | e>
90 -> a / <clock, io | e>
91{
92 handle
93 {
94 action ()
95 }
96 with
97 { emit level message fields -> printed least Entry(level, message, fields) }
98}
99
100fn printed :: least: Level entry: Entry -> () / <clock, io>
101{
102 if entry.level < least
103 {
104 ()
105 }
106 else if entry.level < Warn
107 {
108 io.println (line (time.now ()) entry)
109 }
110 else
111 {
112 io.eprintln (line (time.now ()) entry)
113 }
114}
115
116/// Runs `action`, passing each entry at `least` or above to the
117/// enclosing `log` handler and dropping the others.
118pub fn at_least :: least: Level action: fn() -> a / <log | e> -> a / <log | e>
119{
120 handle
121 {
122 action ()
123 }
124 with
125 { emit level message fields -> passed least Entry(level, message, fields) }
126}
127
128fn passed :: least: Level entry: Entry -> () / <log>
129{
130 if entry.level < least
131 {
132 ()
133 }
134 else
135 {
136 emit entry.level entry.message entry.fields
137 }
138}
139
140/// Runs `action`, its entries dropped.
141pub fn silently :: action: fn() -> a / <log | e> -> a / <e>
142{
143 handle
144 {
145 action ()
146 }
147 with
148 { emit _ _ _ -> () }
149}
150
151/// Runs `action`, and answers its result with the entries it logged, in
152/// order (for tests).
153pub fn captured :: action: fn() -> a / <log | e> -> (a, List<Entry>) / <e>
154{
155 region
156 {
157 let entries = ref.new []
158 let result = handle
159 {
160 action ()
161 }
162 with
163 { emit level message fields -> kept entries Entry(level, message, fields) }
164 (result, list.reverse (ref.get entries))
165 }
166}
167
168fn kept :: entries: Ref<h, List<Entry>> entry: Entry -> () / <st<h>>
169{
170 ref.update entries fn earlier { [entry, ..earlier] }
171}
172
173// ---- the line ----------------------------------------------------------------------
174
175/// `entry` as one line, stamped `at`: the RFC 3339 time in milliseconds,
176/// the level padded to five characters, the message, then ` key=value`
177/// per field.
178pub fn line :: at: Timestamp entry: Entry -> String
179{
180 let head = "{stamp at} {padded (name entry.level)} {one_line entry.message}"
181 string.concat [head, ..(list.map entry.fields fn f { " {f.0}={value f.1}" })]
182}
183
184/// `at` in RFC 3339 with exactly three fraction digits, so lines align:
185/// `2026-11-05T14:02:11.000Z`.
186fn stamp :: at: Timestamp -> String
187{
188 let ms = time.unix_ms at
189 let ms_part = ms - floored ms 1000
190 let whole = time.format (time.from_unix_ms (ms - ms_part))
191 let digits = "{ms_part}"
192 "{string.slice whole 0 (string.length whole - 1)}.{string.repeat "0" (3 - string.length digits)}{digits}Z"
193}
194
195/// The greatest multiple of `d` at or below `n`.
196fn floored :: n: Int d: Int -> Int
197{
198 let r = n % d
199 if r < 0
200 {
201 n - r - d
202 }
203 else
204 {
205 n - r
206 }
207}
208
209fn padded :: text: String -> String
210{
211 text <> string.repeat " " (5 - string.length text)
212}
213
214/// A field's value, quoted (backslashes, `"` and newlines escaped) when it
215/// is empty or would not split cleanly on spaces and `=`.
216fn value :: text: String -> String
217{
218 let plain =
219 text != ""
220 && !list.any [" ", "\"", "=", "\n", "\\"] fn c { string.contains text c }
221 if plain
222 {
223 text
224 }
225 else
226 {
227 let inner = replaced (replaced text "\\" "\\\\") "\"" "\\\""
228 "\"{one_line inner}\""
229 }
230}
231
232/// `text` with its newlines written `\n`, so it stays on one line.
233fn one_line :: text: String -> String
234{
235 replaced text "\n" "\\n"
236}
237
238fn replaced :: text: String old: String new: String -> String
239{
240 string.join (string.split text old) new
241}