-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
278 lines (221 loc) · 7.58 KB
/
Copy pathmain.go
File metadata and controls
278 lines (221 loc) · 7.58 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
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/JupiterMetaLabs/ion"
"github.com/JupiterMetaLabs/ion/fields"
)
// ============================================================================
// Example 1: Simple Usage
// Best for: Small apps, scripts, or quick prototypes.
// ============================================================================
func example1_SimpleUsage() {
ctx := context.Background()
// Create Ion instance - one entry point for everything
// Use Development() to see caller and debug logs
app, warnings, err := ion.New(ion.Development().WithService("example-app"))
if err != nil {
log.Fatalf("Failed to create ion: %v", err)
}
for _, w := range warnings {
log.Printf("ion warning: %v", w)
}
defer func() { _ = app.Sync() }()
// Use Ion directly for logging
app.Info(ctx, "application started")
app.Debug(ctx, "debug info", ion.String("key", "value"))
app.Warn(ctx, "something might be wrong")
}
// ============================================================================
// Example 2: Dependency Injection Pattern
// Best for: Libraries, large apps, or teams that prefer explicit dependencies.
// ============================================================================
func example2_DependencyInjection() {
ctx := context.Background()
app, _, err := ion.New(ion.Default().WithService("payment-api"))
if err != nil {
log.Fatalf("Failed to create ion: %v", err)
}
defer func() { _ = app.Sync() }()
// Pass a scoped child to components — preserves logging, tracing, and metrics
server := NewServer(app.Child("server"))
server.Start(ctx)
}
type Server struct {
app *ion.Ion // Full observability — logging, tracing, and metrics
}
func NewServer(app *ion.Ion) *Server {
return &Server{app: app}
}
func (s *Server) Start(ctx context.Context) {
s.app.Info(ctx, "server listening", ion.Int("port", 8080))
// Child has full access to tracing
tracer := s.app.Tracer("server.handler")
ctx, span := tracer.Start(ctx, "Start")
defer span.End()
s.app.Info(ctx, "server initialized")
}
// ============================================================================
// Example 3: Child Loggers (With and Named)
// Demonstrates how to scope loggers for specific contexts.
// ============================================================================
func example3_ChildLoggers() {
ctx := context.Background()
app, _, _ := ion.New(ion.Default())
// Named: Adds a "logger" field to identify the component
httpLog := app.Named("http")
grpcLog := app.Named("grpc")
// With: Adds permanent fields to all log entries from this child
userLogger := app.With(
ion.Int("user_id", 42),
ion.String("tenant", "acme-corp"),
)
httpLog.Info(ctx, "request received") // {"logger": "http", ...}
grpcLog.Info(ctx, "rpc called") // {"logger": "grpc", ...}
userLogger.Info(ctx, "action taken") // {"user_id": 42, "tenant": "acme-corp", ...}
}
// ============================================================================
// Example 4: Metrics
// Demonstrates OpenTelemetry metrics instrumentation.
// ============================================================================
func example4_Metrics() {
ctx := context.Background()
cfg := ion.Default().WithService("metrics-demo")
cfg.Metrics.Enabled = true
cfg.Metrics.Endpoint = "localhost:4317" // OTel Collector
cfg.Metrics.Protocol = "grpc"
cfg.Metrics.Insecure = true
app, _, err := ion.New(cfg)
if err != nil {
log.Fatalf("Failed to create ion: %v", err)
}
defer func() { _ = app.Shutdown(ctx) }()
// Get a named meter
meter := app.Meter("example.metrics")
// Create instruments
requestCounter, _ := meter.Int64Counter("http_requests_total") // metric.WithDescription("Total HTTP requests"),
latencyHist, _ := meter.Float64Histogram("http_request_duration_seconds") // metric.WithDescription("HTTP request latency"),
// Record metrics
requestCounter.Add(ctx, 1)
latencyHist.Record(ctx, 0.025) // 25ms
app.Info(ctx, "metrics recorded")
}
// ============================================================================
// Example 5: Blockchain Fields
// Demonstrates domain-specific field helpers.
// ============================================================================
func example5_BlockchainFields() {
ctx := context.Background()
app, _, _ := ion.New(ion.Default().WithService("mempool-router"))
app.Info(ctx, "transaction routed",
fields.TxHash("0xabc123..."),
fields.ShardID(3),
fields.Slot(150_000_000),
fields.Epoch(350),
fields.BlockHeight(19_500_000),
fields.LatencyMs(12.5),
)
}
// ============================================================================
// Example 6: Production Setup with Tracing
// The recommended pattern for real-world services.
// ============================================================================
func example6_ProductionSetup() {
ctx := context.Background()
cfg := ion.Config{
Level: "info",
Development: false,
ServiceName: "order-service",
Version: "v2.1.0",
Console: ion.ConsoleConfig{
Enabled: true,
Format: "json",
ErrorsToStderr: true,
},
File: ion.FileConfig{
Enabled: true,
Path: "/var/log/orders/app.log",
MaxSizeMB: 100,
MaxBackups: 5,
Compress: true,
},
OTEL: ion.OTELConfig{
Enabled: true,
Endpoint: "otel-collector:4317",
Protocol: "grpc",
Attributes: map[string]string{
"env": "production",
"region": "us-east-1",
},
},
Tracing: ion.TracingConfig{
Enabled: true,
Sampler: "ratio:0.1", // Sample 10%
},
}
app, warnings, err := ion.New(cfg)
if err != nil {
log.Fatalf("Failed to create ion: %v", err)
}
for _, w := range warnings {
log.Printf("ion warning: %v", w)
}
// CRITICAL: Graceful shutdown to flush all logs and traces
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := app.Shutdown(shutdownCtx); err != nil {
fmt.Fprintf(os.Stderr, "shutdown error: %v\n", err)
}
}()
// Run your application
runProductionApp(ctx, app)
}
func runProductionApp(ctx context.Context, app *ion.Ion) {
// Child preserves tracing and metrics — single entry point for component observability
svc := app.Child("main")
tracer := svc.Tracer("order-service.main")
// Create a span for the main operation
ctx, span := tracer.Start(ctx, "ApplicationRun")
defer span.End()
svc.Info(ctx, "service started")
// Simulate work
time.Sleep(100 * time.Millisecond)
// Simulate an error
err := errors.New("database connection lost")
svc.Error(ctx, "critical failure", err, ion.String("component", "db"))
// Wait for signal
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
go func() {
// Auto-exit for example purposes
time.Sleep(200 * time.Millisecond)
sigChan <- syscall.SIGTERM
}()
svc.Info(ctx, "waiting for shutdown signal...")
<-sigChan
svc.Info(ctx, "received shutdown signal, exiting...")
}
// ============================================================================
// Main: Run all examples
// ============================================================================
func main() {
fmt.Println("=== Example 1: Simple Usage ===")
example1_SimpleUsage()
fmt.Println("\n=== Example 2: Dependency Injection ===")
example2_DependencyInjection()
fmt.Println("\n=== Example 3: Child Loggers ===")
example3_ChildLoggers()
fmt.Println("\n=== Example 4: Metrics ===")
example4_Metrics()
fmt.Println("\n=== Example 5: Blockchain Fields ===")
example5_BlockchainFields()
fmt.Println("\n=== Example 6: Production Setup ===")
example6_ProductionSetup()
}