-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructlog.v
More file actions
533 lines (477 loc) · 12.2 KB
/
structlog.v
File metadata and controls
533 lines (477 loc) · 12.2 KB
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
module structlog
import io
import os
import strings
import time
import term
import x.json2 as json
pub interface RecordHandler {
mut:
// handle method must prepare the Record for writing and write it.
handle(rec Record) !
}
pub enum Level {
none // disables all logs.
fatal // disables error, warn, info, debug and trace.
error // disables warn, info, debug and trace.
warn // disables info, debug and trace.
info // disables debug and trace.
debug // disables trace.
trace
}
pub type Value = i8
| i16
| i32
| i64
| int
| isize
| u8
| u16
| u32
| u64
| usize
| f32
| f64
| string
| bool
| []Value
| map[string]Value
// str returns a string representation of Value.
pub fn (v Value) str() string {
return match v {
i8 { v.str() }
i16 { v.str() }
i32 { v.str() }
i64 { v.str() }
int { v.str() }
isize { v.str() }
u8 { v.str() }
u16 { v.str() }
u32 { v.str() }
u64 { v.str() }
usize { v.str() }
f32 { v.str() }
f64 { v.str() }
string { v.str() }
bool { v.str() }
[]Value { v.str() }
map[string]Value { v.str() }
}
}
// Field represents a named field of log record.
pub struct Field {
pub:
name string
value Value
}
// as_map converts array of fields into map.
pub fn (f []Field) as_map() map[string]Value {
mut mapping := map[string]Value{}
for field in f {
mapping[field.name] = field.value
}
return mapping
}
@[noinit]
pub struct Record {
channel chan Record
pub:
level Level
fields []Field
}
// append adds new fields to a record and returns the modified record.
pub fn (r Record) append(field ...Field) Record {
if field.len == 0 {
return r
}
mut fields_orig := unsafe { r.fields }
fields_orig << field
return Record{
...r
fields: &fields_orig
}
}
// prepend adds new fields to the beginning of the record and returns the modified record.
pub fn (r Record) prepend(field ...Field) Record {
if field.len == 0 {
return r
}
mut new_fields := unsafe { field }
new_fields << r.fields
return Record{
...r
fields: new_fields
}
}
// add adds new field with given name and value to a record and returns the modified record.
pub fn (r Record) add(name string, value Value) Record {
return r.append(field(name, value))
}
// field adds new field with given name and value to a record and returns the modified record.
@[deprecated: 'use add() instead']
pub fn (r Record) field(name string, value Value) Record {
return r.append(Field{ name: name, value: value })
}
// message adds new message field to a record and returns the modified record.
// This is a shothand for `add('message', 'message text')`.
pub fn (r Record) message(s string) Record {
return r.add('message', s)
}
// error adds an error as new field to a record and returns the modified record.
// The IError .msg() and .code() methods output will be logged.
pub fn (r Record) error(err IError) Record {
return r.append(Field{
name: 'error'
value: {
'msg': Value(err.msg())
'code': Value(err.code())
}
})
}
// send sends a record to the record handler for the futher processing and writing.
pub fn (r Record) send() {
r.channel <- r
}
pub struct Timestamp {
pub mut:
// format sets the format of datetime in logs. TimestampFormat values
// map 1-to-1 to the date formats provided by `time.Time`.
// If .custom format is selected the `custom` field must be set.
format TimestampFormat = .rfc3339
// custom sets the custom datetime string format if format is set to .custom.
// See docs for Time.format_custom() fn from stadnard `time` module.
custom string
// If local is true the local time will be used instead of UTC.
local bool
}
fn (t Timestamp) as_value() Value {
return timestamp(t.format, t.custom, t.local)
}
pub enum TimestampFormat {
default
rfc3339
rfc3339_micro
rfc3339_nano
ss
ss_micro
ss_milli
ss_nano
unix
unix_micro
unix_milli
unix_nano
custom
}
@[params]
pub struct LogConfig {
pub:
// level holds a logging level for the logger.
// This value cannot be changed after logger initialization.
level Level = .info
// timestamp holds the timestamp settings.
timestamp Timestamp
add_level bool = true // if true add `level` field to all log records.
add_timestamp bool = true // if true add `timestamp` field to all log records.
// handler holds a log record handler object which is used to process logs.
handler RecordHandler = TextHandler{
writer: os.stdout()
}
}
fn timestamp(format TimestampFormat, custom string, local bool) Value {
mut t := time.utc()
if local {
t = t.local()
}
return match format {
.default { t.format() }
.rfc3339 { t.format_rfc3339() }
.rfc3339_micro { t.format_rfc3339_micro() }
.rfc3339_nano { t.format_rfc3339_nano() }
.ss { t.format_ss() }
.ss_micro { t.format_ss_micro() }
.ss_milli { t.format_ss_milli() }
.ss_nano { t.format_ss_nano() }
.unix { t.unix() }
.unix_micro { t.unix_micro() }
.unix_milli { t.unix_milli() }
.unix_nano { t.unix_nano() }
.custom { t.custom_format(custom) }
}
}
// new creates new logger with given config. See LogConfig for defaults.
// This function starts a separate thread for processing and writing logs.
// The calling code MUST wait for this thread to complete to ensure all logs
// are written correctly. To do this, close the logger as shown in the examples.
// Example:
// ```v ignore
// log := structlog.new()
// defer {
// log.close()
// }
// ```
pub fn new(config LogConfig) StructuredLog {
ch := chan Record{cap: 4096}
mut logger := StructuredLog{
LogConfig: config
channel: ch
}
handler_thread := go fn [mut logger] () {
loop: for {
mut rec := <-logger.channel or { break }
if int(rec.level) > int(logger.level) {
continue loop
}
mut extra_fields := []Field{}
if logger.add_timestamp {
extra_fields << Field{
name: 'timestamp'
value: logger.timestamp.as_value()
}
}
if logger.add_level {
extra_fields << Field{
name: 'level'
value: rec.level.str()
}
}
rec = rec.prepend(...extra_fields)
mut handler := logger.handler
handler.handle(rec) or { eprintln('error when handling log record!') }
if rec.level == .fatal {
exit(1)
}
}
}()
logger.handler_thread = handler_thread
return logger
}
@[heap; noinit]
pub struct StructuredLog {
LogConfig
mut:
channel chan Record
handler_thread thread
}
fn (s StructuredLog) record(level Level) Record {
return Record{
channel: s.channel
level: level
}
}
// trace creates new log record with trace level.
pub fn (s StructuredLog) trace() Record {
return s.record(.trace)
}
// debug creates new log record with debug level.
pub fn (s StructuredLog) debug() Record {
return s.record(.debug)
}
// info creates new log record with info level.
pub fn (s StructuredLog) info() Record {
return s.record(.info)
}
// warn creates new log record wth warning level.
pub fn (s StructuredLog) warn() Record {
return s.record(.warn)
}
// error creates new log record with error level.
pub fn (s StructuredLog) error() Record {
return s.record(.error)
}
// fatal creates new log record with fatal level.
// Note: After calling `send()` on record with fatal level the program will
// immediately exit with exit code 1.
pub fn (s StructuredLog) fatal() Record {
return s.record(.fatal)
}
// close closes the internal communication channell (which is used for transfer
// log messages) and waits for record handler thread. It MUST be called for
// normal log processing.
pub fn (s StructuredLog) close() {
s.channel.close()
s.handler_thread.wait()
}
// DefaultHandler is a default empty implementation of RecordHandler interface.
// Its only purpose for existence is to be embedded in a concrete implementation
// of the interface for common struct fields.
pub struct DefaultHandler {
pub mut:
writer io.Writer
}
// handle is the default implementation of handle method of RecordHandler. It does nothing.
pub fn (mut h DefaultHandler) handle(rec Record) ! {}
pub struct JSONHandler {
DefaultHandler
}
// handle converts the log record into json string and writes it into underlying writer.
pub fn (mut h JSONHandler) handle(rec Record) ! {
str := json.encode[map[string]Value](rec.fields.as_map()) + '\n'
h.writer.write(str.bytes())!
if h.writer is os.File {
h.writer.flush()
}
}
pub struct TextHandler {
DefaultHandler
pub:
// If true use colors in log messages. Otherwise disable colors at all.
// Turning on/off color here does not affect any colors that may be contained
// within the log itself i.e. in-string ANSI escape sequences are not processed.
color bool = true
}
// handle builds a log string from given record and writes it into underlying writer.
pub fn (mut h TextHandler) handle(rec Record) ! {
mut buf := strings.new_builder(512)
for i, field in rec.fields {
match field.name {
'timestamp' {
if field.value is string {
buf.write_string(field.value)
} else {
buf.write_string((field.value as i64).str())
}
}
'level' {
mut lvl := ''
if h.color {
lvl = match rec.level {
.trace { term.magenta('TRACE') }
.debug { term.cyan('DEBUG') }
.info { term.white('INFO ') }
.warn { term.yellow('WARN ') }
.error { term.red('ERROR') }
.fatal { term.bg_red('FATAL') }
.none { '' }
}
} else {
lvl = match rec.level {
.trace { 'TRACE' }
.debug { 'DEBUG' }
.info { 'INFO ' }
.warn { 'WARN ' }
.error { 'ERROR' }
.fatal { 'FATAL' }
.none { '' }
}
}
buf.write_byte(`[`)
buf.write_string(lvl)
buf.write_byte(`]`)
}
else {
if field.value is map[string]Value {
mut j := 0
for k, v in field.value {
j++
buf.write_string('${field.name}.${k}')
buf.write_byte(`:`)
buf.write_byte(` `)
buf.write_string(quote(v.str()))
if j != field.value.len {
buf.write_string(', ')
}
}
} else {
buf.write_string(field.name)
buf.write_byte(`:`)
buf.write_byte(` `)
buf.write_string(quote(field.value.str()))
}
}
}
if i + 1 != rec.fields.len {
if i in [0, 1] {
buf.write_byte(` `)
} else {
buf.write_string(', ')
}
}
}
buf.write_byte(`\n`)
h.writer.write(buf)!
if h.writer is os.File {
h.writer.flush()
}
}
@[inline]
fn quote(input string) string {
if !input.contains(' ') {
return input
}
if input.contains("'") {
return '"' + input + '"'
}
return "'" + input + "'"
}
// struct_adapter generates the log fields list form a flat struct.
// Supported struct field attrubutes:
//
// | Attribute | Meaning |
// | ------------------- | ------------------------------------------ |
// | `@[skip]` | Do not process field at all |
// | `@[structlog: '-']` | Do not process field at all |
// | `@[omitempty]` | Do not process field if it has empty value |
//
// Note: Nested struct fields are not supported.
pub fn struct_adapter[T](s T) []Field {
$if T !is $struct {
$compile_error('structlog.struct_adapted: only struct types is accepted')
}
mut fields := []Field{}
mut skip := false
mut omitempty := false
$for f in s.fields {
skip = false
for attr in f.attrs {
if attr == 'skip' || (attr.starts_with('structlog: ')
&& attr.all_after('structlog: ').trim('"\'') == '-') {
skip = true
}
if attr == 'omitempty' {
omitempty = true
}
}
value := s.$(f.name)
if omitempty {
skip = check_is_empty(value) or { false }
}
if !skip {
fields << field(f.name, value)
}
}
return fields
}
fn check_is_empty[T](val T) ?bool {
$if val is string {
if val == '' {
return false
}
} $else $if val is $int || val is $float {
if val == 0 {
return false
}
} $else $if val is ?string {
return val ? != ''
} $else $if val is ?int {
return val ? != 0
} $else $if val is ?f64 || val is ?f32 {
return val ? != 0.0
}
return true
}
// field creates new `Field` with given name and value.
// Map values will be transformed to `map[string]Value`.
pub fn field[T](name string, value T) Field {
$if value is $struct {
$compile_error('structlog.field: cannot pass struct as field value')
}
$if value is $map {
mut value_map := map[string]Value{}
for k, v in value {
value_map[k.str()] = Value(v)
}
return Field{name, value_map}
} $else {
return Field{name, value}
}
}