shared-logging 0.1.0

Structured logging library with context propagation, redaction, and HTTP middleware
Documentation
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
# Consumer Guide: Using shared-logging

This guide walks you through consuming the `shared-logging` crate in your Rust application.

## Table of Contents

1. [Installation]#installation
2. [Basic Setup]#basic-setup
3. [Basic Logging]#basic-logging
4. [Structured Logging with Fields]#structured-logging-with-fields
5. [Context Propagation]#context-propagation
6. [Error Logging]#error-logging
7. [HTTP Middleware]#http-middleware
8. [OpenTelemetry Integration]#opentelemetry-integration
9. [Configuration]#configuration

## Installation

### Option 1: Local Path Dependency (Recommended for Development)

For local development when the crate is in a sibling directory or workspace:

```toml
[dependencies]
shared-logging = { path = "../shared-logging" }  # Adjust path relative to your project

# With optional features
# shared-logging = { path = "../shared-logging", features = ["http", "otel"] }
```

**When to use:** 
- Developing the crate alongside your application
- Testing changes to the logging library
- Local development and testing

### Option 2: Git Dependency

If the crate is in a Git repository:

```toml
[dependencies]
shared-logging = { git = "https://github.com/kelleyblackmore/shared-logging" }

# With optional features
# shared-logging = { git = "https://github.com/kelleyblackmore/shared-logging", features = ["http"] }
```

**When to use:**
- Using a specific version from a Git repository
- The crate isn't published to crates.io yet

### Option 3: Published to crates.io (Future)

Once published, you can use it like any other crate:

```toml
[dependencies]
shared-logging = "0.1.0"  # Use the version number

# With optional features
# shared-logging = { version = "0.1.0", features = ["http", "otel"] }
```

**When to use:**
- The crate is published to crates.io
- You want version management via semver

### Option 4: Workspace Setup (Multiple Projects)

If you have multiple projects that use this crate, set up a Cargo workspace:

**In your workspace root `Cargo.toml`:**
```toml
[workspace]
members = [
    "shared-logging",
    "my-service-1",
    "my-service-2",
]
```

**In your service `Cargo.toml`:**
```toml
[dependencies]
shared-logging = { path = "../shared-logging" }
```

**When to use:**
- Managing multiple projects that share the logging library
- Coordinated development across services

### Step 2: Import the Library

```rust
use shared_logging::{init_logger, Logger, ContextBuilder};
```

## Basic Setup

### Initialize the Logger (Once at Startup)

The logger must be initialized once at the start of your application. This sets up:
- JSON formatter
- Log level filtering
- Output destination (stdout by default)

```rust
use shared_logging::init_logger;

fn main() {
    // Initialize with service name and default log level
    init_logger("my-service", "info")
        .expect("Failed to initialize logger");
    
    // Your application code here
}
```

**Parameters:**
- `service_name`: Name of your service (appears in all log events)
- `default_level`: Default log level (`"trace"`, `"debug"`, `"info"`, `"warn"`, `"error"`)

**Note:** The log level can be overridden with the `RUST_LOG` environment variable:
```bash
RUST_LOG=debug cargo run
RUST_LOG=my_service=debug,other_crate=info cargo run
```

## Basic Logging

### Create a Logger Instance

Create logger instances for different modules/components:

```rust
use shared_logging::Logger;

// Create logger for a specific module
let logger = Logger::new("auth");
let api_logger = Logger::new("api");
let db_logger = Logger::new("database");
```

### Simple Logging

```rust
let logger = Logger::new("my-module");

logger.trace("Very detailed information");
logger.debug("Debug information");
logger.info("Informational message");
logger.warn("Warning message");
logger.error("Error message");
```

**Output:**
```json
{
  "timestamp": "2024-01-15T10:30:45.123Z",
  "level": "info",
  "message": "Informational message",
  "service": "my-service",
  "module": "my-module"
}
```

## Structured Logging with Fields

Add structured fields to your logs:

```rust
logger.info_with("User logged in", |e| {
    e.field("user_id", "user123");
    e.field("ip_address", "192.168.1.100");
    e.field("login_method", "oauth");
    e.field("success", true);
});
```

**Output:**
```json
{
  "timestamp": "2024-01-15T10:30:45.123Z",
  "level": "info",
  "message": "User logged in",
  "service": "my-service",
  "module": "auth",
  "fields": "{\"user_id\":\"user123\",\"ip_address\":\"192.168.1.100\",\"login_method\":\"oauth\",\"success\":true}"
}
```

### Automatic Redaction

Sensitive fields are automatically redacted:

```rust
logger.info_with("User registration", |e| {
    e.field("email", "user@example.com");        // Partially redacted: ****.com
    e.field("password", "secret123");            // Fully redacted: [REDACTED]
    e.field("api_key", "sk_live_abc123xyz");     // Fully redacted: [REDACTED]
    e.field("phone", "555-123-4567");            // Partially redacted: ****4567
});
```

## Context Propagation

Context fields (`trace_id`, `span_id`, `request_id`, `user_id`, `tenant_id`) are automatically included in all logs.

### Creating Context

```rust
use shared_logging::{ContextBuilder, Logger};

// Build context
let context = ContextBuilder::new()
    .trace_id("abc123def456")           // OpenTelemetry trace ID
    .span_id("span789")                 // OpenTelemetry span ID
    .generate_request_id()               // Auto-generate request ID
    .user_id("user123")                  // User identifier
    .tenant_id("tenant001")              // Tenant identifier
    .build();

// Create logger with context
let logger = Logger::with_context("api", context);
logger.info("Processing request");  // All logs include context fields
```

