referrerpolicy=no-referrer-when-downgrade

sc_tracing/logging/
directives.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Substrate.
3// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
4
5// Substrate is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9
10// Substrate is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14
15// You should have received a copy of the GNU General Public License
16// along with Substrate. If not, see <https://www.gnu.org/licenses/>.
17
18use parking_lot::Mutex;
19use std::sync::OnceLock;
20use tracing_subscriber::{
21	filter::Directive, fmt as tracing_fmt, layer, reload::Handle, EnvFilter, Registry,
22};
23
24// Handle to reload the tracing log filter
25static FILTER_RELOAD_HANDLE: OnceLock<Handle<EnvFilter, SCSubscriber>> = OnceLock::new();
26// Directives that are defaulted to when resetting the log filter
27static DEFAULT_DIRECTIVES: OnceLock<Mutex<Vec<String>>> = OnceLock::new();
28// Current state of log filter
29static CURRENT_DIRECTIVES: OnceLock<Mutex<Vec<String>>> = OnceLock::new();
30
31/// Add log filter directive(s) to the defaults
32///
33/// The syntax is identical to the CLI `<target>=<level>`:
34///
35/// `sync=debug,state=trace`
36pub(crate) fn add_default_directives(directives: &str) {
37	DEFAULT_DIRECTIVES
38		.get_or_init(|| Mutex::new(Vec::new()))
39		.lock()
40		.push(directives.to_owned());
41	add_directives(directives);
42}
43
44/// Add directives to current directives.
45pub fn add_directives(directives: &str) {
46	CURRENT_DIRECTIVES
47		.get_or_init(|| Mutex::new(Vec::new()))
48		.lock()
49		.push(directives.to_owned());
50}
51
52/// Returns the current directives.
53pub fn get_directives() -> Vec<String> {
54	CURRENT_DIRECTIVES.get_or_init(|| Mutex::new(Vec::new())).lock().clone()
55}
56
57/// Parse `Directive` and add to default directives if successful.
58///
59/// Ensures the supplied directive will be restored when resetting the log filter.
60pub(crate) fn parse_default_directive(directive: &str) -> super::Result<Directive> {
61	let dir = directive.parse()?;
62	add_default_directives(directive);
63	Ok(dir)
64}
65
66/// Reload the logging filter with the supplied directives added to the existing directives
67pub fn reload_filter() -> Result<(), String> {
68	let mut env_filter = EnvFilter::default();
69	if let Some(current_directives) = CURRENT_DIRECTIVES.get() {
70		// Use join and then split in case any directives added together
71		for directive in current_directives.lock().join(",").split(',').map(|d| d.parse()) {
72			match directive {
73				Ok(dir) => env_filter = env_filter.add_directive(dir),
74				Err(invalid_directive) => {
75					log::warn!(
76						target: "tracing",
77						"Unable to parse directive while setting log filter: {:?}",
78						invalid_directive,
79					);
80				},
81			}
82		}
83	}
84
85	// Set the max logging level for the `log` macros.
86	let max_level_hint =
87		tracing_subscriber::Layer::<tracing_subscriber::FmtSubscriber>::max_level_hint(&env_filter);
88	log::set_max_level(super::to_log_level_filter(max_level_hint));
89
90	log::debug!(target: "tracing", "Reloading log filter with: {}", env_filter);
91	FILTER_RELOAD_HANDLE
92		.get()
93		.ok_or("No reload handle present")?
94		.reload(env_filter)
95		.map_err(|e| format!("{}", e))
96}
97
98/// Resets the log filter back to the original state when the node was started.
99///
100/// Includes substrate defaults and CLI supplied directives.
101pub fn reset_log_filter() -> Result<(), String> {
102	let directive = DEFAULT_DIRECTIVES.get_or_init(|| Mutex::new(Vec::new())).lock().clone();
103
104	*CURRENT_DIRECTIVES.get_or_init(|| Mutex::new(Vec::new())).lock() = directive;
105	reload_filter()
106}
107
108/// Initialize FILTER_RELOAD_HANDLE, only possible once
109pub(crate) fn set_reload_handle(handle: Handle<EnvFilter, SCSubscriber>) {
110	let _ = FILTER_RELOAD_HANDLE.set(handle);
111}
112
113// The layered Subscriber as built up in `LoggerBuilder::init()`.
114// Used in the reload `Handle`.
115type SCSubscriber<
116	N = tracing_fmt::format::DefaultFields,
117	E = crate::logging::EventFormat,
118	W = crate::logging::DefaultLogger,
119> = layer::Layered<tracing_fmt::Layer<Registry, N, E, W>, Registry>;