Skip to content

Commit 6219cc7

Browse files
committed
subscriber: replace chrono with time for timestamp formatting (#1646)
## Motivation Currently, `tracing-subscriber` supports the `chrono` crate for timestamp formatting, via a default-on feature flag. When this code was initially added to `tracing-subscriber`, the `time` crate did not have support for the timestamp formatting options we needed. Unfortunately, the `chrono` crate's maintainance status is now in question (see #1598). Furthermore, `chrono` depends on version 0.1 of the `time` crate, which contains a security vulnerability (https://rustsec.org/advisories/RUSTSEC-2020-0071.html). This vulnerability is fixed in more recent releases of `time`, but `chrono` still uses v0.1. ## Solution Fortunately, the `time` crate now has its own timestamp formatting support. This branch replaces the `ChronoLocal` and `ChronoUtc` timestamp formatters with new `LocalTime` and `UtcTime` formatters. These formatters use the `time` crate's formatting APIs rather than `chrono`'s. This removes the vulnerable dependency on `time` 0.1 Additionally, the new `time` APIs are feature flagged as an _opt-in_ feature, rather than as an _opt-out_ feature. This should make it easier to avoid accidentally depending on the `time` crate when more sophisticated timestamp formatting is _not_ required. In a follow-up branch, we could also add support for `humantime` as an option for timestamp formatting. Naturally, since this removes existing APIs, this is a breaking change, and will thus require publishing `tracing-subscriber` 0.3. We'll want to do some other breaking changes as well. Fixes #1598.
1 parent d169ae4 commit 6219cc7

File tree

10 files changed

+369
-189
lines changed

10 files changed

+369
-189
lines changed

examples/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ tracing-core = { path = "../tracing-core", version = "0.1" }
1515
tracing-error = { path = "../tracing-error" }
1616
tracing-flame = { path = "../tracing-flame" }
1717
tracing-tower = { version = "0.1.0", path = "../tracing-tower" }
18-
tracing-subscriber = { path = "../tracing-subscriber", version = "0.2.13", features = ["json", "chrono"] }
18+
tracing-subscriber = { path = "../tracing-subscriber", version = "0.2", features = ["json"] }
1919
tracing-futures = { version = "0.2.1", path = "../tracing-futures", features = ["futures-01"] }
2020
tracing-attributes = { path = "../tracing-attributes", version = "0.1.2" }
2121
tracing-log = { path = "../tracing-log", version = "0.1.1", features = ["env_logger"] }

tracing-subscriber/Cargo.toml

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,15 @@ keywords = ["logging", "tracing", "metrics", "subscriber"]
2323

2424
[features]
2525

26-
default = ["env-filter", "smallvec", "fmt", "ansi", "chrono", "tracing-log", "json"]
26+
default = ["env-filter", "smallvec", "fmt", "ansi", "tracing-log", "json"]
2727
env-filter = ["matchers", "regex", "lazy_static", "tracing"]
2828
fmt = ["registry"]
2929
ansi = ["fmt", "ansi_term"]
3030
registry = ["sharded-slab", "thread_local"]
3131
json = ["tracing-serde", "serde", "serde_json"]
32+
# Enables support for local time when using the `time` crate timestamp
33+
# formatters.
34+
local-time = ["time/local-offset"]
3235

3336
[dependencies]
3437
tracing-core = { path = "../tracing-core", version = "0.1.20" }
@@ -43,7 +46,7 @@ lazy_static = { optional = true, version = "1" }
4346
# fmt
4447
tracing-log = { path = "../tracing-log", version = "0.1.2", optional = true, default-features = false, features = ["log-tracer", "std"] }
4548
ansi_term = { version = "0.12", optional = true }
46-
chrono = { version = "0.4.16", optional = true, default-features = false, features = ["clock", "std"] }
49+
time = { version = "0.3", features = ["formatting"], optional = true }
4750

4851
# only required by the json feature
4952
serde_json = { version = "1.0", optional = true }
@@ -65,6 +68,8 @@ criterion = { version = "0.3", default_features = false }
6568
regex = { version = "1", default-features = false, features = ["std"] }
6669
tracing-futures = { path = "../tracing-futures", version = "0.2", default-features = false, features = ["std-future", "std"] }
6770
tokio = { version = "0.2", features = ["rt-core", "macros"] }
71+
# Enable the `time` crate's `macros` feature, for examples.
72+
time = { version = "0.3", features = ["formatting", "macros"] }
6873

6974
[badges]
7075
maintenance = { status = "experimental" }

tracing-subscriber/src/fmt/fmt_layer.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -221,15 +221,18 @@ where
221221
{
222222
/// Use the given [`timer`] for span and event timestamps.
223223
///
224-
/// See [`time`] for the provided timer implementations.
224+
/// See the [`time` module] for the provided timer implementations.
225225
///
226-
/// Note that using the `chrono` feature flag enables the
227-
/// additional time formatters [`ChronoUtc`] and [`ChronoLocal`].
226+
/// Note that using the `"time`"" feature flag enables the
227+
/// additional time formatters [`UtcTime`] and [`LocalTime`], which use the
228+
/// [`time` crate] to provide more sophisticated timestamp formatting
229+
/// options.
228230
///
229-
/// [`time`]: ./time/index.html
230-
/// [`timer`]: ./time/trait.FormatTime.html
231-
/// [`ChronoUtc`]: ./time/struct.ChronoUtc.html
232-
/// [`ChronoLocal`]: ./time/struct.ChronoLocal.html
231+
/// [`timer`]: super::time::FormatTime
232+
/// [`time` module]: mod@super::time
233+
/// [`UtcTime`]: super::time::UtcTime
234+
/// [`LocalTime`]: super::time::LocalTime
235+
/// [`time` crate]: https://docs.rs/time/0.3
233236
pub fn with_timer<T2>(self, timer: T2) -> Layer<S, N, format::Format<L, T2>, W> {
234237
Layer {
235238
fmt_event: self.fmt_event.with_timer(timer),

tracing-subscriber/src/fmt/format/json.rs

Lines changed: 4 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
use super::{Format, FormatEvent, FormatFields, FormatTime};
22
use crate::{
33
field::{RecordFields, VisitOutput},
4-
fmt::fmt_layer::{FmtContext, FormattedFields},
4+
fmt::{
5+
fmt_layer::{FmtContext, FormattedFields},
6+
writer::WriteAdaptor,
7+
},
58
registry::LookupSpan,
69
};
710
use serde::ser::{SerializeMap, Serializer as _};
811
use serde_json::Serializer;
912
use std::{
1013
collections::BTreeMap,
1114
fmt::{self, Write},
12-
io,
1315
};
1416
use tracing_core::{
1517
field::{self, Field},
@@ -477,44 +479,6 @@ impl<'a> field::Visit for JsonVisitor<'a> {
477479
};
478480
}
479481
}
480-
481-
/// A bridge between `fmt::Write` and `io::Write`.
482-
///
483-
/// This is needed because tracing-subscriber's FormatEvent expects a fmt::Write
484-
/// while serde_json's Serializer expects an io::Write.
485-
struct WriteAdaptor<'a> {
486-
fmt_write: &'a mut dyn fmt::Write,
487-
}
488-
489-
impl<'a> WriteAdaptor<'a> {
490-
fn new(fmt_write: &'a mut dyn fmt::Write) -> Self {
491-
Self { fmt_write }
492-
}
493-
}
494-
495-
impl<'a> io::Write for WriteAdaptor<'a> {
496-
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
497-
let s =
498-
std::str::from_utf8(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
499-
500-
self.fmt_write
501-
.write_str(s)
502-
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
503-
504-
Ok(s.as_bytes().len())
505-
}
506-
507-
fn flush(&mut self) -> io::Result<()> {
508-
Ok(())
509-
}
510-
}
511-
512-
impl<'a> fmt::Debug for WriteAdaptor<'a> {
513-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514-
f.pad("WriteAdaptor { .. }")
515-
}
516-
}
517-
518482
#[cfg(test)]
519483
mod test {
520484
use super::*;

tracing-subscriber/src/fmt/format/mod.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -360,13 +360,16 @@ impl<F, T> Format<F, T> {
360360
///
361361
/// See [`time` module] for the provided timer implementations.
362362
///
363-
/// Note that using the `chrono` feature flag enables the
364-
/// additional time formatters [`ChronoUtc`] and [`ChronoLocal`].
363+
/// Note that using the `"time"` feature flag enables the
364+
/// additional time formatters [`UtcTime`] and [`LocalTime`], which use the
365+
/// [`time` crate] to provide more sophisticated timestamp formatting
366+
/// options.
365367
///
366368
/// [`timer`]: super::time::FormatTime
367369
/// [`time` module]: mod@super::time
368-
/// [`ChronoUtc`]: super::time::ChronoUtc
369-
/// [`ChronoLocal`]: super::time::ChronoLocal
370+
/// [`UtcTime`]: super::time::UtcTime
371+
/// [`LocalTime`]: super::time::LocalTime
372+
/// [`time` crate]: https://docs.rs/time/0.3
370373
pub fn with_timer<T2>(self, timer: T2) -> Format<F, T2> {
371374
Format {
372375
format: self.format,

tracing-subscriber/src/fmt/mod.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -591,15 +591,18 @@ where
591591
{
592592
/// Use the given [`timer`] for log message timestamps.
593593
///
594-
/// See [`time`] for the provided timer implementations.
594+
/// See the [`time` module] for the provided timer implementations.
595595
///
596-
/// Note that using the `chrono` feature flag enables the
597-
/// additional time formatters [`ChronoUtc`] and [`ChronoLocal`].
596+
/// Note that using the `"time`"" feature flag enables the
597+
/// additional time formatters [`UtcTime`] and [`LocalTime`], which use the
598+
/// [`time` crate] to provide more sophisticated timestamp formatting
599+
/// options.
598600
///
599-
/// [`time`]: ./time/index.html
600-
/// [`timer`]: ./time/trait.FormatTime.html
601-
/// [`ChronoUtc`]: ./time/struct.ChronoUtc.html
602-
/// [`ChronoLocal`]: ./time/struct.ChronoLocal.html
601+
/// [`timer`]: time::FormatTime
602+
/// [`time` module]: mod@time
603+
/// [`UtcTime`]: time::UtcTime
604+
/// [`LocalTime`]: time::LocalTime
605+
/// [`time` crate]: https://docs.rs/time/0.3
603606
pub fn with_timer<T2>(self, timer: T2) -> SubscriberBuilder<N, format::Format<L, T2>, F, W> {
604607
SubscriberBuilder {
605608
filter: self.filter,

tracing-subscriber/src/fmt/time/mod.rs

Lines changed: 7 additions & 123 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,15 @@
22
use std::fmt;
33
use std::time::Instant;
44

5-
#[cfg(not(feature = "chrono"))]
65
mod datetime;
76

7+
#[cfg(feature = "time")]
8+
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
9+
mod time_crate;
10+
#[cfg(feature = "time")]
11+
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
12+
pub use time_crate::{LocalTime, UtcTime};
13+
814
/// A type that can measure and format the current time.
915
///
1016
/// This trait is used by `Format` to include a timestamp with each `Event` when it is logged.
@@ -81,9 +87,6 @@ impl FormatTime for fn(&mut dyn fmt::Write) -> fmt::Result {
8187
}
8288

8389
/// Retrieve and print the current wall-clock time.
84-
///
85-
/// If the `chrono` feature is enabled, the current time is printed in a human-readable format like
86-
/// "Jun 25 14:27:12.955". Otherwise the `Debug` implementation of `std::time::SystemTime` is used.
8790
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
8891
pub struct SystemTime;
8992

@@ -109,14 +112,6 @@ impl From<Instant> for Uptime {
109112
}
110113
}
111114

112-
#[cfg(feature = "chrono")]
113-
impl FormatTime for SystemTime {
114-
fn format_time(&self, w: &mut dyn fmt::Write) -> fmt::Result {
115-
write!(w, "{}", chrono::Local::now().format("%b %d %H:%M:%S%.3f"))
116-
}
117-
}
118-
119-
#[cfg(not(feature = "chrono"))]
120115
impl FormatTime for SystemTime {
121116
fn format_time(&self, w: &mut dyn fmt::Write) -> fmt::Result {
122117
write!(
@@ -133,114 +128,3 @@ impl FormatTime for Uptime {
133128
write!(w, "{:4}.{:09}s", e.as_secs(), e.subsec_nanos())
134129
}
135130
}
136-
137-
/// The RFC 3339 format is used by default and using
138-
/// this struct allows chrono to bypass the parsing
139-
/// used when a custom format string is provided
140-
#[cfg(feature = "chrono")]
141-
#[derive(Debug, Clone, Eq, PartialEq)]
142-
enum ChronoFmtType {
143-
Rfc3339,
144-
Custom(String),
145-
}
146-
147-
#[cfg(feature = "chrono")]
148-
impl Default for ChronoFmtType {
149-
fn default() -> Self {
150-
ChronoFmtType::Rfc3339
151-
}
152-
}
153-
154-
/// Retrieve and print the current UTC time.
155-
#[cfg(feature = "chrono")]
156-
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
157-
#[derive(Debug, Clone, Eq, PartialEq, Default)]
158-
pub struct ChronoUtc {
159-
format: ChronoFmtType,
160-
}
161-
162-
#[cfg(feature = "chrono")]
163-
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
164-
impl ChronoUtc {
165-
/// Format the time using the [`RFC 3339`] format
166-
/// (a subset of [`ISO 8601`]).
167-
///
168-
/// [`RFC 3339`]: https://tools.ietf.org/html/rfc3339
169-
/// [`ISO 8601`]: https://en.wikipedia.org/wiki/ISO_8601
170-
pub fn rfc3339() -> Self {
171-
ChronoUtc {
172-
format: ChronoFmtType::Rfc3339,
173-
}
174-
}
175-
176-
/// Format the time using the given format string.
177-
///
178-
/// See [`chrono::format::strftime`]
179-
/// for details on the supported syntax.
180-
///
181-
/// [`chrono::format::strftime`]: https://docs.rs/chrono/0.4.9/chrono/format/strftime/index.html
182-
pub fn with_format(format_string: String) -> Self {
183-
ChronoUtc {
184-
format: ChronoFmtType::Custom(format_string),
185-
}
186-
}
187-
}
188-
189-
#[cfg(feature = "chrono")]
190-
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
191-
impl FormatTime for ChronoUtc {
192-
fn format_time(&self, w: &mut dyn fmt::Write) -> fmt::Result {
193-
let time = chrono::Utc::now();
194-
match self.format {
195-
ChronoFmtType::Rfc3339 => write!(w, "{}", time.to_rfc3339()),
196-
ChronoFmtType::Custom(ref format_str) => write!(w, "{}", time.format(format_str)),
197-
}
198-
}
199-
}
200-
201-
/// Retrieve and print the current local time.
202-
#[cfg(feature = "chrono")]
203-
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
204-
#[derive(Debug, Clone, Eq, PartialEq, Default)]
205-
pub struct ChronoLocal {
206-
format: ChronoFmtType,
207-
}
208-
209-
#[cfg(feature = "chrono")]
210-
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
211-
impl ChronoLocal {
212-
/// Format the time using the [`RFC 3339`] format
213-
/// (a subset of [`ISO 8601`]).
214-
///
215-
/// [`RFC 3339`]: https://tools.ietf.org/html/rfc3339
216-
/// [`ISO 8601`]: https://en.wikipedia.org/wiki/ISO_8601
217-
pub fn rfc3339() -> Self {
218-
ChronoLocal {
219-
format: ChronoFmtType::Rfc3339,
220-
}
221-
}
222-
223-
/// Format the time using the given format string.
224-
///
225-
/// See [`chrono::format::strftime`]
226-
/// for details on the supported syntax.
227-
///
228-
/// [`chrono::format::strftime`]: https://docs.rs/chrono/0.4.9/chrono/format/strftime/index.html
229-
pub fn with_format(format_string: String) -> Self {
230-
ChronoLocal {
231-
format: ChronoFmtType::Custom(format_string),
232-
}
233-
}
234-
}
235-
236-
#[cfg(feature = "chrono")]
237-
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
238-
impl FormatTime for ChronoLocal {
239-
fn format_time(&self, w: &mut dyn fmt::Write) -> fmt::Result {
240-
let time = chrono::Local::now();
241-
match self.format {
242-
ChronoFmtType::Rfc3339 => write!(w, "{}", time.to_rfc3339()),
243-
ChronoFmtType::Custom(ref format_str) => write!(w, "{}", time.format(format_str)),
244-
}
245-
}
246-
}

0 commit comments

Comments
 (0)