Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ All significant changes to this project will be documented in this file.

## Unreleased

### Breaking changes

* Replace `TextLayout::no_color` with `TextLayout::{color, color_for}` in `logforth-layout-text`, and change `TextLayout::new` (and `Default`) to omit ANSI colors by default; pass `.color(true)` for unconditional ANSI coloring or `.color_for(&stream)` to resolve coloring against a target stream, `NO_COLOR`, and `CLICOLOR_FORCE`.

### Improvements

* Resolve default `TextLayout` coloring in `logforth::starter_log::{stdout, stderr, testing}` against the target standard stream, `NO_COLOR`, and `CLICOLOR_FORCE` instead of emitting ANSI escape sequences unconditionally when redirected.

## v0.31.0

| Crate | Version |
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use logforth::layout::TextLayout;

fn main() {
let logger = logforth::builder()
.dispatch(|d| d.append(Stderr::new().with_layout(TextLayout::new())))
.dispatch(|d| d.append(Stderr::new().with_layout(TextLayout::new().color_for(&std::io::stderr()))))
.build();

logforth::info!(logger, ["port" = 8080, "tls" = false], "server listening");
Expand Down Expand Up @@ -79,7 +79,7 @@ fn main() -> Result<(), logforth::Error> {
.rollover_daily()
.build()?;

let stderr = Stderr::new().with_layout(TextLayout::new());
let stderr = Stderr::new().with_layout(TextLayout::new().color_for(&std::io::stderr()));

let logger = logforth::builder()
.dispatch(|d| d.append(json_file))
Expand Down Expand Up @@ -158,7 +158,7 @@ Runnable end-to-end scenarios live in the [`examples`](examples) workspace crate
| | [`OpentelemetryLog`] | `append-opentelemetry` | Export structured OpenTelemetry log batches with trace correlation. |
| | [`FastraceEvent`] | `append-fastrace` | Attach log records as events on active [`fastrace`] spans. |
| Layouts | [`PlainTextLayout`] | *built-in* | Minimal uncolored single-line text output. |
| | [`TextLayout`] | `layout-text` | Human-readable single-line text with timestamps and ANSI colors. |
| | [`TextLayout`] | `layout-text` | Human-readable single-line text with timestamps and optional ANSI colors. |
| | [`LogfmtLayout`] | `layout-logfmt` | Single-line `key=value` [`logfmt`] output. |
| | [`JsonLayout`] | `layout-json` | Single-line JSON output. |
| | [`GoogleCloudLoggingLayout`] | `layout-google-cloud-logging` | Structured JSON output for Google Cloud Logging. |
Expand Down
2 changes: 1 addition & 1 deletion appenders/syslog/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ fn build_native_tls_syslog(connector: TlsConnector) -> Result<SocketSyslog, logf

- **Syslog header**: `SocketSyslog` formats the RFC 3164 or RFC 5424 header in Rust from `Record::time()` and `SyslogContext` (in `SyslogFormat::Rfc5424`, `MSGID` and `STRUCTURED-DATA` are emitted as `-`), whereas `PosixSyslog` (`cfg(unix)`, `PosixSyslog::new()` or `PosixSyslogBuilder::new()` with `.facility(...)` and `.layout(...)`) delegates header generation (`<PRI>`, OS call-time timestamp, `ident`, and `[pid]`) to `libc::syslog` using process-wide `posix_openlog` / `posix_closelog` state (`PosixSyslogOptions::PID`, etc.). Because `syslog(3)` stamps the OS clock at call time, buffered `Async` dispatch records the `syslog(3)` call time rather than preserving `Record::time()`.
- **Payload-only default**: Without `SocketSyslogBuilder::layout` or `PosixSyslogBuilder::layout`, both `SocketSyslog` and `PosixSyslog` emit only `Record::payload()` as the message body (`MSG`); `Record::key_values()`, `Diagnostic` entries, and source location metadata (`module_path`, `file`, `line`, `column`) are omitted.
- **Configuring a `Layout`**: Attach `.layout(...)` when structured fields or source locations should be rendered into `MSG`, such as `JsonLayout::new()`, `LogfmtLayout::new()`, or `TextLayout::new().no_timestamp().no_color()` (disabling `TextLayout`'s timestamp and ANSI color escapes avoids duplicating the syslog header timestamp or writing terminal escape sequences to syslog).
- **Configuring a `Layout`**: Attach `.layout(...)` when structured fields or source locations should be rendered into `MSG`, such as `JsonLayout::new()`, `LogfmtLayout::new()`, or `TextLayout::new().no_timestamp()` (disabling `TextLayout`'s timestamp avoids duplicating the syslog header timestamp, while its uncolored default avoids writing terminal escape sequences to syslog).

Each `Level` maps to one of the 8 syslog severities following the OpenTelemetry severity mapping:

Expand Down
4 changes: 2 additions & 2 deletions appenders/syslog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@
//! They omit [`Record::key_values`](logforth_core::record::Record::key_values),
//! [`Diagnostic`](logforth_core::Diagnostic) entries, and source location. Configure `.layout(...)`
//! with `JsonLayout::new()` or `LogfmtLayout::new()` for structured output. To include those
//! fields in text without repeating the header timestamp or emitting ANSI color escapes, use
//! `TextLayout::new().no_timestamp().no_color()`.
//! fields in uncolored text without repeating the header timestamp, use
//! `TextLayout::new().no_timestamp()`.
//!
//! Each [`Level`](logforth_core::record::Level) maps to a [`Severity`] and numeric code.
//!
Expand Down
4 changes: 2 additions & 2 deletions appenders/syslog/src/posix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ impl PosixSyslogBuilder {
/// The default body contains only [`Record::payload`].
///
/// Use `JsonLayout::new()` or `LogfmtLayout::new()` for structured fields and source locations.
/// Use `TextLayout::new().no_timestamp().no_color()` to include those fields in text without
/// repeating the header timestamp or emitting ANSI color escapes.
/// Use `TextLayout::new().no_timestamp()` to include those fields in uncolored text without
/// repeating the header timestamp.
pub fn layout(mut self, layout: impl Into<Box<dyn Layout>>) -> Self {
self.appender.layout = Some(layout.into());
self
Expand Down
2 changes: 1 addition & 1 deletion examples/src/dynamic_filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ fn main() {
d.filter(DebugRequestFilter)
.filter(LevelFilter::MoreSevereEqual(Level::Info))
.diagnostic(ThreadLocalDiagnostic::new())
.append(Stdout::new().with_layout(TextLayout::new().no_color().utc()))
.append(Stdout::new().with_layout(TextLayout::new().utc()))
})
.build();

Expand Down
4 changes: 2 additions & 2 deletions examples/src/library_logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ fn main() {
.dispatch(|d| {
d.filter(LevelFilter::MoreSevereEqual(Level::Info))
.diagnostic(StaticDiagnostic::new([("client", "api")]))
.append(Stdout::new().with_layout(TextLayout::new().no_color().utc()))
.append(Stdout::new().with_layout(TextLayout::new().utc()))
})
.build();
http_client::Client::new()
Expand All @@ -80,7 +80,7 @@ fn main() {
.dispatch(|d| {
d.filter(LevelFilter::MoreSevereEqual(Level::Debug))
.diagnostic(StaticDiagnostic::new([("client", "debug")]))
.append(Stdout::new().with_layout(TextLayout::new().no_color().utc()))
.append(Stdout::new().with_layout(TextLayout::new().utc()))
})
.build();
http_client::Client::new()
Expand Down
4 changes: 3 additions & 1 deletion examples/src/multi_logger_pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ mod logging {
.append(Stdout::new().with_layout(JsonLayout::new().utc()))
.build()?,
);
let alert_sink = Arc::new(Stderr::new().with_layout(TextLayout::new().no_color().utc()));
let alert_sink = Arc::new(
Stderr::new().with_layout(TextLayout::new().color_for(&std::io::stderr()).utc()),
);
let general_filter = RustLogFilterBuilder::from_default_env_or("info")?.build();
let _ = LOGGERS.set(Loggers {
general: channel_logger("general", general_filter, &json_sink, &alert_sink),
Expand Down
2 changes: 1 addition & 1 deletion examples/src/per_module_logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ mod logging {
use logforth::record::LevelFilter;

static SINK: LazyLock<Arc<Stdout>> =
LazyLock::new(|| Arc::new(Stdout::new().with_layout(TextLayout::new().no_color().utc())));
LazyLock::new(|| Arc::new(Stdout::new().with_layout(TextLayout::new().utc())));

pub fn module_logger(default_level: Level) -> Logger {
let filter = match std::env::var("RUST_LOG") {
Expand Down
27 changes: 14 additions & 13 deletions layouts/text/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use logforth_core::append::Stderr;
use logforth_layout_text::TextLayout;

let logger = LoggerBuilder::new()
.dispatch(|d| d.append(Stderr::new().with_layout(TextLayout::new().utc())))
.dispatch(|d| d.append(Stderr::new().with_layout(TextLayout::new().color_for(&std::io::stderr()).utc())))
.build();

logforth_core::info!(logger, ["port" = 8080], "server listening");
Expand All @@ -32,18 +32,19 @@ By default, `TextLayout` renders an RFC 3339 timestamp with microsecond precisio
2024-08-11T22:44:57.172276+08:00 INFO app::http: server.rs:53:5 server listening port=8080
```

| Method | Effect |
| :----------------------------------- | :---------------------------------------------------------------------------------- |
| `fatal_color(c)` .. `trace_color(c)` | Customizes the foreground [`Color`] for all 4 levels in that severity band. |
| `no_color()` | Disables ANSI coloring (recommended when formatting into files or pipes). |
| `no_module_path()` | Omits the `{module_path}:` segment from formatted records. |
| `no_file()` | Omits the `{filename}:{line}:{column}` segment from formatted records. |
| `no_timestamp()` | Omits the timestamp segment from formatted records. |
| `precision(p)` | Sets fractional-second digits (`0`..=`9`, default: `6` for microseconds). |
| `timezone(tz)` | Sets the [`TimeZone`] for numeric `+HH:MM` offsets (default: `TimeZone::system()`). |
| `utc()` | Formats timestamps in UTC with the `Z` suffix instead of a numeric offset. |

`anstyle` and `jiff` are re-exported at `logforth_layout_text::anstyle` and `logforth_layout_text::jiff` so callers do not need direct Cargo dependencies to configure [`Color`] or [`TimeZone`]. By default, `TextLayout` emits ANSI colors deterministically; pass `no_color()` when targeting file sinks or non-terminal streams (for example, `if !std::io::stderr().is_terminal() { layout = layout.no_color(); }`).
| Method | Effect |
| :----------------------------------- | :-------------------------------------------------------------------------------------- |
| `fatal_color(c)` .. `trace_color(c)` | Customizes the foreground [`Color`] for all 4 levels in that severity band. |
| `color(enabled)` | Enables or disables ANSI coloring of the severity label (default: `false`). |
| `color_for(stream)` | Resolves ANSI coloring once for `stream` (`NO_COLOR` > `CLICOLOR_FORCE` > `IsTerminal`). |
| `no_module_path()` | Omits the `{module_path}:` segment from formatted records. |
| `no_file()` | Omits the `{filename}:{line}:{column}` segment from formatted records. |
| `no_timestamp()` | Omits the timestamp segment from formatted records. |
| `precision(p)` | Sets fractional-second digits (`0`..=`9`, default: `6` for microseconds). |
| `timezone(tz)` | Sets the [`TimeZone`] for numeric `+HH:MM` offsets (default: `TimeZone::system()`). |
| `utc()` | Formats timestamps in UTC with the `Z` suffix instead of a numeric offset. |

`anstyle` and `jiff` are re-exported at `logforth_layout_text::anstyle` and `logforth_layout_text::jiff` so callers do not need direct Cargo dependencies to configure [`Color`] or [`TimeZone`]. `TextLayout` omits ANSI escape sequences by default so file, buffer, and pipe sinks stay clean; enable coloring explicitly with `color(true)` or resolve it for a target stream at construction time with `color_for(&stream)` (`NO_COLOR` > `CLICOLOR_FORCE` > `stream.is_terminal()`).

[`Color`]: https://docs.rs/anstyle/1.0.14/anstyle/enum.Color.html
[`TimeZone`]: https://docs.rs/jiff/1.0.2/jiff/tz/struct.TimeZone.html
Expand Down
Loading
Loading