tracing_serde/lib.rs
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
//! # tracing-serde
//!
//! An adapter for serializing [`tracing`] types using [`serde`].
//!
//! [![Documentation][docs-badge]][docs-url]
//! [![Documentation (master)][docs-master-badge]][docs-master-url]
//!
//! [docs-badge]: https://docs.rs/tracing-serde/badge.svg
//! [docs-url]: crate
//! [docs-master-badge]: https://img.shields.io/badge/docs-master-blue
//! [docs-master-url]: https://tracing-rs.netlify.com/tracing_serde
//!
//! ## Overview
//!
//! [`tracing`] is a framework for instrumenting Rust programs to collect
//! scoped, structured, and async-aware diagnostics.`tracing-serde` enables
//! serializing `tracing` types using [`serde`].
//!
//! Traditional logging is based on human-readable text messages.
//! `tracing` gives us machine-readable structured diagnostic
//! information. This lets us interact with diagnostic data
//! programmatically. With `tracing-serde`, you can implement a
//! `Collector` to serialize your `tracing` types and make use of the
//! existing ecosystem of `serde` serializers to talk with distributed
//! tracing systems.
//!
//! Serializing diagnostic information allows us to do more with our logged
//! values. For instance, when working with logging data in JSON gives us
//! pretty-print when we're debugging in development and you can emit JSON
//! and tracing data to monitor your services in production.
//!
//! The `tracing` crate provides the APIs necessary for instrumenting
//! libraries and applications to emit trace data.
//!
//! *Compiler support: [requires `rustc` 1.63+][msrv]*
//!
//! [msrv]: #supported-rust-versions
//!
//! ## Usage
//!
//! First, add this to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! tracing = "0.1"
//! tracing-serde = "0.1"
//! ```
//!
//! Next, add this to your crate:
//!
//! ```rust
//! use tracing_serde::AsSerde;
//! ```
//!
//! Please read the [`tracing` documentation](https://docs.rs/tracing/latest/tracing/index.html)
//! for more information on how to create trace data.
//!
//! This crate provides the `as_serde` function, via the `AsSerde` trait,
//! which enables serializing the `Attributes`, `Event`, `Id`, `Metadata`,
//! and `Record` `tracing` values.
//!
//! For the full example, please see the [examples](../examples) folder.
//!
//! Implement a `Collector` to format the serialization of `tracing`
//! types how you'd like.
//!
//! ```rust
//! # use tracing_core::{Collect, Metadata, Event};
//! # use tracing_core::span::{Attributes, Current, Id, Record};
//! # use std::sync::atomic::{AtomicUsize, Ordering};
//! use tracing_serde::AsSerde;
//! use serde_json::json;
//!
//! pub struct JsonCollector {
//! next_id: AtomicUsize, // you need to assign span IDs, so you need a counter
//! }
//!
//! impl JsonCollector {
//! fn new() -> Self {
//! Self { next_id: 1.into() }
//! }
//! }
//!
//! impl Collect for JsonCollector {
//!
//! fn new_span(&self, attrs: &Attributes<'_>) -> Id {
//! let id = self.next_id.fetch_add(1, Ordering::Relaxed);
//! let id = Id::from_u64(id as u64);
//! let json = json!({
//! "new_span": {
//! "attributes": attrs.as_serde(),
//! "id": id.as_serde(),
//! }});
//! println!("{}", json);
//! id
//! }
//!
//! fn event(&self, event: &Event<'_>) {
//! let json = json!({
//! "event": event.as_serde(),
//! });
//! println!("{}", json);
//! }
//!
//! // ...
//! # fn enabled(&self, _: &Metadata<'_>) -> bool { true }
//! # fn enter(&self, _: &Id) {}
//! # fn exit(&self, _: &Id) {}
//! # fn record(&self, _: &Id, _: &Record<'_>) {}
//! # fn record_follows_from(&self, _: &Id, _: &Id) {}
//! # fn current_span(&self) -> Current { Current::unknown() }
//! }
//! ```
//!
//! After you implement your `Collector`, you can use your `tracing`
//! collector (`JsonCollector` in the above example) to record serialized
//! trace data.
//!
//! ## Crate Feature Flags
//!
//! The following crate feature flags are available:
//!
//! * `std`: Depend on the Rust standard library (enabled by default).
//!
//! `no_std` users may disable this feature with `default-features = false`:
//!
//! ```toml
//! [dependencies]
//! tracing-serde = { version = "0.2", default-features = false }
//! ```
//
//! **Note**:`tracing-serde`'s `no_std` support requires `liballoc`.
//!
//! ## Supported Rust Versions
//!
//! Tracing is built against the latest stable release. The minimum supported
//! version is 1.63. The current Tracing version is not guaranteed to build on
//! Rust versions earlier than the minimum supported version.
//!
//! Tracing follows the same compiler support policies as the rest of the Tokio
//! project. The current stable Rust compiler and the three most recent minor
//! versions before it will always be supported. For example, if the current
//! stable compiler version is 1.69, the minimum supported version will not be
//! increased past 1.66, three minor versions prior. Increasing the minimum
//! supported compiler version is not considered a semver breaking change as
//! long as doing so complies with this policy.
//!
//! [`tracing`]: https://crates.io/crates/tracing
//! [`serde`]: https://crates.io/crates/serde
#![doc(
html_logo_url = "https://raw.githubusercontent.com/tokio-rs/tracing/master/assets/logo-type.png",
html_favicon_url = "https://raw.githubusercontent.com/tokio-rs/tracing/master/assets/favicon.ico",
issue_tracker_base_url = "https://github.com/tokio-rs/tracing/issues/"
)]
#![warn(
missing_debug_implementations,
// missing_docs, // TODO: add documentation
rust_2018_idioms,
unreachable_pub,
bad_style,
dead_code,
improper_ctypes,
non_shorthand_field_patterns,
no_mangle_generic_items,
overflowing_literals,
path_statements,
patterns_in_fns_without_body,
private_interfaces,
private_bounds,
unconditional_recursion,
unused,
unused_allocation,
unused_comparisons,
unused_parens,
while_true
)]
// Support using tracing-serde without the standard library!
#![cfg_attr(not(feature = "std"), no_std)]
use core::fmt;
use serde::{
ser::{SerializeMap, SerializeSeq, SerializeStruct, SerializeTupleStruct, Serializer},
Serialize,
};
use tracing_core::{
event::Event,
field::{Field, FieldSet, Visit},
metadata::{Level, Metadata},
span::{Attributes, Id, Record},
};
pub mod fields;
#[derive(Debug)]
pub struct SerializeField<'a>(&'a Field);
impl<'a> Serialize for SerializeField<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.0.name())
}
}
#[derive(Debug)]
pub struct SerializeFieldSet<'a>(&'a FieldSet);
impl<'a> Serialize for SerializeFieldSet<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
for element in self.0 {
seq.serialize_element(&SerializeField(&element))?;
}
seq.end()
}
}
#[derive(Debug)]
pub struct SerializeLevel<'a>(&'a Level);
impl<'a> Serialize for SerializeLevel<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if self.0 == &Level::ERROR {
serializer.serialize_str("ERROR")
} else if self.0 == &Level::WARN {
serializer.serialize_str("WARN")
} else if self.0 == &Level::INFO {
serializer.serialize_str("INFO")
} else if self.0 == &Level::DEBUG {
serializer.serialize_str("DEBUG")
} else if self.0 == &Level::TRACE {
serializer.serialize_str("TRACE")
} else {
unreachable!()
}
}
}
#[derive(Debug)]
pub struct SerializeId<'a>(&'a Id);
impl<'a> Serialize for SerializeId<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_tuple_struct("Id", 1)?;
state.serialize_field(&self.0.into_u64())?;
state.end()
}
}
#[derive(Debug)]
pub struct SerializeMetadata<'a>(&'a Metadata<'a>);
impl<'a> Serialize for SerializeMetadata<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("Metadata", 9)?;
state.serialize_field("name", self.0.name())?;
state.serialize_field("target", self.0.target())?;
state.serialize_field("level", &SerializeLevel(self.0.level()))?;
state.serialize_field("module_path", &self.0.module_path())?;
state.serialize_field("file", &self.0.file())?;
state.serialize_field("line", &self.0.line())?;
state.serialize_field("fields", &SerializeFieldSet(self.0.fields()))?;
state.serialize_field("is_span", &self.0.is_span())?;
state.serialize_field("is_event", &self.0.is_event())?;
state.end()
}
}
/// Implements `serde::Serialize` to write `Event` data to a serializer.
#[derive(Debug)]
pub struct SerializeEvent<'a>(&'a Event<'a>);
impl<'a> Serialize for SerializeEvent<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut serializer = serializer.serialize_struct("Event", 2)?;
serializer.serialize_field("metadata", &SerializeMetadata(self.0.metadata()))?;
let mut visitor = SerdeStructVisitor {
serializer,
state: Ok(()),
};
self.0.record(&mut visitor);
visitor.finish()
}
}
/// Implements `serde::Serialize` to write `Attributes` data to a serializer.
#[derive(Debug)]
pub struct SerializeAttributes<'a>(&'a Attributes<'a>);
impl<'a> Serialize for SerializeAttributes<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut serializer = serializer.serialize_struct("Attributes", 3)?;
serializer.serialize_field("metadata", &SerializeMetadata(self.0.metadata()))?;
serializer.serialize_field("parent", &self.0.parent().map(SerializeId))?;
serializer.serialize_field("is_root", &self.0.is_root())?;
let mut visitor = SerdeStructVisitor {
serializer,
state: Ok(()),
};
self.0.record(&mut visitor);
visitor.finish()
}
}
/// Implements `serde::Serialize` to write `Record` data to a serializer.
#[derive(Debug)]
pub struct SerializeRecord<'a>(&'a Record<'a>);
impl<'a> Serialize for SerializeRecord<'a> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let serializer = serializer.serialize_map(None)?;
let mut visitor = SerdeMapVisitor::new(serializer);
self.0.record(&mut visitor);
visitor.finish()
}
}
/// Implements `tracing_core::field::Visit` for some `serde::ser::SerializeMap`.
#[derive(Debug)]
pub struct SerdeMapVisitor<S: SerializeMap> {
serializer: S,
state: Result<(), S::Error>,
}
impl<S> SerdeMapVisitor<S>
where
S: SerializeMap,
{
/// Create a new map visitor.
pub fn new(serializer: S) -> Self {
Self {
serializer,
state: Ok(()),
}
}
/// Completes serializing the visited object, returning `Ok(())` if all
/// fields were serialized correctly, or `Error(S::Error)` if a field could
/// not be serialized.
pub fn finish(self) -> Result<S::Ok, S::Error> {
self.state?;
self.serializer.end()
}
/// Completes serializing the visited object, returning ownership of the underlying serializer
/// if all fields were serialized correctly, or `Err(S::Error)` if a field could not be
/// serialized.
pub fn take_serializer(self) -> Result<S, S::Error> {
self.state?;
Ok(self.serializer)
}
}
impl<S> Visit for SerdeMapVisitor<S>
where
S: SerializeMap,
{
fn record_bool(&mut self, field: &Field, value: bool) {
// If previous fields serialized successfully, continue serializing,
// otherwise, short-circuit and do nothing.
if self.state.is_ok() {
self.state = self.serializer.serialize_entry(field.name(), &value)
}
}
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
if self.state.is_ok() {
self.state = self
.serializer
.serialize_entry(field.name(), &format_args!("{:?}", value))
}
}
fn record_u64(&mut self, field: &Field, value: u64) {
if self.state.is_ok() {
self.state = self.serializer.serialize_entry(field.name(), &value)
}
}
fn record_i64(&mut self, field: &Field, value: i64) {
if self.state.is_ok() {
self.state = self.serializer.serialize_entry(field.name(), &value)
}
}
fn record_f64(&mut self, field: &Field, value: f64) {
if self.state.is_ok() {
self.state = self.serializer.serialize_entry(field.name(), &value)
}
}
fn record_str(&mut self, field: &Field, value: &str) {
if self.state.is_ok() {
self.state = self.serializer.serialize_entry(field.name(), &value)
}
}
}
/// Implements `tracing_core::field::Visit` for some `serde::ser::SerializeStruct`.
#[derive(Debug)]
pub struct SerdeStructVisitor<S: SerializeStruct> {
serializer: S,
state: Result<(), S::Error>,
}
impl<S> Visit for SerdeStructVisitor<S>
where
S: SerializeStruct,
{
fn record_bool(&mut self, field: &Field, value: bool) {
// If previous fields serialized successfully, continue serializing,
// otherwise, short-circuit and do nothing.
if self.state.is_ok() {
self.state = self.serializer.serialize_field(field.name(), &value)
}
}
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
if self.state.is_ok() {
self.state = self
.serializer
.serialize_field(field.name(), &format_args!("{:?}", value))
}
}
fn record_u64(&mut self, field: &Field, value: u64) {
if self.state.is_ok() {
self.state = self.serializer.serialize_field(field.name(), &value)
}
}
fn record_i64(&mut self, field: &Field, value: i64) {
if self.state.is_ok() {
self.state = self.serializer.serialize_field(field.name(), &value)
}
}
fn record_f64(&mut self, field: &Field, value: f64) {
if self.state.is_ok() {
self.state = self.serializer.serialize_field(field.name(), &value)
}
}
fn record_str(&mut self, field: &Field, value: &str) {
if self.state.is_ok() {
self.state = self.serializer.serialize_field(field.name(), &value)
}
}
}
impl<S: SerializeStruct> SerdeStructVisitor<S> {
/// Completes serializing the visited object, returning `Ok(())` if all
/// fields were serialized correctly, or `Error(S::Error)` if a field could
/// not be serialized.
pub fn finish(self) -> Result<S::Ok, S::Error> {
self.state?;
self.serializer.end()
}
}
pub trait AsSerde<'a>: self::sealed::Sealed {
type Serializable: serde::Serialize + 'a;
/// `as_serde` borrows a `tracing` value and returns the serialized value.
fn as_serde(&'a self) -> Self::Serializable;
}
impl<'a> AsSerde<'a> for tracing_core::Metadata<'a> {
type Serializable = SerializeMetadata<'a>;
fn as_serde(&'a self) -> Self::Serializable {
SerializeMetadata(self)
}
}
impl<'a> AsSerde<'a> for tracing_core::Event<'a> {
type Serializable = SerializeEvent<'a>;
fn as_serde(&'a self) -> Self::Serializable {
SerializeEvent(self)
}
}
impl<'a> AsSerde<'a> for tracing_core::span::Attributes<'a> {
type Serializable = SerializeAttributes<'a>;
fn as_serde(&'a self) -> Self::Serializable {
SerializeAttributes(self)
}
}
impl<'a> AsSerde<'a> for tracing_core::span::Id {
type Serializable = SerializeId<'a>;
fn as_serde(&'a self) -> Self::Serializable {
SerializeId(self)
}
}
impl<'a> AsSerde<'a> for tracing_core::span::Record<'a> {
type Serializable = SerializeRecord<'a>;
fn as_serde(&'a self) -> Self::Serializable {
SerializeRecord(self)
}
}
impl<'a> AsSerde<'a> for Level {
type Serializable = SerializeLevel<'a>;
fn as_serde(&'a self) -> Self::Serializable {
SerializeLevel(self)
}
}
impl<'a> AsSerde<'a> for Field {
type Serializable = SerializeField<'a>;
fn as_serde(&'a self) -> Self::Serializable {
SerializeField(self)
}
}
impl<'a> AsSerde<'a> for FieldSet {
type Serializable = SerializeFieldSet<'a>;
fn as_serde(&'a self) -> Self::Serializable {
SerializeFieldSet(self)
}
}
impl<'a> self::sealed::Sealed for Event<'a> {}
impl<'a> self::sealed::Sealed for Attributes<'a> {}
impl self::sealed::Sealed for Id {}
impl self::sealed::Sealed for Level {}
impl<'a> self::sealed::Sealed for Record<'a> {}
impl<'a> self::sealed::Sealed for Metadata<'a> {}
impl self::sealed::Sealed for Field {}
impl self::sealed::Sealed for FieldSet {}
mod sealed {
pub trait Sealed {}
}