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
// Copyright 2023 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
mod appender;
mod error;
mod layers;
#[cfg(feature = "process-metrics")]
pub mod metrics;
use crate::error::{Error, Result};
use layers::TracingLayers;
use std::path::PathBuf;
use tracing::info;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_core::{dispatcher::DefaultGuard, Level};
use tracing_subscriber::{prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt};
#[derive(Debug, Clone)]
pub enum LogOutputDest {
Stdout,
Path(PathBuf),
}
impl std::fmt::Display for LogOutputDest {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
LogOutputDest::Stdout => write!(f, "stdout"),
LogOutputDest::Path(p) => write!(f, "{}", p.to_string_lossy()),
}
}
}
#[derive(Debug, Clone)]
pub enum LogFormat {
Default,
Json,
}
impl LogFormat {
pub fn parse_from_str(val: &str) -> Result<Self> {
match val {
"default" => Ok(LogFormat::Default),
"json" => Ok(LogFormat::Json),
_ => Err(Error::LoggingConfigurationError(
"The only valid values for this argument are \"default\" or \"json\"".to_string(),
)),
}
}
}
pub struct LogBuilder {
default_logging_targets: Vec<(String, Level)>,
output_dest: LogOutputDest,
format: LogFormat,
max_uncompressed_log_files: Option<usize>,
max_compressed_log_files: Option<usize>,
}
impl LogBuilder {
/// Create a new builder
/// Provide the default_logging_targets that are used if the `SN_LOG` env variable is not set.
///
/// By default, we use log to the StdOut with the default format.
pub fn new(default_logging_targets: Vec<(String, Level)>) -> Self {
Self {
default_logging_targets,
output_dest: LogOutputDest::Stdout,
format: LogFormat::Default,
max_uncompressed_log_files: None,
max_compressed_log_files: None,
}
}
/// Set the logging output destination
pub fn output_dest(&mut self, output_dest: LogOutputDest) {
self.output_dest = output_dest;
}
/// Set the logging format
pub fn format(&mut self, format: LogFormat) {
self.format = format
}
/// The max number of uncompressed log files to store
pub fn max_uncompressed_log_files(&mut self, files: usize) {
self.max_uncompressed_log_files = Some(files);
}
/// The max number of compressed files to store
pub fn max_compressed_log_files(&mut self, files: usize) {
self.max_compressed_log_files = Some(files);
}
/// Inits node logging, returning the NonBlocking guard if present.
/// This guard should be held for the life of the program.
///
/// Logging should be instantiated only once.
pub fn initialize(self) -> Result<Option<WorkerGuard>> {
let mut layers = TracingLayers::default();
#[cfg(not(feature = "otlp"))]
layers.fmt_layer(
self.default_logging_targets,
self.output_dest,
self.format,
self.max_uncompressed_log_files,
self.max_compressed_log_files,
)?;
#[cfg(feature = "otlp")]
{
layers.fmt_layer(
self.default_logging_targets.clone(),
self.output_dest,
self.format,
self.max_uncompressed_log_files,
self.max_compressed_log_files,
)?;
match std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT") {
Ok(_) => layers.otlp_layer(self.default_logging_targets)?,
Err(_) => println!(
"The OTLP feature is enabled but the OTEL_EXPORTER_OTLP_ENDPOINT variable is not \
set, so traces will not be submitted."
),
}
}
if tracing_subscriber::registry()
.with(layers.layers)
.try_init()
.is_err()
{
println!("Tried to initialize and set global default subscriber more than once");
}
Ok(layers.guard)
}
/// Logs to the data_dir. Should be called from a single threaded tokio/non-tokio context.
/// Provide the test file name to capture tracings from the test.
///
/// subscriber.set_default() should be used if under a single threaded tokio / single threaded non-tokio context.
/// Refer here for more details: <https://github.com/tokio-rs/tracing/discussions/1626>
pub fn init_single_threaded_tokio_test(
test_file_name: &str,
) -> (Option<WorkerGuard>, DefaultGuard) {
let layers = Self::get_test_layers(test_file_name);
let log_guard = tracing_subscriber::registry()
.with(layers.layers)
.set_default();
// this is the test_name and not the test_file_name
if let Some(test_name) = std::thread::current().name() {
info!("Running test: {test_name}");
}
(layers.guard, log_guard)
}
/// Logs to the data_dir. Should be called from a multi threaded tokio context.
/// Provide the test file name to capture tracings from the test.
///
/// subscriber.init() should be used under multi threaded tokio context. If you have 1+ multithreaded tokio tests under
/// the same integration test, this might result in loss of logs. Hence use .init() (instead of .try_init()) to panic
/// if called more than once.
pub fn init_multi_threaded_tokio_test(test_file_name: &str) -> Option<WorkerGuard> {
let layers = Self::get_test_layers(test_file_name);
tracing_subscriber::registry()
.with(layers.layers)
.try_init()
.expect("You have tried to init multi_threaded tokio logging twice\nRefer sn_logging::get_test_layers docs for more.");
layers.guard
}
/// Initialize just the fmt_layer for testing purposes.
///
/// Also overwrites the SN_LOG variable to log everything including the test_file_name
fn get_test_layers(test_file_name: &str) -> TracingLayers {
// overwrite SN_LOG
std::env::set_var("SN_LOG", format!("{test_file_name}=TRACE,all"));
let output_dest = match dirs_next::data_dir() {
Some(dir) => {
// Get the current timestamp and format it to be human readable
let timestamp = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S").to_string();
let path = dir
.join("safe")
.join("client")
.join("logs")
.join(format!("log_{}", timestamp));
LogOutputDest::Path(path)
}
None => LogOutputDest::Stdout,
};
let mut layers = TracingLayers::default();
layers
.fmt_layer(vec![], output_dest, LogFormat::Default, None, None)
.expect("Failed to get TracingLayers");
layers
}
}