rusty-rich 0.3.0

Rich text and beautiful formatting in the terminal — a Rust port of Python's Rich library
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
# Logging

`RichHandler` provides Rich-formatted log output by integrating with the `log` crate. It formats log records with colored levels, timestamps, source locations, and optional console markup, exactly like Python Rich's `RichHandler`.

```rust
use rusty_rich::RichHandler;

let mut handler = RichHandler::new();
handler.emit(&record);
```

---

## RichHandler

The core struct. It holds a `Console` instance and a set of formatting flags that control the rendered output of every log record.

### Constructor

```rust
pub fn new() -> Self
```

Creates a handler with default settings:

| Field | Default | Description |
|-------|---------|-------------|
| `show_time` | `true` | Prepend a dim `[HH:MM:SS]` timestamp. |
| `show_level` | `true` | Prepend a colored, space-padded level name (e.g. `INFO `). |
| `show_path` | `true` | Append a dim italic `[file:line]` location. |
| `enable_link_path` | `false` | Render `file:line` as a clickable terminal hyperlink. |
| `markup` | `false` | Interpret `[style]` markup tags inside log messages. |

```rust
// Default handler — most common starting point
let mut handler = RichHandler::new();
```

---

### Fields

All configuration fields are public and can be set directly after construction.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `console` | `Console` | `Console::new()` | The console used for output at emit time. |
| `show_time` | `bool` | `true` | Show a dim `[HH:MM:SS]` before each record. |
| `show_level` | `bool` | `true` | Show the log level name with level-specific colour. |
| `show_path` | `bool` | `true` | Show the source file and line number. |
| `enable_link_path` | `bool` | `false` | Emit `file:line` as an OSC-8 hyperlink. |
| `markup` | `bool` | `false` | Parse Rich markup tags in the message body. |
| `highlighter` | `ReprHighlighter` | `ReprHighlighter::new()` | Highlighter applied to the message text. |

```rust
let mut handler = RichHandler::new();
handler.show_time = false;         // suppress timestamps
handler.markup = true;             // enable console markup in messages
handler.enable_link_path = true;   // clickable file:line links
```

---

### show_time

When `true`, a dimmed timestamp is prepended to every log record in the format `[HH:MM:SS]`.

```rust
let mut handler = RichHandler::new();
handler.show_time = true;    // default

// Disable timestamps for cleaner output in pipelines
handler.show_time = false;
```

Output with `show_time: true`:

```
[14:30:01] INFO  Server listening on 0.0.0.0:8080 [src/main.rs:42]
```

The timestamp uses the local system clock via `chrono::Local::now()` and is formatted with `Style::new().dim(true)` so it recedes into the background.

---

### show_level

When `true`, the log level name is rendered in a level-specific colour, right-padded to five characters for alignment.

| Level | Colour | Style |
|-------|--------|-------|
| `ERROR` | Red | Bold |
| `WARN` | Yellow | Normal |
| `INFO` | Green | Normal |
| `DEBUG` | Blue | Normal |
| `TRACE` | Bright black | Normal |

```rust
let mut handler = RichHandler::new();
handler.show_level = true;    // default

handler.show_level = false;   // suppress level labels
```

Output showing level-coloured prefixes:

```
ERROR Server crashed: out of memory   [src/main.rs:88]
WARN  Disk usage above 90%            [src/monitor.rs:34]
INFO  Server listening on 0.0.0.0:8080 [src/main.rs:42]
DEBUG Loaded config in 12ms           [src/config.rs:15]
TRACE Entering parse_config           [src/config.rs:10]
```

The colour mapping is defined by the `style_level()` function, which returns a `Style` for each `log::Level` variant.

---

### show_path

When `true`, the source file and line number are appended in dim italic, enclosed in square brackets.

```rust
let mut handler = RichHandler::new();
handler.show_path = true;    // default

handler.show_path = false;   // suppress source location
```

Output with `show_path: true`:

```
INFO  Request processed in 4ms [src/routes/user.rs:142]
```

