-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathquick-reference.html
More file actions
1381 lines (1164 loc) · 61.4 KB
/
Copy pathquick-reference.html
File metadata and controls
1381 lines (1164 loc) · 61.4 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
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>mtlog - Quick Reference</title>
<meta name="description" content="Quick reference guide for mtlog - Message Template Logging for Go">
<!-- Go import -->
<meta name="go-import" content="mtlog.dev git https://github.com/willibrandon/mtlog">
<!-- Prevent theme flash -->
<script>
(() => {
try {
const stored = localStorage.getItem('theme');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const theme = stored || (prefersDark ? 'dark' : 'light');
if (theme === 'light') {
document.documentElement.classList.add('light');
document.body?.classList.add('light', 'bg-white', 'text-gray-900');
document.body?.classList.remove('bg-gray-900', 'text-gray-100');
}
} catch {}
})();
</script>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Prism.js for syntax highlighting -->
<link id="prism-theme-dark" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet" disabled />
<link id="prism-theme-light" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css" rel="stylesheet" />
<style>
/* Custom gradient text */
.gradient-text {
background: linear-gradient(135deg, #7c3aed 0%, #2563eb 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
/* Theme transition */
* {
transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
}
/* Light theme adjustments */
body.light pre[class*="language-"] {
background-color: #f5f5f5;
border: 1px solid #e5e5e5;
}
/* Navigation link colors for light mode */
body.light nav a {
color: #6b7280; /* gray-500 */
}
body.light nav a:hover {
color: #111827; /* gray-900 */
}
/* Code block styling */
pre[class*="language-"] {
border-radius: 0.5rem;
margin: 0;
font-size: 0.875rem;
}
/* Smooth scroll with offset for sticky header */
html {
scroll-behavior: smooth;
scroll-padding-top: 100px; /* Offset for sticky header */
}
/* Sticky sidebar */
.sticky-sidebar {
position: sticky;
top: 5rem;
max-height: calc(100vh - 6rem);
overflow-y: auto;
}
/* Active nav link */
.nav-link.active {
color: #3b82f6;
font-weight: 600;
}
</style>
</head>
<body class="bg-gray-900 text-gray-100">
<!-- Header -->
<header class="border-b border-gray-800 sticky top-0 bg-gray-900 z-50">
<div class="container mx-auto px-4 py-4 flex justify-between items-center">
<div class="flex items-center gap-6">
<a href="/" class="text-2xl font-bold gradient-text">mtlog</a>
<h1 class="text-xl text-gray-400">Quick Reference</h1>
</div>
<div class="flex items-center gap-6">
<nav class="flex gap-6">
<a href="https://pkg.go.dev/github.com/willibrandon/mtlog" class="text-gray-400 hover:text-gray-100 transition">Docs</a>
<a href="https://github.com/willibrandon/mtlog" class="text-gray-400 hover:text-gray-100 transition">GitHub</a>
</nav>
<!-- Theme Switcher -->
<button id="theme-toggle" class="p-2 rounded-lg bg-gray-800 hover:bg-gray-700 transition" aria-label="Toggle theme">
<svg class="w-5 h-5 hidden dark-icon" fill="currentColor" viewBox="0 0 20 20">
<path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z"></path>
</svg>
<svg class="w-5 h-5 light-icon" fill="currentColor" viewBox="0 0 20 20">
<path d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z"></path>
</svg>
</button>
</div>
</div>
</header>
<div class="container mx-auto px-4 py-8">
<div class="flex gap-8">
<!-- Sidebar Navigation -->
<aside class="w-64 hidden lg:block">
<nav class="sticky-sidebar">
<h3 class="font-semibold mb-4 text-gray-400">On this page</h3>
<ul class="space-y-2 text-sm">
<li><a href="#basic-setup" class="nav-link text-gray-400 hover:text-white">Basic Setup</a></li>
<li><a href="#logging-methods" class="nav-link text-gray-400 hover:text-white">Logging Methods</a></li>
<li><a href="#message-templates" class="nav-link text-gray-400 hover:text-white">Message Templates</a></li>
<li><a href="#output-templates" class="nav-link text-gray-400 hover:text-white">Output Templates</a></li>
<li><a href="#enrichers" class="nav-link text-gray-400 hover:text-white">Enrichers</a></li>
<li><a href="#filters" class="nav-link text-gray-400 hover:text-white">Filters</a></li>
<li><a href="#sinks" class="nav-link text-gray-400 hover:text-white">Sinks</a></li>
<li><a href="#fortype" class="nav-link text-gray-400 hover:text-white">ForType</a></li>
<li><a href="#sampling" class="nav-link text-gray-400 hover:text-white">Per-Message Sampling</a></li>
<li><a href="#context-logging" class="nav-link text-gray-400 hover:text-white">Context Logging</a></li>
<li><a href="#logcontext" class="nav-link text-gray-400 hover:text-white">LogContext</a></li>
<li><a href="#deadline-awareness" class="nav-link text-gray-400 hover:text-white">Context Deadlines</a></li>
<li><a href="#dynamic-levels" class="nav-link text-gray-400 hover:text-white">Dynamic Levels</a></li>
<li><a href="#http-middleware" class="nav-link text-gray-400 hover:text-white">HTTP Middleware</a></li>
<li><a href="#ecosystem" class="nav-link text-gray-400 hover:text-white">Ecosystem</a></li>
<li><a href="#static-analysis" class="nav-link text-gray-400 hover:text-white">Static Analysis</a></li>
<li><a href="#ide-extensions" class="nav-link text-gray-400 hover:text-white">IDE Extensions</a></li>
</ul>
</nav>
</aside>
<!-- Main Content -->
<main class="flex-1 max-w-4xl">
<div class="prose prose-invert max-w-none">
<p class="text-lg text-gray-400 mb-8">A quick reference for all mtlog features and common usage patterns.</p>
<!-- Basic Setup -->
<section id="basic-setup" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Basic Setup</h2>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">import (
"github.com/willibrandon/mtlog"
"github.com/willibrandon/mtlog/core"
)
// Simple logger
logger := mtlog.New(mtlog.WithConsole())
// Production logger
logger := mtlog.New(
mtlog.WithConsoleTheme("dark"),
mtlog.WithSeq("http://localhost:5341", "api-key"),
mtlog.WithMinimumLevel(core.InformationLevel),
)</code></pre>
</div>
</section>
<!-- Logging Methods -->
<section id="logging-methods" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Logging Methods</h2>
<h3 class="text-xl font-semibold mb-2">Traditional Methods</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">logger.Verbose("Verbose message")
logger.Debug("Debug: {Value}", value)
logger.Information("Info: {User} {Action}", user, action)
logger.Warning("Warning: {Count} items", count)
logger.Error("Error: {Error}", err)
logger.Fatal("Fatal: {Reason}", reason)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">Generic Methods (Type-Safe)</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">logger.VerboseT("Verbose message")
logger.DebugT("Debug: {Value}", value)
logger.InformationT("Info: {User} {Action}", user, action)
logger.WarningT("Warning: {Count} items", count)
logger.ErrorT("Error: {Error}", err)
logger.FatalT("Fatal: {Reason}", reason)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">Short Methods</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">logger.V("Verbose")
logger.D("Debug: {Value}", value)
logger.I("Info: {Message}", msg)
logger.W("Warning: {Issue}", issue)
logger.E("Error: {Error}", err)
logger.F("Fatal: {Reason}", reason)</code></pre>
</div>
</section>
<!-- Message Templates -->
<section id="message-templates" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Message Templates</h2>
<h3 class="text-xl font-semibold mb-2">Template Syntaxes</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Traditional syntax
log.Information("User {UserId} logged in from {IP}", userId, ipAddress)
// Go template syntax
log.Information("User {{.UserId}} logged in from {{.IP}}", userId, ipAddress)
// Mixed syntax
log.Information("User {UserId} ({{.Username}}) from {IP}", userId, username, ipAddress)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">Capturing Hints</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// @ - capture complex types
log.Information("Order {@Order} created", order)
// $ - force scalar rendering
log.Information("Error occurred: {$Error}", err)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">Format Specifiers</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Numbers
log.Information("Count: {Count:000}", 42) // 042
log.Information("Price: ${Price:F2}", 123.456) // $123.46
log.Information("Usage: {Percent:P1}", 0.85) // 85.0%
// Custom alignment
log.Information("Status: {Status,10}", "OK") // "OK "
log.Information("Code: {Code,-5}", "ABC") // "ABC "</code></pre>
</div>
</section>
<!-- Output Templates -->
<section id="output-templates" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Output Templates</h2>
<h3 class="text-xl font-semibold mb-2">Console Templates</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Simple
mtlog.WithConsoleTemplate("[${Level:u3}] ${Message}")
// With timestamp
mtlog.WithConsoleTemplate("[${Timestamp:HH:mm:ss} ${Level:u3}] ${Message}")
// Full details
mtlog.WithConsoleTemplate(
"[${Timestamp:yyyy-MM-dd HH:mm:ss} ${Level:u3}] {SourceContext}: ${Message}${NewLine}${Exception}")</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">File Templates</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">mtlog.WithFileTemplate("app.log",
"[${Timestamp:o} ${Level:u3}] {SourceContext} ${Message}${NewLine}${Exception}")</code></pre>
</div>
</section>
<!-- Enrichers -->
<section id="enrichers" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Enrichers</h2>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Built-in enrichers
logger := mtlog.New(
mtlog.WithTimestamp(),
mtlog.WithMachineName(),
mtlog.WithProcessInfo(),
mtlog.WithEnvironmentVariables("APP_ENV", "VERSION"),
mtlog.WithThreadId(),
mtlog.WithCallersInfo(),
mtlog.WithSourceContext(),
)
// Custom enricher
type UserEnricher struct{ userID int }
func (e *UserEnricher) Enrich(event *core.LogEvent, factory core.LogEventPropertyFactory) {
event.AddPropertyIfAbsent(factory.CreateProperty("UserId", e.userID))
}
logger := mtlog.New(
mtlog.WithEnricher(&UserEnricher{userID: 123}),
)</code></pre>
</div>
</section>
<!-- Filters -->
<section id="filters" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Filters</h2>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Level filtering
mtlog.WithMinimumLevel(core.WarningLevel)
// Level overrides by source
mtlog.WithMinimumLevelOverrides(map[string]core.LogEventLevel{
"myapp/services": core.DebugLevel,
"github.com/gin-gonic/gin": core.WarningLevel,
})
// Custom filter
mtlog.WithFilter(filters.NewPredicateFilter(func(e *core.LogEvent) bool {
return !strings.Contains(e.MessageTemplate.Text, "health-check")
}))
// Rate limiting
mtlog.WithFilter(filters.NewRateLimitFilter(100, time.Minute))
// Sampling
mtlog.WithFilter(filters.NewSamplingFilter(0.1)) // 10% of events</code></pre>
</div>
</section>
<!-- Sinks -->
<section id="sinks" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Sinks</h2>
<h3 class="text-xl font-semibold mb-2">Console</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Themes
mtlog.WithConsoleTheme(sinks.LiterateTheme())
mtlog.WithConsoleTheme(sinks.DarkTheme())
mtlog.WithConsoleTheme(sinks.LightTheme())
mtlog.WithConsoleTheme(sinks.NoColorTheme())</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">File</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Simple file
mtlog.WithFileSink("app.log")
// Rolling by size
mtlog.WithRollingFile("app.log", 10*1024*1024) // 10MB
// Rolling by time
mtlog.WithRollingFileTime("app.log", time.Hour)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">Seq</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Basic
mtlog.WithSeq("http://localhost:5341")
// With API key
mtlog.WithSeq("http://localhost:5341", "your-api-key")
// Dynamic level control
levelOption, levelSwitch, controller := mtlog.WithSeqLevelControl(
"http://localhost:5341",
mtlog.SeqLevelControllerOptions{
CheckInterval: 30*time.Second,
},
)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">Elasticsearch</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Basic
mtlog.WithElasticsearch("http://localhost:9200", "logs")
// With multiple nodes and API key
mtlog.WithElasticsearchAdvanced(
[]string{"http://node1:9200", "http://node2:9200"},
sinks.WithElasticsearchIndex("logs-%{+yyyy.MM.dd}"),
sinks.WithElasticsearchAPIKey("your-api-key"),
sinks.WithElasticsearchBatchSize(100),
)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">Splunk</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Basic HEC integration
mtlog.WithSplunk("http://localhost:8088", "hec-token")
// Advanced configuration
mtlog.WithSplunkAdvanced("http://localhost:8088",
sinks.WithSplunkToken("your-hec-token"),
sinks.WithSplunkIndex("main"),
sinks.WithSplunkSource("mtlog"),
sinks.WithSplunkSourceType("_json"),
)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">Sentry</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">import "github.com/willibrandon/mtlog/adapters/sentry"
// Basic error tracking
sink, _ := sentry.WithSentry("https://key@sentry.io/project")
log := mtlog.New(mtlog.WithSink(sink))
// With sampling for high-volume applications
sink, _ := sentry.WithSentry("https://key@sentry.io/project",
sentry.WithFixedSampling(0.1), // 10% sampling
)
// Advanced configuration with performance monitoring
sink, _ := sentry.WithSentry("https://key@sentry.io/project",
sentry.WithEnvironment("production"),
sentry.WithRelease("v1.2.3"),
sentry.WithTracesSampleRate(0.2),
sentry.WithProfilesSampleRate(0.1),
sentry.WithAdaptiveSampling(0.01, 0.5), // 1% to 50% adaptive
sentry.WithRetryPolicy(3, time.Second),
sentry.WithStackTraceCache(1000),
)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">OpenTelemetry (OTLP)</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">import "github.com/willibrandon/mtlog/adapters/otel"
// Basic OTLP sink
logger := otel.NewOTELLogger(
otel.WithOTLPEndpoint("localhost:4317"),
otel.WithOTLPInsecure(),
)
// With batching and compression
logger := mtlog.New(
otel.WithOTLPSink(
otel.WithOTLPEndpoint("otel-collector:4317"),
otel.WithOTLPBatching(100, 5*time.Second),
otel.WithOTLPCompression("gzip"),
),
)
// With trace context enrichment
logger := otel.NewRequestLogger(ctx,
otel.WithOTLPEndpoint("localhost:4317"),
otel.WithOTLPInsecure(),
)
// With sampling strategies
logger := mtlog.New(
otel.WithOTLPSink(
otel.WithOTLPEndpoint("localhost:4317"),
otel.WithOTLPSampling(otel.NewRateSampler(0.1)), // 10% sampling
),
)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">Async & Durable</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Async wrapper
mtlog.WithAsync(mtlog.WithFileSink("app.log"))
// Durable buffering
mtlog.WithDurable(
mtlog.WithSeq("http://localhost:5341"),
sinks.WithDurableDirectory("./logs/buffer"),
sinks.WithDurableMaxSize(100*1024*1024),
)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-2">Event Routing</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Conditional sink - zero overhead for non-matching events
alertSink := sinks.NewConditionalSink(
func(e *core.LogEvent) bool {
return e.Level >= core.ErrorLevel && e.Properties["Alert"] != nil
},
sinks.NewFileSink("alerts.log"),
)
// Built-in predicates
sinks.LevelPredicate(core.ErrorLevel) // Level filtering
sinks.PropertyPredicate("Audit") // Property exists
sinks.PropertyValuePredicate("Environment", "production") // Property value
sinks.AndPredicate(pred1, pred2) // All must match
sinks.OrPredicate(pred1, pred2) // Any matches
sinks.NotPredicate(pred) // Invert predicate
// Router sink - FirstMatch mode (exclusive routing)
router := sinks.NewRouterSink(sinks.FirstMatch,
sinks.ErrorRoute("errors", errorSink),
sinks.AuditRoute("audit", auditSink),
)
// Router sink - AllMatch mode (broadcast routing)
router := sinks.NewRouterSink(sinks.AllMatch,
sinks.MetricRoute("metrics", metricsSink),
sinks.AuditRoute("audit", auditSink),
)
// Dynamic route management
router.AddRoute(sinks.Route{
Name: "debug",
Predicate: func(e *core.LogEvent) bool { return e.Level <= core.DebugLevel },
Sink: debugSink,
})
router.RemoveRoute("debug")
// Fluent route builder
route := sinks.NewRoute("special").
When(func(e *core.LogEvent) bool { return e.Properties["Special"] != nil }).
To(specialSink)</code></pre>
</div>
</section>
<!-- ForType -->
<section id="fortype" class="mb-12">
<h2 class="text-2xl font-bold mb-4">ForType - Type-Based Logging</h2>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Automatic SourceContext from types
userLogger := mtlog.ForType[User](logger)
userLogger.Information("User created") // SourceContext: "User"
// Service pattern
type UserService struct {
logger core.Logger
}
func NewUserService(base core.Logger) *UserService {
return &UserService{
logger: mtlog.ForType[UserService](base),
}
}
// Advanced options
opts := mtlog.TypeNameOptions{
IncludePackage: true,
Prefix: "MyApp.",
}
name := mtlog.ExtractTypeName[User](opts) // "MyApp.mypackage.User"</code></pre>
</div>
</section>
<!-- Per-Message Sampling -->
<section id="sampling" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Per-Message Sampling</h2>
<h3 class="text-xl font-semibold mb-3 text-purple-400">Basic Sampling</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Sample every Nth message
sampledLogger := logger.Sample(10) // Every 10th message
// Time-based sampling
sampledLogger := logger.SampleDuration(time.Second) // At most once per second
// Rate-based sampling (percentage)
sampledLogger := logger.SampleRate(0.1) // 10% of messages
// First N occurrences
sampledLogger := logger.SampleFirst(100) // First 100 messages only</code></pre>
</div>
<h3 class="text-xl font-semibold mb-3 text-purple-400">Advanced Sampling</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Group sampling - share counter across loggers
dbLogger := logger.SampleGroup("database", 10)
cacheLogger := logger.SampleGroup("database", 10) // Same counter
// Conditional sampling
var highLoad atomic.Bool
sampledLogger := logger.SampleWhen(func() bool {
return highLoad.Load()
}, 5) // Every 5th when condition true
// Exponential backoff
errorLogger := logger.SampleBackoff("connection-error", 2.0)
// Logs at: 1st, 2nd, 4th, 8th, 16th, 32nd...</code></pre>
</div>
<h3 class="text-xl font-semibold mb-3 text-purple-400">Configuration</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Default sampling for all messages
logger := mtlog.New(
mtlog.WithConsole(),
mtlog.WithDefaultSampling(100), // Every 100th by default
)
// Reset sampling counters
sampledLogger.ResetSampling()
logger.ResetSamplingGroup("database")
// Sampling statistics
sampledLogger.EnableSamplingSummary(5 * time.Minute)
sampled, skipped := sampledLogger.GetSamplingStats()
// Cache warmup (at startup)
mtlog.WarmupSamplingGroups([]string{"database", "api"})
mtlog.WarmupSamplingBackoff([]string{"error", "timeout"}, 2.0)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-3 text-purple-400">Advanced Sampling Configuration</h3>
<h4 class="text-lg font-medium mb-2 text-blue-400">Predefined Sampling Profiles</h4>
<p class="text-gray-400 mb-3">Ready-to-use sampling profiles for common production scenarios:</p>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// High-traffic API endpoints (1% sampling)
apiLogger := logger.SampleProfile("HighTrafficAPI")
// Background workers (10% sampling)
workerLogger := logger.SampleProfile("BackgroundWorker")
// Error logging with exponential backoff
errorLogger := logger.SampleProfile("ErrorReporting")
// Debug mode with higher sampling (25%)
debugLogger := logger.SampleProfile("DebugVerbose")
// Interactive user actions (50% sampling)
userLogger := logger.SampleProfile("UserInteractive")
// Database operations (every 5th message)
dbLogger := logger.SampleProfile("DatabaseOps")
// Analytics events (5% sampling)
analyticsLogger := logger.SampleProfile("Analytics")
// System health monitoring (time-based, once per second)
healthLogger := logger.SampleProfile("SystemHealth")</code></pre>
</div>
<h4 class="text-lg font-medium mb-2 text-blue-400">Adaptive Sampling</h4>
<p class="text-gray-400 mb-3">Automatically adjusts sampling rates to maintain target throughput:</p>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Target 100 events per second - automatically adjusts sampling rate
adaptiveLogger := logger.SampleAdaptive(100)
// Advanced adaptive sampling with bounds
adaptiveLogger := logger.SampleAdaptiveWithOptions(
250, // Target: 250 events/second
0.01, // Minimum rate: 1%
1.0, // Maximum rate: 100%
30*time.Second, // Check interval
)
// Advanced adaptive sampling with hysteresis for stability
hysteresisLogger := logger.SampleAdaptiveWithHysteresis(
200, // Target: 200 events/second
0.005, // Minimum rate: 0.5%
0.8, // Maximum rate: 80%
15*time.Second, // Check interval
0.15, // Hysteresis: 15% (prevents oscillation)
0.7, // Aggressiveness: 70% (smoother adjustments)
)
// Ultimate adaptive sampling with dampening for extreme load
dampenedLogger := logger.SampleAdaptiveWithDampening(
200, // Target: 200 events/second
0.005, // Minimum rate: 0.5%
0.8, // Maximum rate: 80%
15*time.Second, // Check interval
0.15, // Hysteresis: 15% (prevents oscillation)
0.7, // Aggressiveness: 70% (smoother adjustments)
0.4, // Dampening: 40% (reduces oscillation)
)
// Simplified adaptive sampling with dampening presets
conservativeLogger := logger.SampleAdaptiveWithPreset(100, mtlog.DampeningConservative)
moderateLogger := logger.SampleAdaptiveWithPreset(100, mtlog.DampeningModerate)
aggressiveLogger := logger.SampleAdaptiveWithPreset(100, mtlog.DampeningAggressive)
ultraStableLogger := logger.SampleAdaptiveWithPreset(100, mtlog.DampeningUltraStable)
responsiveLogger := logger.SampleAdaptiveWithPreset(100, mtlog.DampeningResponsive)
// Custom rate limits with presets
customLogger := logger.SampleAdaptiveWithPresetCustom(150, mtlog.DampeningAggressive, 0.05, 0.8)
// Available Presets:
// - Conservative: Heavy dampening for stable production (3s intervals)
// - Moderate: Balanced for general production use (1s intervals)
// - Aggressive: Light dampening for dynamic environments (500ms intervals)
// - Ultra Stable: Maximum stability for critical systems (5s intervals)
// - Responsive: Minimal dampening for development (200ms intervals)
// Adaptive sampling automatically:
// - Measures actual event rate
// - Increases sampling when below target
// - Decreases sampling when above target
// - Uses hysteresis to prevent rate oscillation
// - Applies exponential smoothing for stability
// - Stays within configured min/max bounds</code></pre>
</div>
<h4 class="text-lg font-medium mb-2 text-blue-400">Custom Sampling Profiles</h4>
<p class="text-gray-400 mb-3">Create application-specific sampling profiles:</p>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Define custom profiles for your application
customProfiles := map[string]mtlog.SamplingProfile{
"PaymentProcessing": {
Description: "Critical payment operations - log all errors, sample others",
Config: func() mtlog.Option {
return mtlog.Sampling().
When(func() bool { return getCurrentErrorRate() > 0.01 }, 1). // All errors
Rate(0.1). // 10% normal ops
CombineOR()
},
},
"UserAnalytics": {
Description: "User behavior tracking",
Config: func() mtlog.Option {
return mtlog.Sampling().
First(1000). // First 1000 events per user
Rate(0.05). // Then 5% sampling
Build()
},
},
}
// Register and use custom profiles
mtlog.RegisterSamplingProfiles(customProfiles)
// Bulk register multiple profiles with error handling
if err := mtlog.RegisterCustomProfiles(customProfiles); err != nil {
log.Fatal("Failed to register sampling profiles:", err)
}
// Freeze profile registry after registration (recommended for production)
mtlog.FreezeProfiles()
// Use custom profiles
paymentLogger := logger.SampleProfile("PaymentProcessing")
// Profile versioning for backward compatibility
mtlog.AddCustomProfileWithVersion("PaymentV2", "Enhanced payment processing", "2.0", false, "",
func() core.LogEventFilter { return mtlog.Sampling().Rate(0.05).Build() })
// Use specific version
legacyPayment := logger.SampleProfileWithVersion("PaymentV2", "1.0")
modernPayment := logger.SampleProfileWithVersion("PaymentV2", "2.0")
// Version management
versions := mtlog.GetProfileVersions("PaymentV2")
isDeprecated, replacement := mtlog.IsProfileDeprecated("PaymentV2")
// Profile version auto-migration
mtlog.SetMigrationPolicy(mtlog.MigrationPolicy{
Consent: mtlog.MigrationAuto, // Auto-migrate without prompting
PreferStable: true, // Skip deprecated versions
MaxVersionDistance: 1, // Allow migration within 1 major version
})
// Request version that might not exist - auto-migrates to compatible version
profile, actualVersion, found := mtlog.GetProfileWithMigration("PaymentV2", "1.5")
migratedLogger := logger.SampleProfileWithVersion("PaymentV2", "1.3") // Auto-migrates if needed
// Migration Consent Modes:
// - MigrationDeny: Strict mode - fail if exact version not found
// - MigrationPrompt: Log warning and migrate to best available (default)
// - MigrationAuto: Silent automatic migration to compatible versions</code></pre>
</div>
<h4 class="text-lg font-medium mb-2 text-blue-400">Fluent Sampling Configuration Builder</h4>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Pipeline-style sampling (filters applied in sequence)
logger := mtlog.New(
mtlog.WithConsole(),
mtlog.Sampling().
Every(10). // First: sample every 10th message
Rate(0.5). // Then: 50% of those that pass
First(100). // Finally: only first 100 that make it through
Build(), // Apply as sequential pipeline
)
// Composite AND sampling (all conditions must match)
logger := mtlog.New(
mtlog.WithConsole(),
mtlog.Sampling().
Every(2). // Must be every 2nd message
First(10). // Must be within first 10 evaluations
CombineAND(), // Both conditions must be true
)
// Composite OR sampling (any condition can match)
logger := mtlog.New(
mtlog.WithConsole(),
mtlog.Sampling().
Every(5). // Either every 5th message
First(3). // Or first 3 messages
CombineOR(), // Either condition allows logging
)</code></pre>
</div>
<h4 class="text-lg font-medium mb-2 text-blue-400">Custom Sampling Policies</h4>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Implement SamplingPolicy interface for complex logic
type UserBasedSamplingPolicy struct {
adminRate float32
premiumRate float32
basicRate float32
}
func (p *UserBasedSamplingPolicy) ShouldSample(event *core.LogEvent) bool {
userTier, _ := event.Properties["UserTier"].(string)
switch userTier {
case "admin": return true
case "premium": return rand.Float32() < p.premiumRate
case "basic": return rand.Float32() < p.basicRate
default: return false
}
}
// Use the custom policy
logger := mtlog.New(
mtlog.WithConsole(),
mtlog.WithSamplingPolicy(&UserBasedSamplingPolicy{
adminRate: 1.0, premiumRate: 0.5, basicRate: 0.1,
}),
)</code></pre>
</div>
<h4 class="text-lg font-medium mb-2 text-blue-400">Pipeline vs Composite Behavior</h4>
<div class="bg-gray-800/50 rounded-lg p-4 mb-6">
<p class="text-gray-300 mb-2"><strong>Key Differences:</strong></p>
<ul class="text-gray-400 space-y-2 list-disc list-inside">
<li><strong>Pipeline (Build()):</strong> Filters applied sequentially. Each filter only sees events that passed the previous filter</li>
<li><strong>Composite (CombineAND/OR()):</strong> Each filter evaluates all events independently, results combined with logical AND/OR</li>
</ul>
<div class="bg-gray-800 rounded-lg p-3 mt-3">
<pre><code class="language-go">// Pipeline: Every(2) → First(5) → Result
mtlog.Sampling().Every(2).First(5).Build()
// Composite: Every(2) AND First(5) → Result
mtlog.Sampling().Every(2).First(5).CombineAND()</code></pre>
</div>
</div>
<h3 class="text-xl font-semibold mb-3 text-purple-400">Production Pattern</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Different sampling for different endpoints
healthLogger := logger.
ForContext("Endpoint", "/health").
SampleDuration(10 * time.Second) // Once per 10 seconds
apiLogger := logger.
ForContext("Endpoint", "/api/users").
SampleRate(0.01) // 1% sampling
errorLogger := logger.
SampleBackoff("api-error", 2.0) // Exponential backoff</code></pre>
</div>
</section>
<!-- Context Logging -->
<section id="context-logging" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Context Logging</h2>
<h3 class="text-xl font-semibold mb-3 text-purple-400">With() Method - Structured Fields</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Basic usage with key-value pairs
logger.With("service", "api", "version", "1.0").Info("Service started")
// Chaining With() calls
logger.
With("environment", "production").
With("region", "us-west-2").
Info("Deployment complete")
// Create a base logger with common fields
apiLogger := logger.With(
"component", "api",
"host", "api-server-01",
)
// Request-scoped logging
requestLogger := apiLogger.With(
"request_id", "abc-123",
"user_id", 456,
)
requestLogger.Info("Request started")
requestLogger.With("duration_ms", 42).Info("Request completed")</code></pre>
</div>
<h3 class="text-xl font-semibold mb-3 text-purple-400">ForContext() Method</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Add single context property
contextLogger := logger.ForContext("RequestId", "abc-123")
// Multiple properties (variadic)
contextLogger := logger.ForContext("UserId", 123, "SessionId", "xyz")
// Source context for sub-loggers
serviceLogger := logger.ForSourceContext("MyApp.Services.UserService")</code></pre>
</div>
<div class="bg-gray-800/50 rounded-lg p-4">
<p class="text-gray-300 mb-2"><strong>With() vs ForContext():</strong></p>
<ul class="text-gray-400 space-y-1 list-disc list-inside">
<li><strong>With():</strong> Accepts variadic key-value pairs (slog-style), convenient for multiple fields</li>
<li><strong>ForContext():</strong> Takes property name and value(s), returns a new logger</li>
<li>Both create a new logger instance with the combined properties</li>
</ul>
</div>
</section>
<!-- LogContext -->
<section id="logcontext" class="mb-12">
<h2 class="text-2xl font-bold mb-4">LogContext - Scoped Properties</h2>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Add properties to context
ctx := context.Background()
ctx = mtlog.PushProperty(ctx, "RequestId", "req-123")
ctx = mtlog.PushProperty(ctx, "UserId", userId)
// Use with logger
log := logger.WithContext(ctx)
log.Information("Processing request") // Includes RequestId & UserId
// Property precedence
ctx = mtlog.PushProperty(ctx, "UserId", 123)
logger.WithContext(ctx).Information("Test") // UserId=123
logger.WithContext(ctx).ForContext("UserId", 456).Information("Test") // UserId=456
logger.WithContext(ctx).Information("User {UserId}", 789) // UserId=789</code></pre>
</div>
</section>
<!-- Context Deadline Awareness -->
<section id="deadline-awareness" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Context Deadline Awareness</h2>
<h3 class="text-xl font-semibold mb-3 text-purple-400">Context-Aware Methods</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// All levels have context variants
logger.InfoContext(ctx, "Processing request")
logger.ErrorContext(ctx, "Operation failed: {Error}", err)
logger.DebugContext(ctx, "Cache hit for key {Key}", key)
// Context methods automatically:
// - Extract LogContext properties
// - Check for approaching deadlines
// - Include deadline properties when warning</code></pre>
</div>
<h3 class="text-xl font-semibold mb-3 text-purple-400">Deadline Configuration</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Absolute threshold - warn when 100ms remains
logger := mtlog.New(
mtlog.WithContextDeadlineWarning(100*time.Millisecond),
)
// Percentage threshold - warn when 20% remains
logger := mtlog.New(
mtlog.WithDeadlinePercentageThreshold(
10*time.Millisecond, // Min absolute
0.2, // 20% threshold
),
)</code></pre>
</div>
<h3 class="text-xl font-semibold mb-3 text-purple-400">Properties Added</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-json">// When approaching deadline
{
"deadline.approaching": true,
"deadline.remaining_ms": 95,
"deadline.at": "2024-01-15T10:30:45Z",
"deadline.first_warning": true
}
// When deadline exceeded
{
"deadline.exceeded": true,
"deadline.exceeded_by_ms": 150
}</code></pre>
</div>
<h3 class="text-xl font-semibold mb-3 text-purple-400">Example Usage</h3>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
logger.InfoContext(ctx, "Starting operation")
time.Sleep(350 * time.Millisecond)
logger.InfoContext(ctx, "Still processing...") // WARNING: Deadline approaching!</code></pre>
</div>
</section>
<!-- Dynamic Levels -->
<section id="dynamic-levels" class="mb-12">
<h2 class="text-2xl font-bold mb-4">Dynamic Level Control</h2>
<div class="bg-gray-800 rounded-lg p-4 mb-4">
<pre><code class="language-go">// Manual control
levelSwitch := mtlog.NewLoggingLevelSwitch(core.InformationLevel)
logger := mtlog.New(
mtlog.WithLevelSwitch(levelSwitch),
mtlog.WithConsole(),
)
// Change at runtime
levelSwitch.SetLevel(core.DebugLevel)
// Fluent interface
levelSwitch.Debug().Information().Warning()
// Check if enabled