1// This file is part of Substrate.
23// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
56// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
1011// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
1516// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
1819use tracing::{span::Attributes, Id, Subscriber};
20use tracing_subscriber::{layer::Context, registry::LookupSpan, Layer};
2122/// Span name used for the logging prefix. See macro `sc_tracing::logging::prefix_logs_with!`
23pub const PREFIX_LOG_SPAN: &str = "substrate-log-prefix";
2425/// A `Layer` that captures the prefix span ([`PREFIX_LOG_SPAN`]) which is then used by
26/// [`crate::logging::EventFormat`] to prefix the log lines by customizable string.
27///
28/// See the macro `sc_cli::prefix_logs_with!` for more details.
29pub struct PrefixLayer;
3031impl<S> Layer<S> for PrefixLayer
32where
33S: Subscriber + for<'a> LookupSpan<'a>,
34{
35fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
36let span = match ctx.span(id) {
37Some(span) => span,
38None => {
39// this shouldn't happen!
40debug_assert!(
41false,
42"newly created span with ID {:?} did not exist in the registry; this is a bug!",
43 id
44 );
45return
46},
47 };
4849if span.name() != PREFIX_LOG_SPAN {
50return
51}
5253let mut extensions = span.extensions_mut();
5455if extensions.get_mut::<Prefix>().is_none() {
56let mut s = String::new();
57let mut v = PrefixVisitor(&mut s);
58 attrs.record(&mut v);
5960if !s.is_empty() {
61let fmt_fields = Prefix(s);
62 extensions.insert(fmt_fields);
63 }
64 }
65 }
66}
6768struct PrefixVisitor<'a, W: std::fmt::Write>(&'a mut W);
6970macro_rules! write_node_name {
71 ($method:ident, $type:ty, $format:expr) => {
72fn $method(&mut self, field: &tracing::field::Field, value: $type) {
73if field.name() == "name" {
74let _ = write!(self.0, $format, value);
75 }
76 }
77 };
78}
7980impl<'a, W: std::fmt::Write> tracing::field::Visit for PrefixVisitor<'a, W> {
81write_node_name!(record_debug, &dyn std::fmt::Debug, "[{:?}] ");
82write_node_name!(record_str, &str, "[{}] ");
83write_node_name!(record_i64, i64, "[{}] ");
84write_node_name!(record_u64, u64, "[{}] ");
85write_node_name!(record_bool, bool, "[{}] ");
86}
8788#[derive(Debug)]
89pub(crate) struct Prefix(String);
9091impl Prefix {
92pub(crate) fn as_str(&self) -> &str {
93self.0.as_str()
94 }
95}