The location uses the `file!()` and `line!()` macros provided by the `log` crate's `Record`. When either value is missing, the location suffix is omitted entirely.

---

### enable_link_path

When `true`, the `file:line` portion is emitted as an OSC-8 terminal hyperlink, making it clickable in terminals that support hyperlinks (kitty, iTerm2, WezTerm, Windows Terminal, etc.).

```rust
let mut handler = RichHandler::new();
handler.enable_link_path = true;
```

This has no effect when `show_path` is `false`.

---

### markup

When `true`, the message body is parsed as Rich console markup, allowing inline styling inside log messages.

```rust
let mut handler = RichHandler::new();
handler.markup = true;
```

With `markup: true`, the following log call:

```rust
log::info!("[bold green]Connected[/bold green] to [underline]database[/underline]");
```

Renders the log message with bold green text for "Connected" and underlined text for "database".

**Important:** When `markup` is `false` (the default), markup tags are rendered literally as plain text — the `[]` brackets are not interpreted. Set `markup: true` only when you control the log messages and trust their content, because user-supplied data containing bracket characters could produce unexpected styling.

---

### highlighter

A `ReprHighlighter` instance that applies syntax-highlighting-style colouring to the message text. The highlighter is applied to the message before any markup parsing (if `markup` is also enabled).

```rust
use rusty_rich::{RichHandler, ReprHighlighter};

let mut handler = RichHandler::new();
handler.highlighter = ReprHighlighter::new();
```

---

## emit()

The primary method that accepts a `log::Record` and writes it to the console.

```rust
pub fn emit(&mut self, record: &log::Record)
```

```rust
handler.emit(&record);
```

`emit` calls `render()` to build the formatted string, writes it to the console's output via `writeln!`, and flushes the output handle. The output goes to `self.console.file`, which by default is `std::io::stdout`.

---

## render()

Produces the formatted string for a single log record without writing it. Useful when you need to capture or further transform the output.

```rust
pub fn render(
    &self,
    level: log::Level,
    message: &str,
    module_path: Option<&str>,
    file: Option<&str>,
    line: Option<u32>,
) -> String
```

```rust
let output = handler.render(
    log::Level::Info,
    "Server started",
    Some("my_app"),
    Some("src/main.rs"),
    Some(42),
);
assert!(output.contains("INFO"));
assert!(output.contains("Server started"));
```

The output format follows this order:

```
[HH:MM:SS] LEVEL  Message text [file:line]
```

Each section is conditionally included based on the handler's `show_time`, `show_level`, and `show_path` flags.

---

## style_level()

A standalone helper that returns the `Style` associated with a given log level.

```rust
pub fn style_level(level: log::Level) -> Style
```

```rust
use rusty_rich::logging::style_level;
use rusty_rich::Style;
use log::Level;

let err_style: Style = style_level(Level::Error);
// err_style is bold red
```

| Level | Style |
|-------|-------|
| `Error` | Bold red |
| `Warn` | Yellow |
| `Info` | Green |
| `Debug` | Blue |
| `Trace` | Bright black |

---

## Integration with the `log` crate

`RichHandler` works with Rust's standard `log` crate facade. The typical integration pattern is to create a `RichHandler`, wrap it in a `log::LevelFilter`, and install it as the global logger.

### Basic setup — manual dispatch

```rust
use log::{LevelFilter, Record};
use rusty_rich::RichHandler;

fn main() {
    let mut handler = RichHandler::new();

    // Log a record directly
    log::info!("Application started");
    log::warn!("Configuration file not found, using defaults");
    log::error!("Failed to bind socket: address in use");
}
```

### Global logger setup

For use as the application-wide logger, implement `log::Log`:

