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 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
use std::{error::Error, io};
use tracing::{Dispatch, Subscriber};
use tracing_core::LevelFilter;
use tracing_subscriber::{
fmt::{
time::{FormatTime, SystemTime},
MakeWriter,
TestWriter,
},
layer::{Layered, SubscriberExt},
registry::LookupSpan,
reload,
Layer,
Registry,
};
use super::names::{
CURRENT_SPAN,
FIELDS,
FILENAME,
LEVEL,
LINE_NUMBER,
SPAN_LIST,
TARGET,
THREAD_ID,
THREAD_NAME,
TIMESTAMP,
};
use crate::layer::JsonLayer;
/// Configures and constructs `Subscriber`s.
///
/// This should be this library's replacement for [`tracing_subscriber::fmt::SubscriberBuilder`].
///
/// Returns a new [`SubscriberBuilder`] for configuring a [formatting subscriber]. The default value
/// should be mostly equivalent to calling `tracing_subscriber::fmt().json()`.
///
/// # Examples
///
/// Using [`init`] to set the default subscriber:
///
/// ```rust
/// json_subscriber::fmt::SubscriberBuilder::default().init();
/// ```
///
/// Configuring the output format:
///
/// ```rust
/// json_subscriber::fmt()
/// // Configure formatting settings.
/// .with_target(false)
/// .with_timer(tracing_subscriber::fmt::time::uptime())
/// .with_level(true)
/// // Set the subscriber as the default.
/// .init();
/// ```
///
/// [`try_init`] returns an error if the default subscriber could not be set:
///
/// ```rust
/// use std::error::Error;
///
/// fn init_subscriber() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
/// json_subscriber::fmt()
/// // This is no-op. This subscriber uses only JSON.
/// .json()
/// // Configure the subscriber to flatten event fields in the output JSON objects.
/// .flatten_event(true)
/// // Set the subscriber as the default, returning an error if this fails.
/// .try_init()?;
///
/// Ok(())
/// }
/// ```
///
/// Rather than setting the subscriber as the default, [`finish`] _returns_ the
/// constructed subscriber, which may then be passed to other functions:
///
/// ```rust
/// let subscriber = json_subscriber::fmt()
/// .with_max_level(tracing::Level::DEBUG)
/// .finish();
///
/// tracing::subscriber::with_default(subscriber, || {
/// // the subscriber will only be set as the default
/// // inside this closure...
/// })
/// ```
///
/// [formatting subscriber]: Subscriber
/// [`SubscriberBuilder::default()`]: SubscriberBuilder::default
/// [`init`]: SubscriberBuilder::init()
/// [`try_init`]: SubscriberBuilder::try_init()
/// [`finish`]: SubscriberBuilder::finish()
pub struct SubscriberBuilder<W = fn() -> io::Stdout, T = SystemTime, F = LevelFilter> {
make_writer: W,
timer: T,
filter: F,
log_internal_errors: bool,
display_timestamp: bool,
display_target: bool,
display_level: bool,
display_thread_id: bool,
display_thread_name: bool,
display_filename: bool,
display_line_number: bool,
flatten_event: bool,
display_current_span: bool,
display_span_list: bool,
#[cfg(feature = "opentelemetry")]
display_opentelemetry_ids: bool,
}
impl Default for SubscriberBuilder {
fn default() -> Self {
Self {
make_writer: io::stdout,
filter: LevelFilter::INFO,
timer: SystemTime,
log_internal_errors: false,
display_timestamp: true,
display_target: true,
display_level: true,
display_thread_id: false,
display_thread_name: false,
display_filename: false,
display_line_number: false,
flatten_event: false,
display_current_span: true,
display_span_list: true,
#[cfg(feature = "opentelemetry")]
display_opentelemetry_ids: false,
}
}
}
impl<W, T, F> SubscriberBuilder<W, T, F>
where
W: for<'writer> MakeWriter<'writer> + Send + Sync + 'static,
T: FormatTime + Send + Sync + 'static,
F: Layer<Layered<JsonLayer<Registry, W>, Registry>> + 'static,
Layered<F, Layered<JsonLayer<Registry, W>, Registry>>:
tracing_core::Subscriber + Into<Dispatch>,
{
pub(crate) fn layers<S>(self) -> (JsonLayer<S, W>, F)
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
{
let mut layer = JsonLayer::<S>::new(self.make_writer);
if self.display_timestamp {
layer.with_timer(TIMESTAMP, self.timer);
}
if self.display_level {
layer.with_level(LEVEL);
}
if self.display_target {
layer.with_target(TARGET);
}
if self.display_filename {
layer.with_file(FILENAME);
}
if self.display_line_number {
layer.with_line_number(LINE_NUMBER);
}
if self.display_thread_name {
layer.with_thread_names(THREAD_NAME);
}
if self.display_thread_id {
layer.with_thread_ids(THREAD_ID);
}
if self.flatten_event {
layer.with_flattened_event();
} else {
layer.with_event(FIELDS);
}
if self.display_current_span {
layer.with_current_span(CURRENT_SPAN);
}
if self.display_span_list {
layer.with_span_list(SPAN_LIST);
}
(layer, self.filter)
}
/// Finish the builder, returning a new [`Subscriber`] which can be used to [lookup spans].
///
/// [lookup spans]: LookupSpan
pub fn finish(self) -> Layered<F, Layered<JsonLayer<Registry, W>, Registry>> {
let (json_layer, filter_layer) = self.layers();
tracing_subscriber::registry()
.with(json_layer)
.with(filter_layer)
}
/// Install this Subscriber as the global default if one is
/// not already set.
///
/// If the `tracing-log` feature is enabled, this will also install
/// the `LogTracer` to convert `Log` records into `tracing` `Event`s.
///
/// # Errors
/// Returns an Error if the initialization was unsuccessful, likely
/// because a global subscriber was already installed by another
/// call to `try_init`.
pub fn try_init(self) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
use tracing_subscriber::util::SubscriberInitExt;
self.finish().try_init()?;
Ok(())
}
/// Install this Subscriber as the global default.
///
/// If the `tracing-log` feature is enabled, this will also install
/// the `LogTracer` to convert `Log` records into `tracing` `Event`s.
///
/// # Panics
/// Panics if the initialization was unsuccessful, likely because a
/// global subscriber was already installed by another call to `try_init`.
pub fn init(self) {
self.try_init()
.expect("Unable to install global subscriber");
}
}
impl<W, T, F> SubscriberBuilder<W, T, F> {
/// This does nothing. It exists only to mimic `tracing-subscriber`'s API.
#[deprecated(note = "Calling `json()` does nothing.")]
#[must_use]
pub fn json(self) -> Self {
self
}
/// This does nothing. It exists only to mimic `tracing-subscriber`'s API.
#[deprecated(note = "Calling `with_ansi()` does nothing.")]
#[must_use]
pub fn with_ansi(self, _ansi: bool) -> Self {
self
}
/// Sets the [`MakeWriter`] that the [`SubscriberBuilder`] being built will use to write events.
///
/// # Examples
///
/// Using `stderr` rather than `stdout`:
///
/// ```rust
/// use std::io;
///
/// let fmt_subscriber = json_subscriber::fmt()
/// .with_writer(io::stderr);
/// ```
pub fn with_writer<W2>(self, make_writer: W2) -> SubscriberBuilder<W2, T, F>
where
W2: for<'writer> MakeWriter<'writer> + 'static,
{
SubscriberBuilder {
make_writer,
timer: self.timer,
filter: self.filter,
log_internal_errors: self.log_internal_errors,
display_timestamp: self.display_timestamp,
display_target: self.display_target,
display_level: self.display_level,
display_thread_id: self.display_thread_id,
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
flatten_event: self.flatten_event,
display_current_span: self.display_current_span,
display_span_list: self.display_span_list,
#[cfg(feature = "opentelemetry")]
display_opentelemetry_ids: self.display_opentelemetry_ids,
}
}
/// Borrows the [writer] for this subscriber.
///
/// [writer]: MakeWriter
pub fn writer(&self) -> &W {
&self.make_writer
}
/// Mutably borrows the [writer] for this subscriber.
///
/// This method is primarily expected to be used with the
/// [`reload::Handle::modify`](reload::Handle::modify) method.
///
/// # Examples
///
/// ```
/// use tracing_subscriber::{fmt::writer::EitherWriter, reload};
/// # fn main() {
/// let subscriber = json_subscriber::fmt()
/// .with_writer::<Box<dyn Fn() -> EitherWriter<_, _>>>(Box::new(|| EitherWriter::A(std::io::stderr())));
/// let (subscriber, reload_handle) = reload::Layer::new(subscriber);
/// # let subscriber: reload::Layer<_, tracing_subscriber::Registry> = subscriber;
///
/// tracing::info!("This will be logged to stderr");
/// reload_handle.modify(|subscriber| *subscriber.writer_mut() = Box::new(|| EitherWriter::B(std::io::stdout())));
/// tracing::info!("This will be logged to stdout");
/// # }
/// ```
///
/// [writer]: MakeWriter
pub fn writer_mut(&mut self) -> &mut W {
&mut self.make_writer
}
/// Configures the subscriber 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
/// let fmt_subscriber = json_subscriber::fmt::fmt()
/// .with_test_writer();
/// ```
/// [capturing]:
/// https://doc.rust-lang.org/book/ch11-02-running-tests.html#showing-function-output
/// [`TestWriter`]: tracing_subscriber::fmt::writer::TestWriter
pub fn with_test_writer(self) -> SubscriberBuilder<TestWriter, T, F> {
SubscriberBuilder {
make_writer: TestWriter::default(),
timer: self.timer,
filter: self.filter,
log_internal_errors: self.log_internal_errors,
display_timestamp: self.display_timestamp,
display_target: self.display_target,
display_level: self.display_level,
display_thread_id: self.display_thread_id,
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
flatten_event: self.flatten_event,
display_current_span: self.display_current_span,
display_span_list: self.display_span_list,
#[cfg(feature = "opentelemetry")]
display_opentelemetry_ids: self.display_opentelemetry_ids,
}
}
/// Sets whether to write errors during internal operations to stderr.
/// This can help identify problems with serialization and with debugging issues.
///
/// Defaults to false.
#[must_use]
pub fn log_internal_errors(self, log_internal_errors: bool) -> Self {
Self {
log_internal_errors,
..self
}
}
/// Updates the [`MakeWriter`] by applying a function to the existing [`MakeWriter`].
///
/// This sets the [`MakeWriter`] that the subscriber being built will use to write events.
///
/// # Examples
///
/// Redirect output to stderr if level is <= WARN:
///
/// ```rust
/// use tracing::Level;
/// use tracing_subscriber::fmt::writer::MakeWriterExt;
///
/// let stderr = std::io::stderr.with_max_level(Level::WARN);
/// let subscriber = json_subscriber::fmt::fmt()
/// .map_writer(move |w| stderr.or_else(w));
/// ```
pub fn map_writer<W2>(self, f: impl FnOnce(W) -> W2) -> SubscriberBuilder<W2, T, F>
where
W2: for<'writer> MakeWriter<'writer> + 'static,
{
SubscriberBuilder {
make_writer: f(self.make_writer),
timer: self.timer,
filter: self.filter,
log_internal_errors: self.log_internal_errors,
display_timestamp: self.display_timestamp,
display_target: self.display_target,
display_level: self.display_level,
display_thread_id: self.display_thread_id,
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
flatten_event: self.flatten_event,
display_current_span: self.display_current_span,
display_span_list: self.display_span_list,
#[cfg(feature = "opentelemetry")]
display_opentelemetry_ids: self.display_opentelemetry_ids,
}
}
/// Sets the JSON subscriber being built to flatten event metadata.
#[must_use]
pub fn flatten_event(self, flatten_event: bool) -> SubscriberBuilder<W, T, F> {
SubscriberBuilder {
flatten_event,
..self
}
}
/// Sets whether or not the formatter will include the current span in
/// formatted events.
#[must_use]
pub fn with_current_span(self, display_current_span: bool) -> SubscriberBuilder<W, T, F> {
SubscriberBuilder {
display_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.
#[must_use]
pub fn with_span_list(self, display_span_list: bool) -> SubscriberBuilder<W, T, F> {
SubscriberBuilder {
display_span_list,
..self
}
}
/// Use the given [`timer`] for log message timestamps.
///
/// See the [`tracing_subscriber::fmt::time` module][`time` module] for the
/// provided timer implementations.
///
/// Note that using the `time` feature flag on `tracing_subscriber` enables the
/// additional time formatters [`UtcTime`] and [`LocalTime`], which use the
/// [`time` crate] to provide more sophisticated timestamp formatting
/// options.
///
/// [`timer`]: 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
pub fn with_timer<T2>(self, timer: T2) -> SubscriberBuilder<W, T2, F> {
SubscriberBuilder {
make_writer: self.make_writer,
timer,
filter: self.filter,
log_internal_errors: self.log_internal_errors,
display_timestamp: self.display_timestamp,
display_target: self.display_target,
display_level: self.display_level,
display_thread_id: self.display_thread_id,
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
flatten_event: self.flatten_event,
display_current_span: self.display_current_span,
display_span_list: self.display_span_list,
#[cfg(feature = "opentelemetry")]
display_opentelemetry_ids: self.display_opentelemetry_ids,
}
}
/// Do not emit timestamps with log messages.
pub fn without_time(self) -> SubscriberBuilder<W, (), F> {
SubscriberBuilder {
make_writer: self.make_writer,
timer: (),
filter: self.filter,
log_internal_errors: self.log_internal_errors,
display_timestamp: self.display_timestamp,
display_target: self.display_target,
display_level: self.display_level,
display_thread_id: self.display_thread_id,
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
flatten_event: self.flatten_event,
display_current_span: self.display_current_span,
display_span_list: self.display_span_list,
#[cfg(feature = "opentelemetry")]
display_opentelemetry_ids: self.display_opentelemetry_ids,
}
}
// /// Configures how synthesized events are emitted at points in the [span
// /// lifecycle][lifecycle].
// ///
// /// The following options are available:
// ///
// /// - `FmtSpan::NONE`: No events will be synthesized when spans are
// /// created, entered, exited, or closed. Data from spans will still be
// /// included as the context for formatted events. This is the default.
// /// - `FmtSpan::NEW`: An event will be synthesized when spans are created.
// /// - `FmtSpan::ENTER`: An event will be synthesized when spans are entered.
// /// - `FmtSpan::EXIT`: An event will be synthesized when spans are exited.
// /// - `FmtSpan::CLOSE`: An event will be synthesized when a span closes. If
// /// [timestamps are enabled][time] for this formatter, the generated
// /// event will contain fields with the span's _busy time_ (the total
// /// time for which it was entered) and _idle time_ (the total time that
// /// the span existed but was not entered).
// /// - `FmtSpan::ACTIVE`: An event will be synthesized when spans are entered
// /// or exited.
// /// - `FmtSpan::FULL`: Events will be synthesized whenever a span is
// /// created, entered, exited, or closed. If timestamps are enabled, the
// /// close event will contain the span's busy and idle time, as
// /// described above.
// ///
// /// The options can be enabled in any combination. For instance, the following
// /// will synthesize events whenever spans are created and closed:
// ///
// /// ```rust
// /// use tracing_subscriber::fmt::format::FmtSpan;
// /// use tracing_subscriber::fmt;
// ///
// /// let subscriber = fmt()
// /// .with_span_events(FmtSpan::NEW | FmtSpan::CLOSE)
// /// .finish();
// /// ```
// ///
// /// Note that the generated events will only be part of the log output by
// /// this formatter; they will not be recorded by other `Collector`s or by
// /// `Subscriber`s added to this subscriber.
// ///
// /// [lifecycle]: mod@tracing::span#the-span-lifecycle
// /// [time]: SubscriberBuilder::without_time()
// pub fn with_span_events(self, kind: format::FmtSpan) -> Self {
// SubscriberBuilder {
// inner: self.inner.with_span_events(kind),
// ..self
// }
// }
/// Sets whether or not an event's target is displayed.
#[must_use]
pub fn with_target(self, display_target: bool) -> SubscriberBuilder<W, T, F> {
SubscriberBuilder {
display_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(self, display_filename: bool) -> SubscriberBuilder<W, T, F> {
SubscriberBuilder {
display_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(self, display_line_number: bool) -> SubscriberBuilder<W, T, F> {
SubscriberBuilder {
display_line_number,
..self
}
}
/// Sets whether or not an event's level is displayed.
#[must_use]
pub fn with_level(self, display_level: bool) -> SubscriberBuilder<W, T, F> {
SubscriberBuilder {
display_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(self, display_thread_name: bool) -> SubscriberBuilder<W, T, F> {
SubscriberBuilder {
display_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(self, display_thread_id: bool) -> SubscriberBuilder<W, T, F> {
SubscriberBuilder {
display_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(self, display_opentelemetry_ids: bool) -> Self {
SubscriberBuilder {
display_opentelemetry_ids,
..self
}
}
/// Sets the [`EnvFilter`] that the collector will use to determine if
/// a span or event is enabled.
///
/// Note that this method requires the "env-filter" feature flag to be enabled.
///
/// If a filter was previously set, or a maximum level was set by the
/// [`with_max_level`] method, that value is replaced by the new filter.
///
/// # Examples
///
/// Setting a filter based on the value of the `RUST_LOG` environment
/// variable:
/// ```rust
/// use tracing_subscriber::EnvFilter;
///
/// json_subscriber::fmt()
/// .with_env_filter(EnvFilter::from_default_env())
/// .init();
/// ```
///
/// Setting a filter based on a pre-set filter directive string:
/// ```rust
/// json_subscriber::fmt()
/// .with_env_filter("my_crate=info,my_crate::my_mod=debug,[my_span]=trace")
/// .init();
/// ```
///
/// Adding additional directives to a filter constructed from an env var:
/// ```rust
/// use tracing_subscriber::filter::{EnvFilter, LevelFilter};
///
/// # fn filter() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
/// let filter = EnvFilter::try_from_env("MY_CUSTOM_FILTER_ENV_VAR")?
/// // Set the base level when not matched by other directives to WARN.
/// .add_directive(LevelFilter::WARN.into())
/// // Set the max level for `my_crate::my_mod` to DEBUG, overriding
/// // any directives parsed from the env variable.
/// .add_directive("my_crate::my_mod=debug".parse()?);
///
/// json_subscriber::fmt()
/// .with_env_filter(filter)
/// .try_init()?;
/// # Ok(())}
/// ```
/// [`EnvFilter`]: tracing_subscriber::filter::EnvFilter
/// [`with_max_level`]: Self::with_max_level()
#[cfg(feature = "env-filter")]
#[cfg_attr(docsrs, doc(cfg(feature = "env-filter")))]
pub fn with_env_filter(
self,
filter: impl Into<tracing_subscriber::EnvFilter>,
) -> SubscriberBuilder<W, T, tracing_subscriber::EnvFilter> {
SubscriberBuilder {
make_writer: self.make_writer,
timer: self.timer,
filter: filter.into(),
log_internal_errors: self.log_internal_errors,
display_timestamp: self.display_timestamp,
display_target: self.display_target,
display_level: self.display_level,
display_thread_id: self.display_thread_id,
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
flatten_event: self.flatten_event,
display_current_span: self.display_current_span,
display_span_list: self.display_span_list,
#[cfg(feature = "opentelemetry")]
display_opentelemetry_ids: self.display_opentelemetry_ids,
}
}
/// Sets the maximum [verbosity level] that will be enabled by the
/// collector.
///
/// If the max level has already been set, or a [`EnvFilter`] was added by
/// [`with_env_filter`], this replaces that configuration with the new
/// maximum level.
///
/// # Examples
///
/// Enable up to the `DEBUG` verbosity level:
/// ```rust
/// use tracing_subscriber::fmt;
/// use tracing::Level;
///
/// fmt()
/// .with_max_level(Level::DEBUG)
/// .init();
/// ```
/// This collector won't record any spans or events!
/// ```rust
/// use tracing_subscriber::{fmt, filter::LevelFilter};
///
/// let subscriber = fmt()
/// .with_max_level(LevelFilter::OFF)
/// .finish();
/// ```
/// [verbosity level]: tracing_core::Level
/// [`EnvFilter`]: struct@tracing_subscriber::filter::EnvFilter
/// [`with_env_filter`]: fn@Self::with_env_filter
pub fn with_max_level(
self,
filter: impl Into<LevelFilter>,
) -> SubscriberBuilder<W, T, LevelFilter> {
SubscriberBuilder {
make_writer: self.make_writer,
timer: self.timer,
filter: filter.into(),
log_internal_errors: self.log_internal_errors,
display_timestamp: self.display_timestamp,
display_target: self.display_target,
display_level: self.display_level,
display_thread_id: self.display_thread_id,
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
flatten_event: self.flatten_event,
display_current_span: self.display_current_span,
display_span_list: self.display_span_list,
#[cfg(feature = "opentelemetry")]
display_opentelemetry_ids: self.display_opentelemetry_ids,
}
}
/// Configures the collector being built to allow filter reloading at
/// runtime.
///
/// The returned builder will have a [`reload_handle`] method, which returns
/// a [`reload::Handle`] that may be used to set a new filter value.
///
/// For example:
///
/// ```rust
/// # use tracing_subscriber::prelude::*;
/// use tracing::Level;
///
/// let builder = json_subscriber::fmt()
/// // Set a max level filter on the collector
/// .with_max_level(Level::INFO)
/// .with_filter_reloading();
///
/// // Get a handle for modifying the collector's max level filter.
/// let handle = builder.reload_handle();
///
/// // Finish building the collector, and set it as the default.
/// builder.finish().init();
///
/// // Currently, the max level is INFO, so this event will be disabled.
/// tracing::debug!("this is not recorded!");
///
/// // Use the handle to set a new max level filter.
/// // (this returns an error if the collector has been dropped, which shouldn't
/// // happen in this example.)
/// handle.reload(Level::DEBUG).expect("the collector should still exist");
///
/// // Now, the max level is INFO, so this event will be recorded.
/// tracing::debug!("this is recorded!");
/// ```
///
/// [`reload_handle`]: Self::reload_handle
#[cfg(feature = "env-filter")]
#[cfg_attr(docsrs, doc(cfg(feature = "env-filter")))]
pub fn with_filter_reloading<S>(self) -> SubscriberBuilder<W, T, reload::Layer<F, S>> {
let (filter, _) = reload::Layer::new(self.filter);
SubscriberBuilder {
make_writer: self.make_writer,
timer: self.timer,
filter,
log_internal_errors: self.log_internal_errors,
display_timestamp: self.display_timestamp,
display_target: self.display_target,
display_level: self.display_level,
display_thread_id: self.display_thread_id,
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
flatten_event: self.flatten_event,
display_current_span: self.display_current_span,
display_span_list: self.display_span_list,
#[cfg(feature = "opentelemetry")]
display_opentelemetry_ids: self.display_opentelemetry_ids,
}
}
}
impl<W, T, F, S> SubscriberBuilder<W, T, reload::Layer<F, S>> {
/// Returns a `Handle` that may be used to reload the constructed collector's
/// filter.
pub fn reload_handle(&self) -> reload::Handle<F, S> {
self.filter.handle()
}
}
#[cfg(test)]
mod tests {
//! These tests are copied from `tracing-subscriber` for compatibility.
use std::path::Path;
use tracing::subscriber::with_default;
use tracing_core::Dispatch;
use tracing_subscriber::{filter::LevelFilter, registry::LookupSpan, Registry};
use super::SubscriberBuilder;
use crate::{
layer::JsonLayer,
tests::{MockMakeWriter, MockTime},
};
fn subscriber() -> SubscriberBuilder {
SubscriberBuilder::default()
}
#[rustfmt::skip]
// TODO uncomment when `tracing` releases version where `&[u8]: Value`
// #[test]
// fn json() {
// let expected =
// "{\"timestamp\":\"fake time\",\"level\":\"INFO\",\"span\":{\"answer\":42,\"name\":\"json_span\",\"number\":3,\"slice\":[97,98,99]},\"spans\":[{\"answer\":42,\"name\":\"json_span\",\"number\":3,\"slice\":[97,98,99]}],\"target\":\"tracing_json::layer::test\",\"fields\":{\"message\":\"some json test\"}}\n";
// let collector = subscriber()
// .flatten_event(false)
// .with_current_span(true)
// .with_span_list(true);
// test_json(expected, collector, || {
// let span = tracing::span!(
// tracing::Level::INFO,
// "json_span",
// answer = 42,
// number = 3,
// slice = &b"abc"[..]
// );
// let _guard = span.enter();
// tracing::info!("some json test");
// });
// }
#[test]
fn json_filename() {
let current_path = Path::new("src")
.join("fmt")
.join("builder.rs")
.to_str()
.expect("path must be valid unicode")
// escape windows backslashes
.replace('\\', "\\\\");
#[rustfmt::skip]
let expected = &format!("{}{}{}",
"{\"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::builder::tests\",\"filename\":\"",
current_path,
"\",\"fields\":{\"message\":\"some json test\"}}\n"
);
let collector = subscriber()
.flatten_event(false)
.with_current_span(true)
.with_file(true)
.with_span_list(true);
test_json(expected, collector, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
tracing::info!("some json test");
});
}
#[test]
fn json_line_number() {
#[rustfmt::skip]
let expected = "{\"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::builder::tests\",\"line_number\":42,\"fields\":{\"message\":\"some json test\"}}\n";
let collector = subscriber()
.flatten_event(false)
.with_current_span(true)
.with_line_number(true)
.with_span_list(true);
test_json_with_line_number(expected, collector, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
tracing::info!("some json test");
});
}
#[test]
fn json_flattened_event() {
#[rustfmt::skip]
let expected = "{\"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::builder::tests\",\"message\":\"some json test\"}\n";
let collector = subscriber()
.flatten_event(true)
.with_current_span(true)
.with_span_list(true);
test_json(expected, collector, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
tracing::info!("some json test");
});
}
#[test]
fn json_disabled_current_span_event() {
#[rustfmt::skip]
let expected = "{\"timestamp\":\"fake time\",\"level\":\"INFO\",\"spans\":[{\"answer\":42,\"name\":\"json_span\",\"number\":3}],\"target\":\"json_subscriber::fmt::builder::tests\",\"fields\":{\"message\":\"some json test\"}}\n";
let collector = subscriber()
.flatten_event(false)
.with_current_span(false)
.with_span_list(true);
test_json(expected, collector, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
tracing::info!("some json test");
});
}
#[test]
fn json_disabled_span_list_event() {
#[rustfmt::skip]
let expected = "{\"timestamp\":\"fake time\",\"level\":\"INFO\",\"span\":{\"answer\":42,\"name\":\"json_span\",\"number\":3},\"target\":\"json_subscriber::fmt::builder::tests\",\"fields\":{\"message\":\"some json test\"}}\n";
let collector = subscriber()
.flatten_event(false)
.with_current_span(true)
.with_span_list(false);
test_json(expected, collector, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
tracing::info!("some json test");
});
}
#[test]
fn json_nested_span() {
#[rustfmt::skip]
let expected = "{\"timestamp\":\"fake time\",\"level\":\"INFO\",\"span\":{\"answer\":43,\"name\":\"nested_json_span\",\"number\":4},\"spans\":[{\"answer\":42,\"name\":\"json_span\",\"number\":3},{\"answer\":43,\"name\":\"nested_json_span\",\"number\":4}],\"target\":\"json_subscriber::fmt::builder::tests\",\"fields\":{\"message\":\"some json test\"}}\n";
let collector = subscriber()
.flatten_event(false)
.with_current_span(true)
.with_span_list(true);
test_json(expected, collector, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
let span = tracing::span!(
tracing::Level::INFO,
"nested_json_span",
answer = 43,
number = 4
);
let _guard = span.enter();
tracing::info!("some json test");
});
}
#[test]
fn json_explicit_span() {
#[rustfmt::skip]
let expected = "{\"timestamp\":\"fake time\",\"level\":\"INFO\",\"span\":{\"answer\":43,\"name\":\"nested_json_span\",\"number\":4},\"spans\":[{\"answer\":42,\"name\":\"json_span\",\"number\":3},{\"answer\":43,\"name\":\"nested_json_span\",\"number\":4}],\"target\":\"json_subscriber::fmt::builder::tests\",\"fields\":{\"message\":\"some json test\"}}\n";
let collector = subscriber()
.flatten_event(false)
.with_current_span(true)
.with_span_list(true);
test_json(expected, collector, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let span = tracing::span!(
parent: &span,
tracing::Level::INFO,
"nested_json_span",
answer = 43,
number = 4
);
// No enter
tracing::info!(parent: &span, "some json test");
});
}
#[test]
fn json_explicit_no_span() {
#[rustfmt::skip]
let expected = "{\"timestamp\":\"fake time\",\"level\":\"INFO\",\"target\":\"json_subscriber::fmt::builder::tests\",\"fields\":{\"message\":\"some json test\"}}\n";
let collector = subscriber()
.flatten_event(false)
.with_current_span(true)
.with_span_list(true);
test_json(expected, collector, || {
let span = tracing::span!(tracing::Level::INFO, "json_span", answer = 42, number = 3);
let _guard = span.enter();
let span = tracing::span!(
tracing::Level::INFO,
"nested_json_span",
answer = 43,
number = 4
);
let _guard = span.enter();
tracing::info!(parent: None, "some json test");
});
}
#[test]
fn json_no_span() {
#[rustfmt::skip]
let expected = "{\"timestamp\":\"fake time\",\"level\":\"INFO\",\"target\":\"json_subscriber::fmt::builder::tests\",\"fields\":{\"message\":\"some json test\"}}\n";
let collector = subscriber()
.flatten_event(false)
.with_current_span(true)
.with_span_list(true);
test_json(expected, collector, || {
tracing::info!("some json test");
});
}
#[test]
fn record_works() {
// This test reproduces tracing issue #707, where using `Span::record` causes
// any events inside the span to be ignored.
let buffer = MockMakeWriter::default();
let subscriber = SubscriberBuilder::default()
.with_writer(buffer.clone())
.finish();
with_default(subscriber, || {
tracing::info!("an event outside the root span");
assert_eq!(
parse_as_json(&buffer)["fields"]["message"],
"an event outside the root span"
);
let span = tracing::info_span!("the span", na = tracing::field::Empty);
span.record("na", "value");
let _enter = span.enter();
tracing::info!("an event inside the root span");
assert_eq!(
parse_as_json(&buffer)["fields"]["message"],
"an event inside the root span"
);
});
}
fn parse_as_json(buffer: &MockMakeWriter) -> serde_json::Value {
let buf = String::from_utf8(buffer.buf().to_vec()).unwrap();
let json = buf
.lines()
.last()
.expect("expected at least one line to be written!");
match serde_json::from_str(json) {
Ok(v) => v,
Err(e) => {
panic!(
"assertion failed: JSON shouldn't be malformed\n error: {e}\n json: {json}"
)
},
}
}
fn test_json<T>(expected: &str, builder: SubscriberBuilder, producer: impl FnOnce() -> T) {
let make_writer = MockMakeWriter::default();
let collector = builder
.with_writer(make_writer.clone())
.with_timer(MockTime)
.finish();
with_default(collector, producer);
let buf = make_writer.buf();
let actual = dbg!(std::str::from_utf8(&buf[..]).unwrap());
assert_eq!(
serde_json::from_str::<std::collections::HashMap<&str, serde_json::Value>>(expected)
.unwrap(),
serde_json::from_str(actual).unwrap()
);
}
fn test_json_with_line_number<T>(
expected: &str,
builder: SubscriberBuilder,
producer: impl FnOnce() -> T,
) {
let make_writer = MockMakeWriter::default();
let collector = builder
.with_writer(make_writer.clone())
.with_timer(MockTime)
.finish();
with_default(collector, producer);
let buf = make_writer.buf();
let actual = std::str::from_utf8(&buf[..]).unwrap();
let mut expected =
serde_json::from_str::<std::collections::HashMap<&str, serde_json::Value>>(expected)
.unwrap();
let expect_line_number = expected.remove("line_number").is_some();
let mut actual: std::collections::HashMap<&str, serde_json::Value> =
serde_json::from_str(actual).unwrap();
let line_number = actual.remove("line_number");
if expect_line_number {
assert_eq!(line_number.map(|x| x.is_number()), Some(true));
} else {
assert!(line_number.is_none());
}
assert_eq!(actual, expected);
}
#[test]
fn subscriber_downcasts() {
let subscriber = SubscriberBuilder::default().finish();
let dispatch = Dispatch::new(subscriber);
assert!(dispatch.downcast_ref::<Registry>().is_some());
}
#[test]
fn subscriber_downcasts_to_parts() {
let subscriber = SubscriberBuilder::default().finish();
let dispatch = Dispatch::new(subscriber);
assert!(dispatch.downcast_ref::<JsonLayer>().is_some());
assert!(dispatch.downcast_ref::<LevelFilter>().is_some());
}
#[test]
fn is_lookup_span() {
fn assert_lookup_span<T: for<'a> LookupSpan<'a>>(_: T) {}
let subscriber = SubscriberBuilder::default().finish();
assert_lookup_span(subscriber);
}
#[test]
#[cfg(feature = "env-filter")]
fn reload_filter_works() {
use tracing::Level;
use tracing_subscriber::util::SubscriberInitExt;
let builder = SubscriberBuilder::default()
// Set a max level filter on the collector
.with_max_level(Level::INFO)
.with_filter_reloading();
// Get a handle for modifying the collector's max level filter.
let handle = builder.reload_handle();
// Finish building the collector, and set it as the default.
builder.finish().init();
// Currently, the max level is INFO, so this event will be disabled.
tracing::debug!("this is not recorded!");
// Use the handle to set a new max level filter.
// (this returns an error if the collector has been dropped, which shouldn't
// happen in this example.)
handle
.reload(Level::DEBUG)
.expect("the collector should still exist");
// Now, the max level is INFO, so this event will be recorded.
tracing::debug!("this is recorded!");
}
}