### Updating Context

```rust
let mut logger = Logger::new("api");

// Set context
let context = ContextBuilder::new()
    .generate_request_id()
    .user_id("user123")
    .build();
logger.set_context(context);

// Or merge additional context
let additional_context = ContextBuilder::new()
    .tenant_id("tenant001")
    .build();
logger.merge_context(additional_context);
```

## Error Logging

### Simple Error Logging

```rust
let result: Result<(), String> = Err("Something went wrong".to_string());

if let Err(e) = result {
    logger.log_error("Operation failed", &e);
}
```

### Error with Context

```rust
use std::error::Error;

fn process_user(user_id: &str) -> Result<(), Box<dyn Error>> {
    // ... your code ...
    Err("Database error".into())
}

// Log error with context
match process_user("user123") {
    Ok(_) => logger.info("User processed successfully"),
    Err(e) => {
        logger.error_with("Failed to process user", |e| {
            e.field("user_id", "user123");
            e.field("operation", "user_processing");
            e.error(e.as_ref());
        });
    }
}
```

**Output:**
```json
{
  "timestamp": "2024-01-15T10:30:45.123Z",
  "level": "error",
  "message": "Failed to process user",
  "service": "my-service",
  "module": "api",
  "fields": "{\"user_id\":\"user123\",\"operation\":\"user_processing\",\"error\":{\"error_type\":\"...\",\"error_message\":\"Database error\",\"error_stack\":[...]}}"
}
```

## HTTP Middleware

### Using with Axum

```rust
use axum::{Router, routing::get};
use shared_logging::init_logger;
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;

#[tokio::main]
async fn main() {
    init_logger("http-server", "info").unwrap();
    
    let app = Router::new()
        .route("/", get(handler))
        .layer(
            ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
        );
    
    // ... start server
}
```

### Manual Request ID Handling

```rust
use axum::extract::Request;
use shared_logging::{Logger, ContextBuilder};

async fn handler(request: Request) -> Response {
    // Extract or generate request ID
    let request_id = request.headers()
        .get("x-request-id")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string())
        .unwrap_or_else(|| ContextBuilder::new().generate_request_id().build().request_id.unwrap());
    
    // Create context with request ID
    let context = ContextBuilder::new()
        .request_id(&request_id)
        .build();
    
    let logger = Logger::with_context("handler", context);
    logger.info("Processing request");
    
    // Your handler logic
}
```

## OpenTelemetry Integration

### Setup

```rust
use shared_logging::{init_logger, otel};

#[cfg(feature = "otel")]
fn setup_otel() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize OpenTelemetry
    otel::init_otel_tracing("my-service")?;
    
    // Initialize logger
    init_logger("my-service", "info")?;
    
    Ok(())
}
```

### Extract Context from OTel Span

```rust
use shared_logging::otel;

#[cfg(feature = "otel")]
fn log_with_otel_context() {
    // Extract context from current OTel span
    let context = otel::extract_context_from_otel();
    
    let logger = Logger::with_context("api", context);
    logger.info("Logging with OTel context");
}
```

## Configuration

### Environment Variables

```bash
# Set log level
export RUST_LOG=info

# Set log level for specific modules
export RUST_LOG=my_service=debug,shared_logging=info

# Set log level for all dependencies
export RUST_LOG=debug
```

### Programmatic Configuration

The logger is configured at initialization:

```rust
// Set default level to "debug"
init_logger("my-service", "debug")?;

// Can be overridden by RUST_LOG environment variable
```

## Complete Example

```rust
use shared_logging::{init_logger, Logger, ContextBuilder};

fn main() {
    // 1. Initialize logger once at startup
    init_logger("my-service", "info").unwrap();
    
    // 2. Create logger instances
    let logger = Logger::new("main");
    logger.info("Application starting");
    
    // 3. Process a request with context
    let context = ContextBuilder::new()
        .generate_request_id()
        .user_id("user123")
        .build();
    
    let api_logger = Logger::with_context("api", context);
    
    // 4. Log with fields
    api_logger.info_with("Processing request", |e| {
        e.field("endpoint", "/api/users");
        e.field("method", "GET");
    });
    
    // 5. Handle errors
    match process_request() {
        Ok(_) => api_logger.info("Request processed successfully"),
        Err(e) => api_logger.log_error("Request failed", &e),
    }
}

fn process_request() -> Result<(), String> {
    // Your logic here
    Ok(())
}
```

## Running Examples

The crate includes example code you can run:

```bash
# Basic usage
cargo run --example basic_usage

# HTTP server example
cargo run --example http_server

# Error handling example
cargo run --example error_handling
```

## Best Practices

1. **Initialize once**: Call `init_logger()` only once at application startup
2. **Use module names**: Create logger instances with descriptive module names
3. **Propagate context**: Use context for request-scoped logging
4. **Structured fields**: Use `*_with()` methods to add structured fields
5. **Error logging**: Use `log_error()` for proper error formatting
6. **Redaction**: Trust the library to redact sensitive data automatically

## Troubleshooting

### Logs not appearing

- Check `RUST_LOG` environment variable
- Ensure `init_logger()` was called
- Verify log level is appropriate

### Context not propagating

- Ensure context is set on the logger instance
- Check that you're using the same logger instance within a request

### Redaction not working

- Verify field names match redaction patterns (password, token, etc.)
- Check that values match PII/secret patterns