Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[tracing-subscriber]: add chrono crate implementations of FormatTime #2690

Merged
merged 10 commits into from Sep 25, 2023
2 changes: 2 additions & 0 deletions tracing-subscriber/Cargo.toml
Expand Up @@ -32,6 +32,7 @@ fmt = ["registry", "std"]
ansi = ["fmt", "nu-ansi-term"]
registry = ["sharded-slab", "thread_local", "std"]
json = ["tracing-serde", "serde", "serde_json"]

# Enables support for local time when using the `time` crate timestamp
# formatters.
local-time = ["time/local-offset"]
Expand All @@ -58,6 +59,7 @@ tracing-serde = { path = "../tracing-serde", version = "0.2", optional = true }

# opt-in deps
parking_lot = { version = "0.12.1", optional = true }
chrono = { version = "0.4.26", optional = true }
shayne-fletcher marked this conversation as resolved.
Show resolved Hide resolved

# registry
sharded-slab = { version = "0.1.4", optional = true }
Expand Down
161 changes: 161 additions & 0 deletions tracing-subscriber/src/fmt/time/chrono_crate.rs
@@ -0,0 +1,161 @@
use crate::fmt::format::Writer;
use crate::fmt::time::FormatTime;

/// Formats [local time]s and [UTC time]s with `FormatTime` implementations
/// that use the [`chrono` crate].
///
/// [local time]: [`chrono::offset::Local`]
/// [UTC time]: [`chrono::offset::Utc`]
/// [`chrono` crate]: [`chrono`]

/// The RFC 3339 format is used by default but a custom format string
/// can be used. See [`chrono::format::strftime`]for details on
/// the supported syntax.
///
/// [`chrono::format::strftime`]: https://docs.rs/chrono/0.4.9/chrono/format/strftime/index.html
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
davidbarsky marked this conversation as resolved.
Show resolved Hide resolved
#[derive(Debug, Clone, Eq, PartialEq)]
enum ChronoFmtType {
shayne-fletcher marked this conversation as resolved.
Show resolved Hide resolved
/// Format according to the RFC 3339 convention.
Rfc3339,
/// Format according to a custom format string.
Custom(String),
shayne-fletcher marked this conversation as resolved.
Show resolved Hide resolved
}

impl Default for ChronoFmtType {
fn default() -> Self {
ChronoFmtType::Rfc3339
}
}

/// Formats the current [local time] using a [formatter] from the [`chrono`] crate.
///
/// [local time]: chrono::Local::now()
/// [formatter]: chrono::format
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct ChronoLocal {
format: ChronoFmtType,
}

impl ChronoLocal {
/// Format the time using the [`RFC 3339`] format
/// (a subset of [`ISO 8601`]).
///
/// [`RFC 3339`]: https://tools.ietf.org/html/rfc3339
/// [`ISO 8601`]: https://en.wikipedia.org/wiki/ISO_8601
pub fn rfc_3339() -> Self {
Self {
format: ChronoFmtType::Rfc3339,
}
}

/// Format the time using the given format string.
///
/// See [`chrono::format::strftime`] for details on the supported syntax.
pub fn new(format_string: String) -> Self {
Self {
format: ChronoFmtType::Custom(format_string),
}
}
}