```rust
use log::{LevelFilter, Log, Record, SetLoggerError};
use rusty_rich::RichHandler;
use std::sync::Mutex;

pub struct RichLogger {
    handler: Mutex<RichHandler>,
}

impl RichLogger {
    pub fn new() -> Self {
        Self {
            handler: Mutex::new(RichHandler::new()),
        }
    }

    pub fn init(level: LevelFilter) -> Result<(), SetLoggerError> {
        let logger = Box::new(Self::new());
        log::set_boxed_logger(logger)?;
        log::set_max_level(level);
        Ok(())
    }
}

impl Log for RichLogger {
    fn enabled(&self, _metadata: &log::Metadata) -> bool {
        true
    }

    fn log(&self, record: &Record) {
        if let Ok(mut handler) = self.handler.lock() {
            handler.emit(record);
        }
    }

    fn flush(&self) {
        // Handler flushes after every write
    }
}

fn main() {
    RichLogger::init(LevelFilter::Debug)
        .expect("Failed to install logger");

    log::info!("Rich logging is ready");
    log::debug!("Debug output is enabled");
}
```

---

### Full example — customised logger

```rust
use log::{LevelFilter, Log, Record, SetLoggerError};
use rusty_rich::RichHandler;
use std::sync::Mutex;

struct RichLogger {
    handler: Mutex<RichHandler>,
}

impl RichLogger {
    fn new() -> Self {
        let mut handler = RichHandler::new();
        // Enable markup in log messages
        handler.markup = true;
        // Show clickable file:line links
        handler.enable_link_path = true;
        Self {
            handler: Mutex::new(handler),
        }
    }

    fn init(level: LevelFilter) -> Result<(), SetLoggerError> {
        let logger = Box::new(Self::new());
        log::set_boxed_logger(logger)?;
        log::set_max_level(level);
        Ok(())
    }
}

impl Log for RichLogger {
    fn enabled(&self, _metadata: &log::Metadata) -> bool {
        true
    }

    fn log(&self, record: &Record) {
        if let Ok(mut handler) = self.handler.lock() {
            handler.emit(record);
        }
    }

    fn flush(&self) {}
}

fn main() {
    // Install as global logger
    RichLogger::init(LevelFilter::Info)
        .expect("Failed to install Rich logger");

    // These messages are rendered with Rich formatting
    log::info!("[bold]Server[/bold] listening on [cyan]0.0.0.0:8080[/cyan]");
    log::warn!("Disk usage at [yellow]92%[/yellow] — consider cleaning up");
    log::error!("Connection pool exhausted");
}
```

---

### Minimal example — inline handler

When a global logger is not required, a `RichHandler` can be used directly:

```rust
use log::Record;
use rusty_rich::RichHandler;

fn main() {
    let mut handler = RichHandler::new();

    // Simulate log records by calling emit directly
    handler.emit(&Record::builder()
        .args(format_args!("Hello from Rich logging"))
        .level(log::Level::Info)
        .module_path(Some("my_app"))
        .file(Some("src/main.rs"))
        .line(Some(10))
        .build());
}
```

---

## Output examples

Default settings (`show_time: true`, `show_level: true`, `show_path: true`):

```
[14:30:01] ERROR Server crashed: out of memory   [src/main.rs:88]
[14:30:01] WARN  Disk usage above 90%            [src/monitor.rs:34]
[14:30:02] INFO  Server listening on 0.0.0.0:8080 [src/main.rs:42]
[14:30:03] DEBUG Loaded config in 12ms           [src/config.rs:15]
[14:30:03] TRACE Entering parse_config           [src/config.rs:10]
```

With `show_time: false`:

```
ERROR Server crashed: out of memory   [src/main.rs:88]
WARN  Disk usage above 90%            [src/monitor.rs:34]
INFO  Server listening on 0.0.0.0:8080 [src/main.rs:42]
```

With `show_path: false`:

```
[14:30:01] ERROR Server crashed: out of memory
[14:30:01] WARN  Disk usage above 90%
[14:30:02] INFO  Server listening on 0.0.0.0:8080
```

With `show_level: false` and `show_path: false`:

```
[14:30:01] Server crashed: out of memory
[14:30:01] Disk usage above 90%
[14:30:02] Server listening on 0.0.0.0:8080
```

---

## Import paths

```rust
use rusty_rich::RichHandler;              // The handler struct
use rusty_rich::logging::style_level;     // Style helper for log levels
use rusty_rich::ReprHighlighter;          // Default highlighter
```