1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
use std::io;
use tracing::Subscriber;
use tracing_subscriber::{
fmt::{
time::{FormatTime, SystemTime},
MakeWriter,
TestWriter,
},
registry::LookupSpan,
Layer as Subscribe,
Registry,
};
use super::names::{
CURRENT_SPAN,
FIELDS,
FILENAME,
LEVEL,
LINE_NUMBER,
SPAN_LIST,
TARGET,
THREAD_ID,
THREAD_NAME,
TIMESTAMP,
};
use crate::layer::{FlatSchemaKey, JsonLayer};
/// A [`Layer`] that logs JSON formatted representations of `tracing` events.
///
/// This is just a wrapper around [`JsonLayer`] which exists for compatibility with
/// `tracing_subscriber`.
///
/// ## Examples
///
/// Constructing a layer with the default configuration:
///
/// ```rust
/// use tracing_subscriber::Registry;
/// use tracing_subscriber::layer::SubscriberExt as _;
/// use json_subscriber::fmt;
///
/// let subscriber = Registry::default()
/// .with(fmt::Layer::default());
///
/// tracing::subscriber::set_global_default(subscriber).unwrap();
/// ```
///
/// Overriding the layer's behavior:
///
/// ```rust
/// use tracing_subscriber::Registry;
/// use tracing_subscriber::layer::SubscriberExt as _;
/// use json_subscriber::fmt;
///
/// let fmt_layer = fmt::layer()
/// .with_target(false) // don't include event targets when logging
/// .with_level(false); // don't include event levels when logging
///
/// let subscriber = Registry::default().with(fmt_layer);
/// # tracing::subscriber::set_global_default(subscriber).unwrap();
/// ```
///
/// [`Layer`]: tracing_subscriber::Layer
pub struct Layer<S: for<'lookup> LookupSpan<'lookup> = Registry, W = fn() -> io::Stdout> {
inner: JsonLayer<S, W>,
}
impl<S: Subscriber + for<'lookup> LookupSpan<'lookup>> Default for Layer<S> {
fn default() -> Self {
let mut inner = JsonLayer::stdout();
inner
// If we do not call this, fields are not printed at all.
.with_event(FIELDS)
.with_timer(TIMESTAMP, SystemTime)
.with_target(TARGET)
.with_level(LEVEL)
.with_current_span(CURRENT_SPAN)
.with_span_list(SPAN_LIST);
Self { inner }
}
}
impl<S, W> Subscribe<S> for Layer<S, W>
where
JsonLayer<S, W>: Subscribe<S>,
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
{
fn on_register_dispatch(&self, subscriber: &tracing::Dispatch) {
self.inner.on_register_dispatch(subscriber);
}
fn on_layer(&mut self, subscriber: &mut S) {
self.inner.on_layer(subscriber);
}
fn register_callsite(
&self,
metadata: &'static tracing::Metadata<'static>,
) -> tracing_core::Interest {
self.inner.register_callsite(metadata)
}
fn enabled(
&self,
metadata: &tracing::Metadata<'_>,
ctx: tracing_subscriber::layer::Context<'_, S>,
) -> bool {
self.inner.enabled(metadata, ctx)
}
fn on_new_span(
&self,
attrs: &tracing_core::span::Attributes<'_>,
id: &tracing_core::span::Id,
ctx: tracing_subscriber::layer::Context<'_, S>,
) {
self.inner.on_new_span(attrs, id, ctx);
}
fn on_record(
&self,
span: &tracing_core::span::Id,
values: &tracing_core::span::Record<'_>,
ctx: tracing_subscriber::layer::Context<'_, S>,
) {
self.inner.on_record(span, values, ctx);
}
fn on_follows_from(
&self,
span: &tracing_core::span::Id,
follows: &tracing_core::span::Id,
ctx: tracing_subscriber::layer::Context<'_, S>,
) {
self.inner.on_follows_from(span, follows, ctx);
}
fn event_enabled(
&self,
event: &tracing::Event<'_>,
ctx: tracing_subscriber::layer::Context<'_, S>,
) -> bool {
self.inner.event_enabled(event, ctx)
}
fn on_event(&self, event: &tracing::Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_event(event, ctx);
}
fn on_enter(
&self,
id: &tracing_core::span::Id,
ctx: tracing_subscriber::layer::Context<'_, S>,
) {
self.inner.on_enter(id, ctx);
}
fn on_exit(&self, id: &tracing_core::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_exit(id, ctx);
}
fn on_close(&self, id: tracing_core::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_close(id, ctx);
}
fn on_id_change(
&self,
old: &tracing_core::span::Id,
new: &tracing_core::span::Id,
ctx: tracing_subscriber::layer::Context<'_, S>,
) {
self.inner.on_id_change(old, new, ctx);
}
}
impl<S, W> Layer<S, W>
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
{
/// Sets the [`MakeWriter`] that the [`JsonLayer`] being built will use to write events.
///
/// # Examples
///
/// Using `stderr` rather than `stdout`:
///
/// ```rust
/// # use tracing_subscriber::prelude::*;
/// let layer = json_subscriber::fmt::layer()
/// .with_writer(std::io::stderr);
/// # tracing_subscriber::registry().with(layer);
/// ```
///
/// [`MakeWriter`]: MakeWriter
/// [`JsonLayer`]: JsonLayer
pub fn with_writer<W2>(self, make_writer: W2) -> Layer<S, W2>
where
W2: for<'writer> MakeWriter<'writer> + 'static,
{
Layer::<S, W2> {
inner: self.inner.with_writer(make_writer),
}
}
/// Updates the [`MakeWriter`] by applying a function to the existing [`MakeWriter`].
///
/// This sets the [`MakeWriter`] that the layer being built will use to write events.
///
/// # Examples
///
/// Redirect output to stderr if level is <= WARN:
///
/// ```rust
/// # use tracing_subscriber::prelude::*;
/// use tracing_subscriber::fmt::writer::MakeWriterExt;
///
/// let stderr = std::io::stderr.with_max_level(tracing::Level::WARN);
/// let layer = json_subscriber::fmt::layer()
/// .map_writer(move |w| stderr.or_else(w));
/// # tracing_subscriber::registry().with(layer);
/// ```
pub fn map_writer<W2>(self, f: impl FnOnce(W) -> W2) -> Layer<S, W2>
where
W2: for<'writer> MakeWriter<'writer> + 'static,
{
Layer::<S, W2> {
inner: self.inner.map_writer(f),
}
}
/// Configures the layer to support [`libtest`'s output capturing][capturing] when used in
/// unit tests.
///
/// See [`TestWriter`] for additional details.
///
/// # Examples
///
/// Using [`TestWriter`] to let `cargo test` capture test output:
///
/// ```rust
/// # use tracing_subscriber::prelude::*;
/// use tracing_subscriber::fmt::writer::MakeWriterExt;
///
/// let layer = json_subscriber::fmt::layer()
/// .with_test_writer();
/// # tracing_subscriber::registry().with(layer);
/// ```
/// [capturing]:
/// https://doc.rust-lang.org/book/ch11-02-running-tests.html#showing-function-output
/// [`TestWriter`]: TestWriter
pub fn with_test_writer(self) -> Layer<S, TestWriter> {
Layer::<S, TestWriter> {
inner: self.inner.with_test_writer(),
}
}
/// Borrows the [writer] for this layer.
///
/// [writer]: MakeWriter
pub fn writer(&self) -> &W {
self.inner.writer()
}
/// Mutably borrows the [writer] for this layer.
///
/// This method is primarily expected to be used with the [`reload::Handle::modify`] method.
///
/// # Examples
///
/// ```
/// # use tracing::info;
/// # use tracing_subscriber::{fmt,reload,Registry,prelude::*};
/// # fn non_blocking<T: std::io::Write>(writer: T) -> (fn() -> std::io::Stdout) {
/// # std::io::stdout
/// # }
/// # fn main() {
/// let layer = json_subscriber::fmt::layer().with_writer(non_blocking(std::io::stderr()));
/// let (layer, reload_handle) = reload::Layer::new(layer);
///
/// tracing_subscriber::registry().with(layer).init();
///
/// info!("This will be logged to stderr");
/// reload_handle.modify(|subscriber| *subscriber.writer_mut() = non_blocking(std::io::stdout()));
/// info!("This will be logged to stdout");
/// # }
/// ```
///
/// [writer]: MakeWriter
/// [`reload::Handle::modify`]: tracing_subscriber::reload::Handle::modify
pub fn writer_mut(&mut self) -> &mut W {
self.inner.writer_mut()
}
/// Mutably borrows the [`JsonLayer`] inside of this layer. This can be useful to add more
/// information to the output or to change the output with the [`reload::Handle::modify`]
/// method.
///
/// # Examples
/// ```rust
/// # use tracing_subscriber::prelude::*;
/// let mut layer = json_subscriber::layer();
/// let mut inner = layer.inner_layer_mut();
///
/// inner.add_static_field(
/// "hostname",
/// serde_json::json!({
/// "hostname": get_hostname(),
/// }),
/// );
/// # tracing_subscriber::registry().with(layer);
/// # fn get_hostname() -> &'static str { "localhost" }
/// ```
///
/// [`reload::Handle::modify`]: tracing_subscriber::reload::Handle::modify
pub fn inner_layer_mut(&mut self) -> &mut JsonLayer<S, W> {
&mut self.inner
}
/// Sets whether to write errors from [`FormatEvent`] to the writer.
/// Defaults to true.
///
/// By default, `fmt::JsonLayer` will write any `FormatEvent`-internal errors to the writer.
/// These errors are unlikely and will only occur if there is a bug in the `FormatEvent`
/// implementation or its dependencies.
///
/// If writing to the writer fails, the error message is printed to stderr as a fallback.
///
/// [`FormatEvent`]: tracing_subscriber::fmt::FormatEvent
#[must_use]
pub fn log_internal_errors(mut self, log_internal_errors: bool) -> Self {
self.inner.log_internal_errors(log_internal_errors);
self
}
/// Sets the JSON subscriber being built to flatten event metadata.
#[must_use]
pub fn flatten_event(mut self, flatten_event: bool) -> Self {
if flatten_event {
self.inner.remove_field(FIELDS);
self.inner.with_flattened_event();
} else {
self.inner
.remove_flattened_field(&FlatSchemaKey::FlattenedEvent);
self.inner.with_event(FIELDS);
}
self
}
/// Sets whether or not the formatter will include the current span in formatted events.
#[must_use]
pub fn with_current_span(mut self, display_current_span: bool) -> Self {
if display_current_span {
self.inner.with_current_span(CURRENT_SPAN);
} else {
self.inner.remove_field(CURRENT_SPAN);
}
self
}
/// Sets whether or not the formatter will include a list (from root to leaf) of all currently
/// entered spans in formatted events.
///
/// This overrides any previous calls to [`with_flat_span_list`](Self::with_flat_span_list).
#[must_use]
pub fn with_span_list(mut self, display_span_list: bool) -> Self {
if display_span_list {
self.inner.with_span_list(SPAN_LIST);
} else {
self.inner.remove_field(SPAN_LIST);
}
self
}
/// Sets whether or not the formatter will include an object containing all parent spans'
/// fields. If multiple ancestor spans recorded the same field, the span closer to the leaf span
/// overrides the values of spans that are closer to the root spans.
///
/// This overrides any previous calls to [`with_span_list`](Self::with_span_list).
#[must_use]
pub fn with_flat_span_list(mut self, flatten_span_list: bool) -> Self {
if flatten_span_list {
self.inner.with_flattened_span_fields(SPAN_LIST);
} else {
self.inner.remove_field(SPAN_LIST);
}
self
}
/// Use the given [`timer`] for log message timestamps.
///
/// See the [`time` module] for the provided timer implementations.
///
/// Note that using the `"time`"" feature flag enables the
/// additional time formatters [`UtcTime`] and [`LocalTime`], which use the
/// [`time` crate] to provide more sophisticated timestamp formatting
/// options.
///
/// [`timer`]: tracing_subscriber::fmt::time::FormatTime
/// [`time` module]: mod@tracing_subscriber::fmt::time
/// [`UtcTime`]: tracing_subscriber::fmt::time::UtcTime
/// [`LocalTime`]: tracing_subscriber::fmt::time::LocalTime
/// [`time` crate]: https://docs.rs/time/0.3
#[must_use]
pub fn with_timer<T: FormatTime + Send + Sync + 'static>(mut self, timer: T) -> Self {
self.inner.with_timer(TIMESTAMP, timer);
self
}
/// Do not emit timestamps with log messages.
#[must_use]
pub fn without_time(mut self) -> Self {
self.inner.remove_field(TIMESTAMP);
self
}
/// Sets whether or not an event's target is displayed.
#[must_use]
pub fn with_target(mut self, display_target: bool) -> Self {
if display_target {
self.inner.with_target(TARGET);
} else {
self.inner.remove_field(TARGET);
}
self
}
/// Sets whether or not an event's [source code file path][file] is
/// displayed.
///
/// [file]: tracing_core::Metadata::file
#[must_use]
pub fn with_file(mut self, display_filename: bool) -> Self {
if display_filename {
self.inner.with_file(FILENAME);
} else {
self.inner.remove_field(FILENAME);
}
self
}
/// Sets whether or not an event's [source code line number][line] is
/// displayed.
///
/// [line]: tracing_core::Metadata::line
#[must_use]
pub fn with_line_number(mut self, display_line_number: bool) -> Self {
if display_line_number {
self.inner.with_line_number(LINE_NUMBER);
} else {
self.inner.remove_field(LINE_NUMBER);
}
self
}
/// Sets whether or not an event's level is displayed.
#[must_use]
pub fn with_level(mut self, display_level: bool) -> Self {
if display_level {
self.inner.with_level(LEVEL);
} else {
self.inner.remove_field(LEVEL);
}
self
}
/// Sets whether or not the [name] of the current thread is displayed
/// when formatting events.
///
/// [name]: std::thread#naming-threads
#[must_use]
pub fn with_thread_names(mut self, display_thread_name: bool) -> Self {
if display_thread_name {
self.inner.with_thread_names(THREAD_NAME);
} else {
self.inner.remove_field(THREAD_NAME);
}
self
}
/// Sets whether or not the [thread ID] of the current thread is displayed
/// when formatting events.
///
/// [thread ID]: std::thread::ThreadId
#[must_use]
pub fn with_thread_ids(mut self, display_thread_id: bool) -> Self {
if display_thread_id {
self.inner.with_thread_ids(THREAD_ID);
} else {
self.inner.remove_field(THREAD_ID);
}
self
}
/// Sets whether or not [OpenTelemetry] trace ID and span ID is displayed when formatting
/// events.
///
/// [OpenTelemetry]: https://opentelemetry.io
#[cfg(feature = "opentelemetry")]
#[cfg_attr(docsrs, doc(cfg(feature = "opentelemetry")))]
#[must_use]
pub fn with_opentelemetry_ids(mut self, display_opentelemetry_ids: bool) -> Self {
self.inner.with_opentelemetry_ids(display_opentelemetry_ids);
self
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use tracing::subscriber::with_default;
use tracing_subscriber::{registry, Layer as _, Registry};
use super::Layer;
use crate::tests::{MockMakeWriter, MockTime};
fn test_json<W, T>(
expected: &serde_json::Value,
layer: Layer<Registry, W>,
producer: impl FnOnce() -> T,
) {
let actual = produce_log_line(layer, producer);
assert_eq!(
expected,
&serde_json::from_str::<serde_json::Value>(&actual).unwrap(),
);
}
fn produce_log_line<W, T>(layer: Layer<Registry, W>, producer: impl FnOnce() -> T) -> String {
let make_writer = MockMakeWriter::default();
let collector = layer
.with_writer(make_writer.clone())
.with_timer(MockTime)
.with_subscriber(registry());
with_default(collector, producer);
let buf = make_writer.buf();
dbg!(std::str::from_utf8(&buf[..]).unwrap()).to_owned()
}
#[test]
fn default() {
let expected = json!(
{
"timestamp": "fake time",
"level": "INFO",
"span": {
"answer": 42,
"name": "json_span",
"number": 3,
},
"spans": [
{
"answer": 42,
"name": "json_span",
"number": 3,
},
],
"target": "json_subscriber::fmt::layer::tests",
"fields": {
"message": "some json test",
},
}
);
let layer = Layer::default();
test_json(&expected, layer, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
tracing::info!("some json test");
});
}
#[test]
fn flatten() {
let expected = json!(
{
"timestamp": "fake time",
"level": "INFO",
"span": {
"answer": 42,
"name": "json_span",
"number": 3,
},
"spans": [
{
"answer": 42,
"name": "json_span",
"number": 3,
},
],
"target": "json_subscriber::fmt::layer::tests",
"message": "some json test",
}
);
let layer = Layer::default()
.flatten_event(true)
.with_current_span(true)
.with_span_list(true);
test_json(&expected, layer, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
tracing::info!("some json test");
});
}
#[test]
fn flatten_conflict() {
// This probably should not work like this. But it's an open question how it *should* work.
// Notice that there is `level` twice so this is not a valid JSON.
#[rustfmt::skip]
let expected = "{\"level\":\"INFO\",\"timestamp\":\"fake time\",\"level\":\"this is a bug\",\"message\":\"some json test\"}\n";
let layer = Layer::default()
.flatten_event(true)
.with_current_span(false)
.with_span_list(false)
.with_target(false);
let actual = produce_log_line(layer, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
tracing::info!(level = "this is a bug", "some json test");
});
assert_eq!(expected, actual);
}
#[test]
fn flatten_spans() {
let expected = json!(
{
"timestamp": "fake time",
"level": "INFO",
"spans": {
"answer": 42,
"name": "child_span",
"number": 100,
"text": "text",
},
"target": "json_subscriber::fmt::layer::tests",
"fields": {
"message": "some json test",
},
}
);
let layer = Layer::default()
.with_flat_span_list(true)
.with_current_span(false);
test_json(&expected, layer, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
let child =
tracing::info_span!("child_span", number = 100, text = tracing::field::Empty);
let _guard = child.clone().entered();
child.record("text", "text");
tracing::info!("some json test");
});
}
#[test]
fn target_quote() {
let expected = json!(
{
"timestamp": "fake time",
"target": "\"",
"fields": {
"message": "some json test",
},
}
);
let layer = Layer::default()
.with_span_list(false)
.with_current_span(false)
.with_level(false);
test_json(&expected, layer, || {
tracing::info!(target: "\"", "some json test");
});
}
#[test]
fn target_backslash() {
let expected = json!(
{
"timestamp": "fake time",
"target": "\\hello\\\\world\\",
"fields": {
"message": "some json test",
},
}
);
let layer = Layer::default()
.with_span_list(false)
.with_current_span(false)
.with_level(false);
test_json(&expected, layer, || {
tracing::info!(target: "\\hello\\\\world\\", "some json test");
});
}
}