impl FormatTime for ChronoLocal {
fn format_time(&self, w: &mut Writer<'_>) -> alloc::fmt::Result {
let t = chrono::Local::now();
match &self.format {
ChronoFmtType::Rfc3339 => w.write_str(&t.to_rfc3339()),
shayne-fletcher marked this conversation as resolved.
Show resolved Hide resolved
ChronoFmtType::Custom(fmt) => w.write_str(&format!("{}", t.format(fmt))),
shayne-fletcher marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

/// Formats the current [UTC time] using a [formatter] from the [`chrono`] crate.
///
/// [UTC time]: chrono::Utc::now()
/// [formatter]: chrono::format
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct ChronoUtc {
format: ChronoFmtType,
}

impl ChronoUtc {
/// Format the time using the [`RFC 3339`] format
/// (a subset of [`ISO 8601`]).
///
/// [`RFC 3339`]: https://tools.ietf.org/html/rfc3339
/// [`ISO 8601`]: https://en.wikipedia.org/wiki/ISO_8601
pub fn rfc_3339() -> Self {
Self {
format: ChronoFmtType::Rfc3339,
}
}

/// Format the time using the given format string.
///
/// See [`chrono::format::strftime`] for details on the supported syntax.
pub fn new(format_string: String) -> Self {
Self {
format: ChronoFmtType::Custom(format_string),
}
}
}

impl FormatTime for ChronoUtc {
fn format_time(&self, w: &mut Writer<'_>) -> alloc::fmt::Result {
let t = chrono::Utc::now();
match &self.format {
ChronoFmtType::Rfc3339 => w.write_str(&t.to_rfc3339()),
ChronoFmtType::Custom(fmt) => w.write_str(&format!("{}", t.format(fmt))),
}
}
}

#[cfg(test)]
mod tests {
use crate::fmt::format::Writer;
use crate::fmt::time::FormatTime;

use super::ChronoFmtType;
use super::ChronoLocal;
use super::ChronoUtc;

#[test]
fn test_chrono_format_time_utc_default() {
let mut buf = String::new();
let mut dst: Writer<'_> = Writer::new(&mut buf);
assert!(FormatTime::format_time(&ChronoUtc::default(), &mut dst).is_ok());
shayne-fletcher marked this conversation as resolved.
Show resolved Hide resolved
// e.g. `buf` contains "2023-08-18T19:05:08.662499+00:00"
}

#[test]
fn test_chrono_format_time_utc_custom() {
let fmt = ChronoUtc {
shayne-fletcher marked this conversation as resolved.
Show resolved Hide resolved
format: ChronoFmtType::Custom("%a %b %e %T %Y".to_owned()),
};
let mut buf = String::new();
let mut dst: Writer<'_> = Writer::new(&mut buf);
assert!(FormatTime::format_time(&fmt, &mut dst).is_ok());
// e.g. `buf` contains "Wed Aug 23 15:53:23 2023"
}

#[test]
fn test_chrono_format_time_local_default() {
let mut buf = String::new();
let mut dst: Writer<'_> = Writer::new(&mut buf);
assert!(FormatTime::format_time(&ChronoLocal::default(), &mut dst).is_ok());
// e.g. `buf` contains "2023-08-18T14:59:08.662499-04:00".
}

#[test]
fn test_chrono_format_time_local_custom() {
let fmt = ChronoLocal {
format: ChronoFmtType::Custom("%a %b %e %T %Y".to_owned()),
};
let mut buf = String::new();
let mut dst: Writer<'_> = Writer::new(&mut buf);
assert!(FormatTime::format_time(&fmt, &mut dst).is_ok());
// e.g. `buf` contains "Wed Aug 23 15:55:46 2023".
}
}
14 changes: 14 additions & 0 deletions tracing-subscriber/src/fmt/time/mod.rs
Expand Up @@ -7,6 +7,7 @@ mod datetime;

#[cfg(feature = "time")]
mod time_crate;

#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub use time_crate::UtcTime;
Expand All @@ -15,6 +16,19 @@ pub use time_crate::UtcTime;
#[cfg_attr(docsrs, doc(cfg(all(unsound_local_offset, feature = "local-time"))))]
pub use time_crate::LocalTime;

/// [`chrono`]-based implementation for [`FormatTime`].
#[cfg(feature = "chrono")]
#[cfg_attr(docsrs, doc(cfg(feature = "local-time")))]
davidbarsky marked this conversation as resolved.
Show resolved Hide resolved
mod chrono_crate;

#[cfg(feature = "chrono")]
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
pub use chrono_crate::ChronoLocal;

#[cfg(feature = "chrono")]
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
pub use chrono_crate::ChronoUtc;

/// A type that can measure and format the current time.
///
/// This trait is used by `Format` to include a timestamp with each `Event` when it is logged.
Expand Down