Skip to content

Commit

Permalink
propagate logging setup errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Keksoj committed May 3, 2024
1 parent 0915dcf commit a0c6b80
Show file tree
Hide file tree
Showing 14 changed files with 55 additions and 28 deletions.
6 changes: 4 additions & 2 deletions bin/src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use mio::net::UnixListener;

use sozu_command_lib::{
config::{Config, ConfigError},
logging::setup_logging_with_config,
logging::{setup_logging_with_config, LogError},
};

use crate::{
Expand Down Expand Up @@ -52,14 +52,16 @@ pub enum StartError {
SetPermissions(IoError),
#[error("could not launch new worker: {0}")]
LaunchWorker(ServerError),
#[error("could not setup the logger: {0}")]
SetupLogging(LogError),
}

pub fn begin_main_process(args: &Args) -> Result<(), StartError> {
let config_file_path = get_config_file_path(args).map_err(StartError::GetConfigPath)?;

let config = Config::load_from_path(config_file_path).map_err(StartError::LoadConfig)?;

setup_logging_with_config(&config, "MAIN");
setup_logging_with_config(&config, "MAIN").map_err(StartError::SetupLogging)?;
info!("Starting up");
setup_metrics(&config).map_err(StartError::SetupMetrics)?;
write_pid_file(&config).map_err(StartError::WritePidFile)?;
Expand Down
6 changes: 5 additions & 1 deletion bin/src/ctl/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,11 @@ impl CommandManager {
let config = self.config.clone();

upgrade_jobs.push(std::thread::spawn(move || {
setup_logging_with_config(&config, &format!("UPGRADE-WRK-{}", worker.id));
if let Err(e) =
setup_logging_with_config(&config, &format!("UPGRADE-WRK-{}", worker.id))
{
error!("Could not setup logging: {}", e);
}

info!("creating channel to upgrade worker {}", worker.id);
let channel = match create_channel(&config) {
Expand Down
6 changes: 4 additions & 2 deletions bin/src/ctl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use sozu_command_lib::{
certificate::CertificateError,
channel::{Channel, ChannelError},
config::{Config, ConfigError},
logging::setup_logging_with_config,
logging::{setup_logging_with_config, LogError},
proto::{
command::{Request, Response},
DisplayError,
Expand Down Expand Up @@ -53,6 +53,8 @@ pub enum CtlError {
NeedClusterDomain,
#[error("wrong response from Sōzu: {0:?}")]
WrongResponse(Response),
#[error("could not setup the logger: {0}")]
SetupLogging(LogError),
}

pub struct CommandManager {
Expand All @@ -70,7 +72,7 @@ pub fn ctl(args: cli::Args) -> Result<(), CtlError> {

// prevent logging for json responses for a clean output
if !args.json {
setup_logging_with_config(&config, "CTL");
setup_logging_with_config(&config, "CTL").map_err(CtlError::SetupLogging)?;
}

// If the command is `config check` then exit because if we are here, the configuration is valid
Expand Down
6 changes: 4 additions & 2 deletions bin/src/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use tempfile::tempfile;

use sozu_command_lib::{
channel::{Channel, ChannelError},
logging::setup_logging_with_config,
logging::{setup_logging_with_config, LogError},
};

use crate::{
Expand Down Expand Up @@ -69,6 +69,8 @@ pub enum UpgradeError {
CreateHub(HubError),
#[error("could not enable cloexec after upgrade: {0}")]
EnableCloexec(ServerError),
#[error("could not setup the logger: {0}")]
SetupLogging(LogError),
}

/// unix-forks the main process
Expand Down Expand Up @@ -180,7 +182,7 @@ pub fn begin_new_main_process(

println!("Setting up logging");

setup_logging_with_config(&config, "MAIN");
setup_logging_with_config(&config, "MAIN").map_err(UpgradeError::SetupLogging)?;
util::setup_metrics(&config).map_err(UpgradeError::SetupMetrics)?;

let mut command_hub =
Expand Down
7 changes: 5 additions & 2 deletions bin/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use tempfile::tempfile;
use sozu_command_lib::{
channel::{Channel, ChannelError},
config::Config,
logging::{setup_logging, AccessLogFormat},
logging::{setup_logging, AccessLogFormat, LogError},
proto::command::{ServerConfig, WorkerRequest, WorkerResponse},
ready::Ready,
request::{read_initial_state_from_file, RequestError},
Expand Down Expand Up @@ -74,6 +74,8 @@ pub enum WorkerError {
state: String,
channel_err: ChannelError,
},
#[error("could not setup the logger: {0}")]
SetupLogging(LogError),
}

/// called within a worker process, this starts the actual proxy
Expand Down Expand Up @@ -117,7 +119,8 @@ pub fn begin_worker_process(
Some(worker_config.log_colored),
&worker_config.log_level,
&worker_id,
);
)
.map_err(WorkerError::SetupLogging)?;

trace!(
"Creating worker {} with config: {:#?}",
Expand Down
4 changes: 3 additions & 1 deletion command/examples/bench_logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ fn main() {
eprintln!(
"n={n}, pre_generate={pre_generate}, target={target}, colored={colored}, filter={filter}"
);
setup_logging(&target, colored, None, None, None, &filter, "WRK-01");
if let Err(e) = setup_logging(&target, colored, None, None, None, &filter, "WRK-01") {
println!("could not setup logging: {}", e);
}

let mut pre_generated_log_iterator;
let mut log_iterator = std::iter::repeat(())
Expand Down
1 change: 1 addition & 0 deletions command/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ pub const MAX_LOOP_ITERATIONS: usize = 100000;
/// with little influence on performance. Defaults to 4.
pub const DEFAULT_SEND_TLS_13_TICKETS: u64 = 4;

/// for both logs and access logs
pub const DEFAULT_LOG_TARGET: &str = "stdout";

#[derive(Debug)]
Expand Down
23 changes: 13 additions & 10 deletions command/src/logging/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{
fmt::Arguments,
fs::{File, OpenOptions},
io::{stdout, Error as IoError, ErrorKind as IoErrorKind, Stdout, Write},
net::{SocketAddr, TcpStream, ToSocketAddrs, UdpSocket},
net::{SocketAddr, TcpStream, UdpSocket},
ops::{Deref, DerefMut},
path::Path,
str::FromStr,
Expand Down Expand Up @@ -131,14 +131,12 @@ impl Logger {
access_logs_target: Option<&str>,
access_format: Option<AccessLogFormat>,
access_colored: Option<bool>,
) {
) -> Result<(), LogError> {
println!("setting log target to {log_target}");
let backend = target_or_default(log_target);

println!("setting target of access logs to {access_logs_target:?}");
let access_backend = access_logs_target.map(|target| {
target_to_backend(target).expect("could not setup logger for access logs")
});
let access_backend = access_logs_target.map(target_to_backend).transpose()?;

let (directives, _errors) = parse_logging_spec(spec);
LOGGER.with(|logger| {
Expand Down Expand Up @@ -170,6 +168,7 @@ impl Logger {
log::set_max_level(log::LevelFilter::Info);
}
});
Ok(())
}

pub fn set_directives(&mut self, directives: Vec<LogDirective>) {
Expand Down Expand Up @@ -616,12 +615,16 @@ pub fn parse_logging_spec(spec: &str) -> (Vec<LogDirective>, Vec<LogSpecParseErr
}

/// start the logger with all logs and access logs on stdout
pub fn setup_default_logging(log_colored: bool, log_level: &str, tag: &str) {
pub fn setup_default_logging(
log_colored: bool,
log_level: &str,
tag: &str,
) -> Result<(), LogError> {
setup_logging("stdout", log_colored, None, None, None, log_level, tag)
}

/// start the logger from config (takes RUST_LOG into account)
pub fn setup_logging_with_config(config: &Config, tag: &str) {
pub fn setup_logging_with_config(config: &Config, tag: &str) -> Result<(), LogError> {
setup_logging(
&config.log_target,
config.log_colored,
Expand All @@ -645,7 +648,7 @@ pub fn setup_logging(
access_logs_colored: Option<bool>,
log_level: &str,
tag: &str,
) {
) -> Result<(), LogError> {
let log_level = env::var("RUST_LOG").unwrap_or(log_level.to_string());

Logger::init(
Expand All @@ -656,13 +659,13 @@ pub fn setup_logging(
access_logs_target,
access_logs_format,
access_logs_colored,
);
)
}

/// defaults to stdout if the log target is unparseable
fn target_or_default(target: &str) -> LoggerBackend {
match target_to_backend(target) {
Ok(backend) => return backend,
Ok(backend) => backend,
Err(target_error) => {
eprintln!("{target_error}, defaulting to stdout");
LoggerBackend::Stdout(stdout())
Expand Down
4 changes: 3 additions & 1 deletion e2e/src/sozu/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,9 @@ impl Worker {
println!("Setting up logging");

let server_job = thread::spawn(move || {
setup_default_logging(false, "error", &thread_name);
if let Err(e) = setup_default_logging(false, "error", &thread_name) {
println!("could not setup logging: {e}");
}
let mut server = Server::try_new_from_config(
cmd_worker_to_main,
thread_scm_worker_to_main,
Expand Down
8 changes: 6 additions & 2 deletions e2e/src/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,9 @@ pub fn try_hard_or_soft_stop(soft: bool) -> State {
}

fn try_http_behaviors() -> State {
setup_default_logging(false, "debug", "BEHAVE-OUT");
if let Err(e) = setup_default_logging(false, "debug", "BEHAVE-OUT") {
println!("could not setup default logging: {e}");
}

info!("starting up");

Expand Down Expand Up @@ -1121,7 +1123,9 @@ pub fn try_blue_geen() -> State {
}

pub fn try_keep_alive() -> State {
setup_default_logging(false, "debug", "KA-OUT");
if let Err(e) = setup_default_logging(false, "debug", "KA-OUT") {
println!("could not setup default logging: {e}");
}

let front_address = create_local_address();

Expand Down
2 changes: 1 addition & 1 deletion lib/examples/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use sozu_command_lib::{
};

fn main() -> anyhow::Result<()> {
setup_default_logging(true, "info", "EXAMPLE");
setup_default_logging(true, "info", "EXAMPLE").with_context(|| "could not setup logging")?;

info!("starting up");

Expand Down
2 changes: 1 addition & 1 deletion lib/examples/https.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use sozu_command_lib::{
};

fn main() -> anyhow::Result<()> {
setup_default_logging(true, "info", "EXAMPLE");
setup_default_logging(true, "info", "EXAMPLE").with_context(|| "could not setup logging")?;

info!("MAIN\tstarting up");

Expand Down
6 changes: 4 additions & 2 deletions lib/examples/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use sozu_command_lib::{
};

fn main() -> anyhow::Result<()> {
setup_default_logging(true, "info", "EXAMPLE");
setup_default_logging(true, "info", "EXAMPLE").with_context(|| "could not setup logging")?;

info!("starting up");

Expand All @@ -30,7 +30,9 @@ fn main() -> anyhow::Result<()> {
address: SocketAddress::new_v4(127, 0, 0, 1, 8080),
..Default::default()
};
setup_default_logging(true, "debug", "TCP");
if let Err(e) = setup_default_logging(true, "debug", "TCP") {
println!("could not setup logging: {e}");
}
sozu_lib::tcp::testing::start_tcp_worker(listener, max_buffers, buffer_size, channel);
});

Expand Down
2 changes: 1 addition & 1 deletion lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@
//! };
//!
//! fn main() -> anyhow::Result<()> {
//! setup_default_logging(true, "info", "EXAMPLE");
//! setup_default_logging(true, "info", "EXAMPLE").with_context(|| "could not setup logging")?;
//!
//! info!("starting up");
//!
Expand Down

0 comments on commit a0c6b80

Please sign in to comment.