diff --git a/CHANGELOG.md b/CHANGELOG.md index cd0f165e..92efb2a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 | diff --git a/README.md b/README.md index 6de12db5..99f509c7 100644 --- a/README.md +++ b/README.md @@ -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"); @@ -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)) @@ -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. | diff --git a/appenders/syslog/README.md b/appenders/syslog/README.md index d0959b43..4c5c23c0 100644 --- a/appenders/syslog/README.md +++ b/appenders/syslog/README.md @@ -121,7 +121,7 @@ fn build_native_tls_syslog(connector: TlsConnector) -> Result`, 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: diff --git a/appenders/syslog/src/lib.rs b/appenders/syslog/src/lib.rs index c339045a..e25f5277 100644 --- a/appenders/syslog/src/lib.rs +++ b/appenders/syslog/src/lib.rs @@ -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. //! diff --git a/appenders/syslog/src/posix.rs b/appenders/syslog/src/posix.rs index 2a69b51e..fea52aec 100644 --- a/appenders/syslog/src/posix.rs +++ b/appenders/syslog/src/posix.rs @@ -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>) -> Self { self.appender.layout = Some(layout.into()); self diff --git a/examples/src/dynamic_filter.rs b/examples/src/dynamic_filter.rs index f5e440b4..b6bb6956 100644 --- a/examples/src/dynamic_filter.rs +++ b/examples/src/dynamic_filter.rs @@ -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(); diff --git a/examples/src/library_logger.rs b/examples/src/library_logger.rs index b47558b6..a373df33 100644 --- a/examples/src/library_logger.rs +++ b/examples/src/library_logger.rs @@ -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() @@ -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() diff --git a/examples/src/multi_logger_pipeline.rs b/examples/src/multi_logger_pipeline.rs index 29c46a38..2b206f92 100644 --- a/examples/src/multi_logger_pipeline.rs +++ b/examples/src/multi_logger_pipeline.rs @@ -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), diff --git a/examples/src/per_module_logger.rs b/examples/src/per_module_logger.rs index 8e7823dd..5de94289 100644 --- a/examples/src/per_module_logger.rs +++ b/examples/src/per_module_logger.rs @@ -32,7 +32,7 @@ mod logging { use logforth::record::LevelFilter; static SINK: LazyLock> = - 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") { diff --git a/layouts/text/README.md b/layouts/text/README.md index 9cd79565..ff8fe1d2 100644 --- a/layouts/text/README.md +++ b/layouts/text/README.md @@ -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"); @@ -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 diff --git a/layouts/text/src/lib.rs b/layouts/text/src/lib.rs index f7e00efa..4b31a3ba 100644 --- a/layouts/text/src/lib.rs +++ b/layouts/text/src/lib.rs @@ -17,8 +17,8 @@ //! [`TextLayout`] implements [`Layout`] by rendering: //! - an RFC 3339 timestamp with configurable fractional-second [`TextLayout::precision`] and //! timezone offset or UTC `Z` suffix (unless hidden with [`TextLayout::no_timestamp`]); -//! - the right-aligned 6-character severity name, colored per severity band via [`anstyle`] unless -//! [`TextLayout::no_color`] is set; +//! - the right-aligned 6-character severity name, uncolored by default, with optional per-band ANSI +//! colors enabled by [`TextLayout::color`] or resolved by [`TextLayout::color_for`]; //! - the module path (unless unset or hidden with [`TextLayout::no_module_path`]); //! - the source location as `filename:line:column`, defaulting an unset line or column to `0` //! (omitted when the filename is unset or [`TextLayout::no_file`] is set); @@ -35,7 +35,7 @@ //! use logforth_core::append::Testing; //! use logforth_layout_text::TextLayout; //! -//! let layout = TextLayout::new().utc().no_color(); +//! let layout = TextLayout::new().utc().color_for(&std::io::stderr()); //! let logger = LoggerBuilder::new() //! .dispatch(|d| d.append(Testing::new().with_layout(layout))) //! .build(); @@ -49,8 +49,10 @@ pub extern crate anstyle; pub extern crate jiff; +use std::ffi::OsStr; use std::fmt; use std::fmt::Write; +use std::io; use anstyle::AnsiColor; use anstyle::Color; @@ -81,13 +83,12 @@ use logforth_core::record::Record; /// /// # Coloring /// -/// Customize per-band foreground colors with [`TextLayout::fatal_color`], -/// [`TextLayout::error_color`], [`TextLayout::warn_color`], [`TextLayout::info_color`], -/// [`TextLayout::debug_color`], and [`TextLayout::trace_color`]. +/// Severity labels are uncolored by default. Use [`TextLayout::color`] to set coloring explicitly +/// or [`TextLayout::color_for`] to resolve it for an output stream. The last call wins. /// -/// By default, severity labels are colored with [`anstyle`]. Call [`TextLayout::no_color`] when -/// attaching `TextLayout` to file sinks or non-terminal streams so ANSI escape sequences are not -/// emitted. +/// Customize the palette independently of whether coloring is enabled with +/// [`TextLayout::fatal_color`], [`TextLayout::error_color`], [`TextLayout::warn_color`], +/// [`TextLayout::info_color`], [`TextLayout::debug_color`], and [`TextLayout::trace_color`]. /// /// # Source Location and Timestamps /// @@ -111,12 +112,15 @@ use logforth_core::record::Record; /// use logforth_layout_text::TextLayout; /// use logforth_layout_text::anstyle::AnsiColor; /// -/// let layout = TextLayout::new().utc().info_color(AnsiColor::Cyan); +/// let layout = TextLayout::new() +/// .utc() +/// .color(true) +/// .info_color(AnsiColor::Cyan); /// ``` #[derive(Debug, Clone)] pub struct TextLayout { colors: LevelColor, - no_color: bool, + color: bool, no_module_path: bool, no_file: bool, no_timestamp: bool, @@ -131,12 +135,12 @@ impl Default for TextLayout { } impl TextLayout { - /// Creates a new [`TextLayout`] using default severity colors, microsecond timestamp precision, - /// and the system timezone. + /// Creates a new [`TextLayout`] with uncolored severity labels, microsecond timestamp + /// precision, and the system timezone. pub fn new() -> Self { Self { colors: LevelColor::default(), - no_color: false, + color: false, no_module_path: false, no_file: false, no_timestamp: false, @@ -147,8 +151,6 @@ impl TextLayout { /// Sets the foreground color for fatal levels (`Fatal`..=`Fatal4`). Defaults to /// [`AnsiColor::BrightRed`]. - /// - /// Has no effect if [`TextLayout::no_color`] is set. pub fn fatal_color(mut self, color: impl Into) -> Self { self.colors.fatal = color.into(); self @@ -156,8 +158,6 @@ impl TextLayout { /// Sets the foreground color for error levels (`Error`..=`Error4`). Defaults to /// [`AnsiColor::Red`]. - /// - /// Has no effect if [`TextLayout::no_color`] is set. pub fn error_color(mut self, color: impl Into) -> Self { self.colors.error = color.into(); self @@ -165,8 +165,6 @@ impl TextLayout { /// Sets the foreground color for warn levels (`Warn`..=`Warn4`). Defaults to /// [`AnsiColor::Yellow`]. - /// - /// Has no effect if [`TextLayout::no_color`] is set. pub fn warn_color(mut self, color: impl Into) -> Self { self.colors.warn = color.into(); self @@ -174,8 +172,6 @@ impl TextLayout { /// Sets the foreground color for info levels (`Info`..=`Info4`). Defaults to /// [`AnsiColor::Green`]. - /// - /// Has no effect if [`TextLayout::no_color`] is set. pub fn info_color(mut self, color: impl Into) -> Self { self.colors.info = color.into(); self @@ -183,8 +179,6 @@ impl TextLayout { /// Sets the foreground color for debug levels (`Debug`..=`Debug4`). Defaults to /// [`AnsiColor::Blue`]. - /// - /// Has no effect if [`TextLayout::no_color`] is set. pub fn debug_color(mut self, color: impl Into) -> Self { self.colors.debug = color.into(); self @@ -192,16 +186,27 @@ impl TextLayout { /// Sets the foreground color for trace levels (`Trace`..=`Trace4`). Defaults to /// [`AnsiColor::Magenta`]. - /// - /// Has no effect if [`TextLayout::no_color`] is set. pub fn trace_color(mut self, color: impl Into) -> Self { self.colors.trace = color.into(); self } - /// Disables ANSI coloring of the log level. - pub fn no_color(mut self) -> Self { - self.no_color = true; + /// Enables or disables ANSI coloring of severity labels regardless of stream or environment. + pub fn color(mut self, enabled: bool) -> Self { + self.color = enabled; + self + } + + /// Resolves ANSI coloring of severity labels for `stream` at the time of this call. + /// + /// A non-empty `NO_COLOR` disables color. Otherwise, a non-empty `CLICOLOR_FORCE` other than + /// `0` enables color. In all other cases, coloring follows [`io::IsTerminal::is_terminal`]. + pub fn color_for(mut self, stream: &impl io::IsTerminal) -> Self { + self.color = resolve_color( + stream.is_terminal(), + std::env::var_os("NO_COLOR").as_deref(), + std::env::var_os("CLICOLOR_FORCE").as_deref(), + ); self } @@ -313,10 +318,10 @@ impl TextLayout { let mut writer = FmtBuf(buf); let level = record.level().name(); - let style = if self.no_color { - Style::new() - } else { + let style = if self.color { self.colors.color_for(record.level()).on_default() + } else { + Style::new() }; write!(writer, "{style}{level:>6}{style:#}").map_err(make_error)?; @@ -362,6 +367,20 @@ impl Layout for TextLayout { } } +fn resolve_color( + is_terminal: bool, + no_color: Option<&OsStr>, + clicolor_force: Option<&OsStr>, +) -> bool { + if no_color.is_some_and(|v| !v.is_empty()) { + return false; + } + if clicolor_force.is_some_and(|v| !v.is_empty() && v != "0") { + return true; + } + is_terminal +} + /// Colors for different log levels. #[derive(Debug, Clone, Copy)] struct LevelColor { @@ -398,3 +417,32 @@ impl LevelColor { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resolves_color_for_terminal_and_environment() { + for is_terminal in [false, true] { + for no_color in [None, Some(""), Some("0"), Some("1")] { + for clicolor_force in [None, Some(""), Some("0"), Some("1")] { + let expected = match (no_color, clicolor_force) { + (Some("0" | "1"), _) => false, + (_, Some("1")) => true, + _ => is_terminal, + }; + assert_eq!( + resolve_color( + is_terminal, + no_color.map(OsStr::new), + clicolor_force.map(OsStr::new) + ), + expected, + "terminal={is_terminal}, NO_COLOR={no_color:?}, CLICOLOR_FORCE={clicolor_force:?}" + ); + } + } + } + } +} diff --git a/logforth/src/starter_log.rs b/logforth/src/starter_log.rs index 22882488..026ad051 100644 --- a/logforth/src/starter_log.rs +++ b/logforth/src/starter_log.rs @@ -33,6 +33,7 @@ use crate::append; use crate::builder; use crate::error::StderrErrorSink; use crate::filter::rustlog::RustLogFilterBuilder; +use crate::layout::TextLayout; mod sealed { pub trait Sealed {} @@ -161,13 +162,14 @@ pub fn testing() -> LogStarter { /// A single-sink preset builder for installing Logforth into the [`log`] facade. /// /// Uses [`RustLogFilterBuilder::from_default_env`] to read `RUST_LOG`, defaulting to `Error` when -/// unset. Formats records with [`TextLayout::default`](crate::layout::TextLayout::default) and -/// reports logging errors through [`StderrErrorSink`]. +/// unset. The default [`TextLayout`] resolves severity coloring at build time with +/// [`TextLayout::color_for`] using stdout for [`stdout`] and stderr for [`stderr`] and [`testing`]. +/// Reports logging errors through [`StderrErrorSink`]. #[derive(Debug)] pub struct LogStarter { sink: StarterSink, filter: Option>, - layout: Box, + layout: Option>, error_sink: Box, } @@ -176,7 +178,7 @@ impl LogStarter { Self { sink, filter: None, - layout: Box::new(crate::layout::TextLayout::default()), + layout: None, error_sink: Box::new(StderrErrorSink::default()), } } @@ -193,7 +195,7 @@ impl LogStarter { /// log::error!("This error will be logged to stderr."); /// ``` pub fn layout(mut self, layout: impl Into>) -> Self { - self.layout = layout.into(); + self.layout = Some(layout.into()); self } @@ -287,6 +289,12 @@ impl LogStarter { Box::new(builder.build()) } }; + let layout = layout.unwrap_or_else(|| match sink { + StarterSink::Stdout(_) => Box::new(TextLayout::new().color_for(&std::io::stdout())), + StarterSink::Stderr(_) | StarterSink::Testing(_) => { + Box::new(TextLayout::new().color_for(&std::io::stderr())) + } + }); let append = sink.into_append(layout); Ok(builder() .error_sink(error_sink) diff --git a/tests-integration/tests/layout_test/text.rs b/tests-integration/tests/layout_test/text.rs index b856c58e..44ced673 100644 --- a/tests-integration/tests/layout_test/text.rs +++ b/tests-integration/tests/layout_test/text.rs @@ -35,7 +35,7 @@ use tests_integration::render_layout; #[test] fn text_layout_omits_separator_for_empty_payloads() { - let layout = TextLayout::new().utc().no_color(); + let layout = TextLayout::new().utc(); let no_ts = layout.clone().no_timestamp(); let base = RecordBuilder::new().build(); let kvs = [(Key::new("port"), Value::u64(8080))]; @@ -88,7 +88,7 @@ fn text_layout_formats_timestamps_precisions_structured_fields_and_toggles() { .build(); // `timezone(TimeZone::UTC)` emits `+00:00`, whereas `utc()` emits `Z`, and the last call wins. - let base_offset_utc = TextLayout::new().timezone(TimeZone::UTC).no_color(); + let base_offset_utc = TextLayout::new().timezone(TimeZone::UTC); assert_eq!( render_layout(&base_offset_utc, &full, &diags), "2023-11-14T22:13:20.123456+00:00 INFO app::http: http.rs:42:7 server started port=8080 env=prod", @@ -124,7 +124,6 @@ fn text_layout_formats_timestamps_precisions_structured_fields_and_toggles() { let layout = TextLayout::default() .utc() .precision(precision) - .no_color() .no_module_path() .no_file(); assert_eq!( @@ -134,11 +133,7 @@ fn text_layout_formats_timestamps_precisions_structured_fields_and_toggles() { } // `no_timestamp()` omits both the timestamp and its trailing space without affecting alignment. - let no_ts = TextLayout::new() - .no_timestamp() - .no_color() - .no_module_path() - .no_file(); + let no_ts = TextLayout::new().no_timestamp().no_module_path().no_file(); assert_eq!( render_layout(&no_ts, &full, &()), " INFO server started port=8080" @@ -186,6 +181,9 @@ fn text_layout_formats_timestamps_precisions_structured_fields_and_toggles() { #[test] fn text_layout_colors_levels_by_severity_band() { let layout = TextLayout::new().no_timestamp(); + let message = RecordBuilder::new().payload(format_args!("msg")).build(); + assert_eq!(render_layout(&layout, &message, &()), " INFO msg"); + let colored = layout.clone().color(true); let custom = layout .clone() .fatal_color(AnsiColor::Red) @@ -194,10 +192,17 @@ fn text_layout_colors_levels_by_severity_band() { .info_color(AnsiColor::Cyan) .debug_color(AnsiColor::Magenta) .trace_color(AnsiColor::Blue); - let plain = custom.clone().no_color(); - let message = RecordBuilder::new().payload(format_args!("msg")).build(); + assert_eq!(render_layout(&custom, &message, &()), " INFO msg"); + let custom = custom.color(true); + let plain = custom.clone().color(false); + let custom_after = colored.clone().info_color(AnsiColor::Cyan); + if std::env::var_os("CLICOLOR_FORCE").is_none() { + let file_layout = colored.clone().color_for(&tempfile::tempfile().unwrap()); + assert_eq!(render_layout(&file_layout, &message, &()), " INFO msg"); + } for (layout, level, color) in [ - (&layout, Level::Info, AnsiColor::Green), + (&colored, Level::Info, AnsiColor::Green), + (&custom_after, Level::Info2, AnsiColor::Cyan), (&custom, Level::Fatal2, AnsiColor::Red), (&custom, Level::Error2, AnsiColor::Yellow), (&custom, Level::Warn2, AnsiColor::Green), @@ -232,7 +237,7 @@ fn text_layout_surfaces_out_of_range_timestamp_and_diagnostic_errors_without_pan .payload(format_args!("overflow")) .build(); - let layout = TextLayout::new().timezone(TimeZone::UTC).no_color(); + let layout = TextLayout::new().timezone(TimeZone::UTC); let mut buf = b"untouched".to_vec(); assert!(layout.format(&bad_ts_record, &(), &mut buf).is_err()); assert_eq!(buf, b"untouched"); diff --git a/tests-integration/tests/logforth_test/pipeline.rs b/tests-integration/tests/logforth_test/pipeline.rs index c4bbf57c..7f640500 100644 --- a/tests-integration/tests/logforth_test/pipeline.rs +++ b/tests-integration/tests/logforth_test/pipeline.rs @@ -127,9 +127,7 @@ fn native_macros_async_promotion_and_layout_module_reexports() { let layouts: [&dyn Layout; 3] = [ &JsonLayout::new().timezone(logforth::layout::json::jiff::tz::TimeZone::UTC), &LogfmtLayout::new().timezone(logforth::layout::logfmt::jiff::tz::TimeZone::UTC), - &TextLayout::new() - .no_color() - .timezone(logforth::layout::text::jiff::tz::TimeZone::UTC), + &TextLayout::new().timezone(logforth::layout::text::jiff::tz::TimeZone::UTC), ]; for layout in layouts { let mut buf = Vec::new(); diff --git a/tests-integration/tests/logforth_test/starter_log.rs b/tests-integration/tests/logforth_test/starter_log.rs index 701466b8..2fc79f3a 100644 --- a/tests-integration/tests/logforth_test/starter_log.rs +++ b/tests-integration/tests/logforth_test/starter_log.rs @@ -70,6 +70,51 @@ fn in_child(test: &str, rust_log: &str, check: impl FnOnce()) { } } +#[test] +fn starter_log_colors_piped_streams() { + const TEST: &str = "starter_log::starter_log_colors_piped_streams"; + const MESSAGE: &str = "preset color probe"; + + if std::env::var("LOGFORTH_TEST_CHILD").as_deref() == Ok(TEST) { + for preset in [starter_log::stdout(), starter_log::stderr()] { + let logger = preset.build(); + logforth::error!(logger, "{MESSAGE}"); + logger.flush(); + } + return; + } + + for (no_color, force, expected) in [ + (None, None, false), + (None, Some("1"), true), + (None, Some("0"), false), + (Some("1"), Some("1"), false), + ] { + let mut cmd = Command::new(std::env::current_exe().unwrap()); + cmd.args(["--exact", TEST, "--nocapture"]) + .env("LOGFORTH_TEST_CHILD", TEST) + .env("RUST_LOG", "error") + .env_remove("NO_COLOR") + .env_remove("CLICOLOR_FORCE"); + if let Some(value) = no_color { + cmd.env("NO_COLOR", value); + } + if let Some(value) = force { + cmd.env("CLICOLOR_FORCE", value); + } + let output = cmd.output().unwrap(); + assert!(output.status.success(), "{output:?}"); + for stream in [&output.stdout, &output.stderr] { + let text = std::str::from_utf8(stream).unwrap(); + let line = text + .lines() + .find(|line| line.ends_with(MESSAGE)) + .expect(text); + assert_eq!(line.contains("\x1b["), expected, "{line:?}"); + } + } +} + #[test] fn child_starter_log_valid_rust_log_sets_max_level_and_rejects_second_install() { in_child(