Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
hawkw authored Oct 10, 2023
2 parents 8da5242 + f085b89 commit 42d8bcb
Show file tree
Hide file tree
Showing 12 changed files with 518 additions and 7 deletions.
2 changes: 1 addition & 1 deletion tracing-attributes/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ rust-version = "1.56.0"
proc-macro = true

[dependencies]
proc-macro2 = "1.0.40"
proc-macro2 = "1.0.60"
syn = { version = "2.0", default-features = false, features = ["full", "parsing", "printing", "visit-mut", "clone-impls", "extra-traits", "proc-macro"] }
quote = "1.0.20"

Expand Down
1 change: 0 additions & 1 deletion tracing-attributes/tests/async_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ async fn test_async_fn(polls: usize) -> Result<(), ()> {
#[allow(dead_code)] // this is just here to test whether it compiles.
#[instrument]
async fn test_ret_impl_trait(n: i32) -> Result<impl Iterator<Item = i32>, ()> {
let n = n;
Ok((0..10).filter(move |x| *x < n))
}

Expand Down
2 changes: 1 addition & 1 deletion tracing-journald/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ impl Subscriber {
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
// If we fail to get the name of the current executable fall back to an empty string.
.unwrap_or_else(String::new),
.unwrap_or_default(),
additional_fields: Vec::new(),
};
// Check that we can talk to journald, by sending empty payload which journald discards.
Expand Down
2 changes: 2 additions & 0 deletions tracing-subscriber/Cargo.toml
Original file line number Diff line number Diff line change
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", default-features = false, features = ["clock", "std"], optional = true }

# registry
sharded-slab = { version = "0.1.4", optional = true }
Expand Down
2 changes: 1 addition & 1 deletion tracing-subscriber/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Utilities for implementing and composing [`tracing`][tracing] subscribers.
[crates-badge]: https://img.shields.io/crates/v/tracing-subscriber.svg
[crates-url]: https://crates.io/crates/tracing-subscriber
[docs-badge]: https://docs.rs/tracing-subscriber/badge.svg
[docs-url]: https://docs.rs/tracing-subscriber/0.2.12
[docs-url]: https://docs.rs/tracing-subscriber/latest
[docs-master-badge]: https://img.shields.io/badge/docs-master-blue
[docs-master-url]: https://tracing-rs.netlify.com/tracing_subscriber
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
Expand Down
99 changes: 99 additions & 0 deletions tracing-subscriber/src/filter/subscriber_filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,36 @@ macro_rules! filter_impl_body {
fn max_level_hint(&self) -> Option<LevelFilter> {
self.deref().max_level_hint()
}

#[inline]
fn event_enabled(&self, event: &Event<'_>, cx: &Context<'_, S>) -> bool {
self.deref().event_enabled(event, cx)
}

#[inline]
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
self.deref().on_new_span(attrs, id, ctx)
}

#[inline]
fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
self.deref().on_record(id, values, ctx)
}

#[inline]
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
self.deref().on_enter(id, ctx)
}

#[inline]
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
self.deref().on_exit(id, ctx)
}

#[inline]
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
self.deref().on_close(id, ctx)
}
};
}

Expand All @@ -493,6 +523,75 @@ impl<S> subscribe::Filter<S> for Box<dyn subscribe::Filter<S> + Send + Sync + 's
filter_impl_body!();
}

// Implement Filter for Option<Filter> where None => allow
#[cfg(feature = "registry")]
#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
impl<F, S> subscribe::Filter<S> for Option<F>
where
F: subscribe::Filter<S>,
{
#[inline]
fn enabled(&self, meta: &Metadata<'_>, ctx: &Context<'_, S>) -> bool {
self.as_ref()
.map(|inner| inner.enabled(meta, ctx))
.unwrap_or(true)
}

#[inline]
fn callsite_enabled(&self, meta: &'static Metadata<'static>) -> Interest {
self.as_ref()
.map(|inner| inner.callsite_enabled(meta))
.unwrap_or_else(Interest::always)
}

#[inline]
fn max_level_hint(&self) -> Option<LevelFilter> {
self.as_ref().and_then(|inner| inner.max_level_hint())
}

#[inline]
fn event_enabled(&self, event: &Event<'_>, ctx: &Context<'_, S>) -> bool {
self.as_ref()
.map(|inner| inner.event_enabled(event, ctx))
.unwrap_or(true)
}

#[inline]
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
if let Some(inner) = self {
inner.on_new_span(attrs, id, ctx)
}
}

#[inline]
fn on_record(&self, id: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
if let Some(inner) = self {
inner.on_record(id, values, ctx)
}
}

#[inline]
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
if let Some(inner) = self {
inner.on_enter(id, ctx)
}
}

#[inline]
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
if let Some(inner) = self {
inner.on_exit(id, ctx)
}
}

#[inline]
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
if let Some(inner) = self {
inner.on_close(id, ctx)
}
}
}

// === impl Filtered ===

impl<S, F, C> Filtered<S, F, C> {
Expand Down
177 changes: 177 additions & 0 deletions tracing-subscriber/src/fmt/time/chrono_crate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
use crate::fmt::format::Writer;
use crate::fmt::time::FormatTime;

use std::sync::Arc;

/// 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`]
/// 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: Arc<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: Arc::new(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: Arc::new(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.as_ref() {
ChronoFmtType::Rfc3339 => {
use chrono::format::{Fixed, Item};
write!(
w,
"{}",
t.format_with_items(core::iter::once(Item::Fixed(Fixed::RFC3339)))
)
}
ChronoFmtType::Custom(fmt) => {
write!(w, "{}", t.format(fmt))
}
}
}
}

/// 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: Arc<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: Arc::new(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: Arc::new(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.as_ref() {
ChronoFmtType::Rfc3339 => w.write_str(&t.to_rfc3339()),
ChronoFmtType::Custom(fmt) => w.write_str(&format!("{}", t.format(fmt))),
}
}
}

/// 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
#[derive(Debug, Clone, Eq, PartialEq)]
enum ChronoFmtType {
/// Format according to the RFC 3339 convention.
Rfc3339,
/// Format according to a custom format string.
Custom(String),
}

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

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

use std::sync::Arc;

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());
// e.g. `buf` contains "2023-08-18T19:05:08.662499+00:00"
assert!(chrono::DateTime::parse_from_str(&buf, "%FT%H:%M:%S%.6f%z").is_ok());
}

#[test]
fn test_chrono_format_time_utc_custom() {
let fmt = ChronoUtc {
format: Arc::new(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"
assert!(chrono::NaiveDateTime::parse_from_str(&buf, "%a %b %e %T %Y").is_ok());
}

#[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".
assert!(chrono::DateTime::parse_from_str(&buf, "%FT%H:%M:%S%.6f%z").is_ok());
}

#[test]
fn test_chrono_format_time_local_custom() {
let fmt = ChronoLocal {
format: Arc::new(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".
assert!(chrono::NaiveDateTime::parse_from_str(&buf, "%a %b %e %T %Y").is_ok());
}
}
13 changes: 13 additions & 0 deletions tracing-subscriber/src/fmt/time/mod.rs
Original file line number Diff line number Diff line change
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,18 @@ 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")]
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
Loading

0 comments on commit 42d8bcb

Please sign in to comment.