-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
760 lines (604 loc) · 22.1 KB
/
example_test.go
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
// Copyright 2021 The sypl Authors. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
//
//nolint:exhaustruct
package sypl_test
import (
"errors"
"fmt"
"os"
"strings"
"github.com/thalesfsp/sypl"
"github.com/thalesfsp/sypl/fields"
"github.com/thalesfsp/sypl/flag"
"github.com/thalesfsp/sypl/formatter"
"github.com/thalesfsp/sypl/level"
"github.com/thalesfsp/sypl/message"
"github.com/thalesfsp/sypl/options"
"github.com/thalesfsp/sypl/output"
"github.com/thalesfsp/sypl/processor"
"github.com/thalesfsp/sypl/safebuffer"
"github.com/thalesfsp/sypl/shared"
"github.com/thalesfsp/sypl/status"
)
//////
// Helpers
//////
// Checks if `src` has `texts`. If not, it prints a message.
//
//nolint:forbidigo
func stringContains(src string, texts ...string) bool {
contains := true
for _, text := range texts {
if !strings.Contains(src, text) {
contains = false
fmt.Printf("Expected %s to contain %s\n", src, text)
}
}
return contains
}
//////
// Examples.
//////
// NonChained is a non-chained example of creating, and setting up a `sypl`
// logger. It writes to a custom buffer.
func ExampleNew_notChained() {
buf := new(strings.Builder)
// Creates logger, and name it.
testingLogger := sypl.New("Testing Logger")
// Creates an `Output`. In this case, called "Console" that will print to
// `stdout` and max print level @ `Info`.
ConsoleToStdOut := output.New("Console", level.Info, buf)
// Creates a `Processor`. It will prefix all messages.
Prefixer := func(prefix string) processor.IProcessor {
return processor.New("Prefixer", func(message message.IMessage) error {
message.GetContent().SetProcessed(prefix + message.GetContent().GetProcessed())
return nil
})
}
// Adds `Processor` to `Output`.
ConsoleToStdOut.AddProcessors(Prefixer(shared.DefaultPrefixValue))
// Adds `Output` to logger.
testingLogger.AddOutputs(ConsoleToStdOut)
// Writes: "My Prefix - Test message"
testingLogger.Print(level.Info, "Test info message")
fmt.Println(buf.String())
// Output:
// My Prefix - Test info message
}
// Chained is the chained example of creating, and setting up a `sypl` logger.
// It writes to both `stdout` and `stderr`.
func ExampleNew_chained() {
// Creates logger, and name it.
sypl.New("Testing Logger").
// Creates a `Processor`. It will prefix all messages. It will only
// prefix messages for this specific `Output`, and @ `Error` level.
AddOutputs(output.New("Error", level.Error, os.Stdout).
AddProcessors(func(prefix string) processor.IProcessor {
return processor.New("Prefixer", func(message message.IMessage) error {
if message.GetLevel() == level.Error {
message.GetContent().SetProcessed(prefix + message.GetContent().GetProcessed())
}
return nil
})
}(shared.DefaultPrefixValue))).
// Prints:
// My Prefix - Test error message
Println(level.Error, "Test error message")
// Output:
// My Prefix - Test error message
}
// ChainedUsingBuiltin is the chained example of creating, and setting up a
// `sypl` logger using built-in `Output`, and `Processor`. It writes to
// `stdout`, and `stderr`.
func ExampleNew_chainedUsingBuiltin() {
// Creates logger, and name it.
sypl.New("Testing Logger").
// Adds an `Output`. In this case, called "Console" that will print to
// `stdout` and max print level @ `Info`.
//
// Adds a `Processor`. It will prefix all messages.
AddOutputs(output.Console(level.Info).AddProcessors(processor.Prefixer(shared.DefaultPrefixValue))).
// Prints: My Prefix - Test info message
Infoln("Test info message")
// output:
// My Prefix - Test info message
}
// inlineUsingBuiltin same as `ChainedUsingBuiltin` but using inline form.
func ExampleNew_inlineUsingBuiltin() {
sypl.New("Testing Logger", output.Console(level.Info).
AddProcessors(processor.Prefixer(shared.DefaultPrefixValue))).
Infoln("Test info message")
// output:
// My Prefix - Test info message
}
// printWithOptions demonstrates `sypl` flexibility. `Options` enhances the
// usual `PrintX` methods allowing to specify flags, and tags.
func ExampleNew_printWithOptions() {
// Creates logger, and name it.
testingLogger := sypl.New("Testing Logger")
// Creates 3 `Output`s, all called "Console" that will print to `stdout`, and
// max print level @ `Info`.
var c1buf safebuffer.Buffer
Console1ToStdOut := output.New("Buffer 1", level.Info, &c1buf)
var c2buf safebuffer.Buffer
Console2ToStdOut := output.New("Buffer 2", level.Info, &c2buf)
var c3buf safebuffer.Buffer
Console3ToStdOut := output.New("Buffer 3", level.Info, &c3buf)
// Creates a `Processor`. It will `prefix` all messages with the Output, and
// Processor names.
Prefixer := func() processor.IProcessor {
return processor.New("Prefixer", func(message message.IMessage) error {
prefix := fmt.Sprintf("Output: %s Processor: %s Content: ",
message.GetOutputName(),
message.GetProcessorName(),
)
message.GetContent().SetProcessed(prefix + message.GetContent().GetProcessed())
return nil
})
}
// Creates a `Processor`. It will `suffix` all messages with the specified
// `tag`.
SuffixBasedOnTag := func(tag string) processor.IProcessor {
return processor.New("SuffixBasedOnTag", func(message message.IMessage) error {
if message.ContainTag(tag) {
message.GetContent().SetProcessed(message.GetContent().GetProcessed() + " - My Suffix")
}
return nil
})
}
// Adds `Processor`s to `Output`s.
Console1ToStdOut.AddProcessors(Prefixer(), SuffixBasedOnTag("SuffixIt"))
Console2ToStdOut.AddProcessors(Prefixer(), SuffixBasedOnTag("SuffixIt"))
Console3ToStdOut.AddProcessors(Prefixer(), SuffixBasedOnTag("SuffixIt"))
// Adds all `Output`s to logger.
testingLogger.AddOutputs(Console1ToStdOut, Console2ToStdOut, Console3ToStdOut)
// Prints with prefix, without suffix.
testingLogger.Print(level.Info, shared.DefaultContentOutput)
fmt.Println(strings.EqualFold(c1buf.String(), "Output: Buffer 1 Processor: Prefixer Content: contentTest"))
fmt.Println(strings.EqualFold(c2buf.String(), "Output: Buffer 2 Processor: Prefixer Content: contentTest"))
fmt.Println(strings.EqualFold(c3buf.String(), "Output: Buffer 3 Processor: Prefixer Content: contentTest"))
c1buf.Reset()
c2buf.Reset()
c3buf.Reset()
// Prints with prefix, and suffix.
testingLogger.PrintWithOptions(
level.Info,
shared.DefaultContentOutput,
sypl.WithOutputsNames("Buffer 1"),
sypl.WithProcessorsNames("Prefixer", "SuffixBasedOnTag"),
sypl.WithTags("SuffixIt"),
)
fmt.Println(strings.EqualFold(c1buf.String(), "Output: Buffer 1 Processor: Prefixer Content: contentTest - My Suffix"))
// output:
// true
// true
// true
// true
}
// PrintPretty example.
func ExampleNew_printPretty() {
type TestType struct {
Key1 string
Key2 int
}
sypl.New("Testing Logger", output.Console(level.Info)).PrintPretty(level.Info, &TestType{
Key1: "text",
Key2: 12,
})
// output:
// {
// "Key1": "text",
// "Key2": 12
// }
}
// Flags example.
func ExampleNew_flags() {
// Creates logger, and name it.
sypl.New("Testing Logger", output.Console(level.Info, processor.Prefixer(shared.DefaultPrefixValue))).
// Message will be processed, and printed independent of `Level`
// restrictions.
PrintlnWithOptions(level.Debug, shared.DefaultContentOutput, sypl.WithFlag(flag.Force)).
// Message will be processed, but not printed.
PrintlnWithOptions(level.Info, shared.DefaultContentOutput, sypl.WithFlag(flag.Mute)).
// Message will not be processed, but printed.
PrintlnWithOptions(level.Info, shared.DefaultContentOutput, sypl.WithFlag(flag.Skip)).
// Should not print - restricted by level.
Debugln(shared.DefaultContentOutput).
// SkipAndForce message will not be processed, but will be printed
// independent of `Level` restrictions.
PrintlnWithOptions(level.Debug, shared.DefaultContentOutput, sypl.WithFlag(flag.SkipAndForce)).
// Message will not be processed, neither printed.
PrintlnWithOptions(level.Debug, shared.DefaultContentOutput, sypl.WithFlag(flag.SkipAndMute))
// output:
// My Prefix - contentTest
// contentTest
// contentTest
}
// Serror{f|lnf|ln} example.
//
//nolint:goerr113
func ExampleNew_serrorX() {
// Creates logger, and name it.
testingLogger := sypl.New("Testing Logger", output.Console(level.Info))
sErrorResult := testingLogger.Serror(shared.DefaultContentOutput)
errExample := errors.New("Failed to reach something")
sErrorfResult := testingLogger.Serrorf("Failed to do something, %s", errExample)
sErrorlnfResult := testingLogger.Serrorlnf("Failed to do something, %s", errExample)
sErrorlnResult := testingLogger.Serrorln(shared.DefaultContentOutput)
fmt.Print(
sErrorResult.Error() == shared.DefaultContentOutput,
sErrorfResult.Error() == "Failed to do something, Failed to reach something",
sErrorlnfResult.Error() == "Failed to do something, Failed to reach something"+"\n",
sErrorlnResult.Error() == shared.DefaultContentOutput+"\n",
)
// output:
// contentTestFailed to do something, Failed to reach somethingFailed to do something, Failed to reach something
// contentTest
// true true true true
}
// Text formatter example.
func ExampleNew_textFormatter() {
buf, o := output.SafeBuffer(level.Info)
o.SetFormatter(formatter.Text())
// Creates logger, and name it.
sypl.New(shared.DefaultComponentNameOutput).
AddOutputs(o).
PrintlnWithOptions(
level.Info,
shared.DefaultContentOutput,
sypl.WithFields(fields.Fields{
"field1": "value1",
"field2": "value2",
"field3": "value3",
}),
)
s := buf.String()
fmt.Print(
strings.Contains(s, shared.DefaultContentOutput),
strings.Contains(s, "field1=value1"),
strings.Contains(s, "field2=value2"),
strings.Contains(s, "field3=value3"),
strings.Contains(s, "component="),
strings.Contains(s, "level="),
strings.Contains(s, "timestamp="),
)
// Prints:
//
// component=componentNameTest level=info field1=value1 field2=value2 field3=value3 timestamp=2021-08-10T22:50:36-07:00
// output:
// true true true true true true true
}
// JSON formatter example.
func ExampleNew_jsonFormatter() {
buf, o := output.SafeBuffer(level.Info)
o.SetFormatter(formatter.JSONPretty())
// Creates logger, and name it.
sypl.New(shared.DefaultComponentNameOutput).
AddOutputs(o).
PrintWithOptions(
level.Info,
shared.DefaultContentOutput,
sypl.WithFields(fields.Fields{
"field1": "value1",
"field2": 1,
"field3": true,
"field4": []string{"1", "2"},
}),
)
s := buf.String()
fmt.Print(
strings.Contains(s, `"component"`),
strings.Contains(s, `"message"`),
strings.Contains(s, `"field1"`),
strings.Contains(s, `"field2"`),
strings.Contains(s, `"field3"`),
strings.Contains(s, `"field4"`),
strings.Contains(s, `"level"`),
strings.Contains(s, `"timestamp"`),
)
// Prints:
//
// {
// "component": "componentNameTest",
// "content": "contentTest",
// "field1": "value1",
// "field2": 1,
// "field3": true,
// "field4": [
// "1",
// "2"
// ],
// "level": "info",
// "timestamp": "2021-08-10T23:27:25-07:00"
// }
// output:
// true true true true true true true true
}
// Simulates a problematic processor.
func ExampleNew_errorSimulator() {
// Creates logger, and name it.
sypl.New(shared.DefaultComponentNameOutput).
AddOutputs(output.Console(level.Info, processor.ErrorSimulator("Test"))).
Infoln(shared.DefaultContentOutput)
// Prints:
//
// 2021/08/10 20:00:56 [sypl] [Error] Output: "Console" Processor: "ErrorSimulator" Error: "Test" Original Message: "contentTest"
}
// Child loggers example.
func ExampleNew_childLoggers() {
// Creates logger, and name it.
k8Logger := sypl.New("k8").
AddOutputs(output.Console(level.Info).SetFormatter(formatter.Text()))
k8Logger.Infoln("k8 connected")
podLogger := k8Logger.New("pod")
podLogger.Infoln("pod created")
k8Logger.GetOutput("Console").SetStatus(status.Disabled)
k8Logger.Infoln("k8 connected")
podLogger.Infoln("pod created")
// Prints:
//
// k8 connected component=k8 level=info timestamp=2021-08-11T09:24:13-07:00
// pod created component=pod level=info timestamp=2021-08-11T09:24:13-07:00
}
// PrintMessagesToOutputs example.
func ExampleNew_printMessagesToOutputs() {
// Creates logger, and name it.
sypl.New("pod").AddOutputs(
output.New("Console 1", level.Trace, os.Stdout).SetFormatter(formatter.Text()),
output.New("Console 2", level.Trace, os.Stdout).SetFormatter(formatter.Text()),
output.New("Console 3", level.Trace, os.Stdout).SetFormatter(formatter.Text()),
).PrintMessagesToOutputs(
sypl.MessageToOutput{OutputName: "Console 1", Level: level.Info, Content: "Test 1\n"},
sypl.MessageToOutput{OutputName: "Console 1", Level: level.Debug, Content: "Test 2\n"},
sypl.MessageToOutput{OutputName: "Console 2", Level: level.Info, Content: "Test 3\n"},
sypl.MessageToOutput{OutputName: "Console 4", Level: level.Info, Content: "Test 4\n"},
)
// Prints:
//
// output=Console 2 level=Info message=Test 3
// output=Console 1 level=Debug message=Test 2
// output=Console 1 level=Info message=Test 1
}
// StdErr output example.
func ExampleNew_stdErrOutputExample() {
// Creates logger, and name it.
sypl.New(shared.DefaultComponentNameOutput, output.StdErr()).
Infoln(shared.DefaultContentOutput).
Errorln(shared.DefaultContentOutput)
// Prints:
//
// contentTest
}
// NewDefault output example.
func ExampleNew_newDefault() {
// Creates logger, and name it.
sypl.NewDefault(shared.DefaultComponentNameOutput, level.Trace).
Infoln(shared.DefaultContentOutput).
Errorln("error message")
// Prints:
//
// component=componentNameTest output=console level=info timestamp=2021-08-17T19:10:00-07:00 message=contentTest
// component=componentNameTest output=console level=error timestamp=2021-08-17T19:10:00-07:00 message=error message
}
// PrintOnlyIfTagged output example.
func ExampleNew_printOnlyIfTagged() {
// Creates logger, and name it.
sypl.NewDefault(shared.DefaultComponentNameOutput, level.Trace, processor.PrintOnlyIfTagged("testTag")).
Infoln(shared.DefaultContentOutput).
PrintlnWithOptions(
level.Info,
shared.DefaultContentOutput,
sypl.WithTags("testTag"),
)
// Prints:
//
// component=componentNameTest output=console level=info timestamp=2021-08-17T19:19:57-07:00 message=contentTest
}
// Updating outputs' max levels example.
func ExampleNew_updateOutputsMaxLevel() {
// Creates logger, and name it.
l := sypl.New(shared.DefaultComponentNameOutput).AddOutputs(
output.New("Console 1", level.Info, os.Stdout),
output.New("Console 2", level.Debug, os.Stdout),
output.New("Console 3", level.Trace, os.Stdout),
)
l.PrintlnWithOptions(
level.Info,
fmt.Sprint(l.GetMaxLevel()),
sypl.WithOutputsNames("Console 1"),
)
l.SetMaxLevel(level.Info)
l.PrintlnWithOptions(
level.Info,
fmt.Sprint(l.GetMaxLevel()),
sypl.WithOutputsNames("Console 1"),
)
// output:
// map[Console 1:info Console 2:debug Console 3:trace]
// map[Console 1:info Console 2:info Console 3:info]
}
// PrintMessagesToOutputsWithOptions example.
func ExampleNew_printMessagesToOutputsWithOptions() {
// Creates logger, and name it.
l := sypl.New(shared.DefaultComponentNameOutput).AddOutputs(
output.New("Console 1", level.Trace, os.Stdout).SetFormatter(formatter.Text()),
output.New("Console 2", level.Trace, os.Stdout).SetFormatter(formatter.Text()),
)
l.PrintMessagesToOutputsWithOptions(&options.Options{
Fields: fields.Fields{"1": 2},
},
sypl.MessageToOutput{Content: fmt.Sprintln(shared.DefaultContentOutput), Level: level.Info, OutputName: "Console 1"},
sypl.MessageToOutput{Content: fmt.Sprintln(shared.DefaultContentOutput), Level: level.Warn, OutputName: "Console 2"},
)
// Prints:
//
// component=componentNameTest output=console 2 level=warn timestamp=2021-08-19T11:48:34-07:00 message=contentTest 1=2
// component=componentNameTest output=console 1 level=info timestamp=2021-08-19T11:48:34-07:00 message=contentTest 1=2
}
// PrintNewLine example.
func ExampleNew_printNewLine() {
// Creates logger, and name it.
l := sypl.New(shared.DefaultComponentNameOutput, output.Console(level.Info))
l.Infoln(shared.DefaultContentOutput)
l.PrintNewLine()
l.Infoln(shared.DefaultContentOutput)
// output:
// contentTest
//
// contentTest
}
// Global fields example.
func ExampleNew_globalFields() {
buf, o := output.SafeBuffer(level.Info)
// Creates logger, and name it.
l := sypl.New(shared.DefaultComponentNameOutput, o.SetFormatter(formatter.Text()))
l.SetFields(fields.Fields{"a": 1})
l.Infoln(shared.DefaultContentOutput) // a=1
l.PrintWithOptions(level.Info, shared.DefaultContentOutput,
sypl.WithFields(fields.Fields{"a": 2, "b": 3}))
l.Infoln(shared.DefaultContentOutput) // a=1
fmt.Println(stringContains(buf.String(), "contentTest", "a=1", "a=2", "b=3"))
// output:
// true
}
// Global tags example.
func ExampleNew_globalTags() {
buf, o := output.SafeBuffer(level.Info)
// Creates logger, and name it.
l := sypl.New(shared.DefaultComponentNameOutput, o.SetFormatter(formatter.JSONPretty()))
l.SetTags("a", "b")
l.Infoln(shared.DefaultContentOutput) // a=1
l.PrintWithOptions(level.Info, shared.DefaultContentOutput,
sypl.WithTags("a", "c"))
l.Infoln(shared.DefaultContentOutput) // a=1
fmt.Println(stringContains(buf.String(), "contentTest", "tags", "a", "b", "c"))
// output:
// true
}
// Global tags example - non-duplicated tags.
func ExampleNew_globalTagsNonDup() {
buf, o := output.SafeBuffer(level.Info)
// Creates logger, and name it.
l := sypl.New(shared.DefaultComponentNameOutput, o.SetFormatter(formatter.JSONPretty()))
l.SetTags("a", "b")
l.PrintWithOptions(level.Info, shared.DefaultContentOutput,
sypl.WithTags("a", "a", "c"))
bufStr := buf.String()
fmt.Println(strings.Count(bufStr, "\"a\""), stringContains(bufStr, "contentTest", "tags", "a", "b", "c"))
// output:
// 1 true
}
// Logging filtering, and debug capability example.
func ExampleNew_debugAndFilter() {
// From any SYPL logger, bump all max levels to `info`
// From any SYPL logger having a `console` output, bump max levels to `debug`
// From a logger named `pod`, for its output called `Console`, bump max levels to `trace`
// From a logger named `pv`, for its output called `o1`, bump max levels to `trace`
os.Setenv(shared.LevelEnvVar, "info,console:debug,pod:console:trace,pv:o1:trace")
defer os.Unsetenv(shared.LevelEnvVar)
// From any SYPL logger, only print the following ones.
os.Setenv(shared.FilterEnvVar, "pod,svc,vs,np,cm,pv")
defer os.Unsetenv(shared.FilterEnvVar)
// Will print, max level bumped to `trace` by `pod:console:trace`.
sypl.New("pod").AddOutputs(output.Console(level.Error)).Traceln("pod created")
// Will print, max level bumped to `debug`.
sypl.New("svc").AddOutputs(output.Console(level.Error)).Debugln("svc created")
// Will print, max level bumped to `debug`.
sypl.New("vs").AddOutputs(output.Console(level.Error)).Debugln("vs created")
// Will print, max level bumped to `debug`.
sypl.New("np").AddOutputs(output.Console(level.Error)).Debugln("np created")
// Will print, max level bumped to `debug`.
sypl.New("cm").AddOutputs(output.Console(level.Error)).Debugln("cm created")
sypl.New("pv").AddOutputs(
// Will print, max level bumped to `trace` by `pv:o1:trace`.
output.New("o1", level.Error, os.Stdout),
// Will not print, max level bumped to `info` but less than `debug`.
output.New("o2", level.Error, os.Stdout),
).Traceln("pv created")
// Will not print, max level bumped to `debug` but it's filtered out.
sypl.New("dp").AddOutputs(output.Console(level.Error)).Debugln("dp created")
// output:
// pod created
// svc created
// vs created
// np created
// cm created
// pv created
}
// Sypl as io.Writer, including sub-loggers thru interfaces.
//
//nolint:gosimple
func ExampleNew_ioWriter() {
buf, o := output.SafeBuffer(level.Trace)
// Creates logger, and name it.
l := sypl.New(shared.DefaultComponentNameOutput, o.SetFormatter(formatter.Text()))
l.SetDefaultIoWriterLevel(level.Info)
if _, err := l.Write([]byte(shared.DefaultContentOutput + "1 \n")); err != nil {
fmt.Println(false)
}
l.SetDefaultIoWriterLevel(level.Warn)
if _, err := l.Write([]byte(shared.DefaultContentOutput + "2 \n")); err != nil {
fmt.Println(false)
}
var m sypl.ISypl
m = l.New("sub")
m.SetDefaultIoWriterLevel(level.Debug)
if _, err := m.Write([]byte(shared.DefaultContentOutput + "3 \n")); err != nil {
fmt.Println(false)
}
m.SetDefaultIoWriterLevel(level.Trace)
if _, err := m.Write([]byte(shared.DefaultContentOutput + "4 \n")); err != nil {
fmt.Println(false)
}
// Buf content should be...:
// component=componentNameTest output=buffer level=info timestamp=2022-02-22T09:58:22-08:00 message=contentTest1
// component=componentNameTest output=buffer level=warn timestamp=2022-02-22T09:58:22-08:00 message=contentTest2
// component=sub output=buffer level=debug timestamp=2022-02-22T09:58:22-08:00 message=contentTest3
// component=sub output=buffer level=trace timestamp=2022-02-22T09:58:22-08:00 message=contentTest4
fmt.Println(stringContains(buf.String(),
"componentNameTest",
"sub",
"contentTest1",
"contentTest2",
"contentTest3",
"contentTest4",
"info",
"warn",
"debug",
"trace",
))
// output:
// true
}
// Tagger processor.
func ExampleNew_tagger() {
buf, o := output.SafeBuffer(level.Info, processor.Tagger("a", "b"))
o.SetFormatter(formatter.Text())
// Creates logger, and name it.
sypl.New(shared.DefaultComponentNameOutput, o).Infoln(shared.DefaultContentOutput)
fmt.Print(strings.Contains(buf.String(), "tags=[a, b]"))
// output:
// true
}
// ForcePrint processor.
func ExampleNew_forcePrintProcessor() {
buf, o := output.SafeBuffer(level.Info, processor.Flagger(flag.Force))
o.SetFormatter(formatter.Text())
// Creates logger, and name it.
sypl.New(shared.DefaultComponentNameOutput, o).Traceln(shared.DefaultContentOutput)
fmt.Print(strings.Contains(buf.String(), "message=contentTest"))
// output:
// true
}
// WithID option.
func ExampleNew_withID_option() {
buf, o := output.SafeBuffer(level.Trace)
o.SetFormatter(formatter.JSON())
// Creates logger, and name it.
sypl.New(shared.DefaultComponentNameOutput, o).PrintWithOptions(level.Info, shared.DefaultContentOutput, sypl.WithID("idTest"))
fmt.Print(strings.Contains(buf.String(), `"id":"idTest"`))
// output:
// true
}