For a daemon like p910nd, it's important to be able to send these to the system log facility as the process will be detached from the standard 3 file descriptors in operation. But we still want to be able to send messages to stderr for debugging purposes.
In main.rs we import the log module which defines macros for various log levels. For example, just before the server starts we output an informative message, and if the server exits abnormally we output an error message.
The logger code is placed in logger.rs. It could have been part of lib.rs but we want to make a module out of it, for practice. Even if the code is textually in lib.rs, it can still be an inline module. This is logger.rs:
use log::LevelFilter; use syslog::{Formatter3164,BasicLogger}; pub fn log_init(debug: bool) -> () { if debug { stderrlog::new() .module(module_path!()) .verbosity(LevelFilter::Info) .init() .expect("Stderrlog not initialised"); } else { let logger = syslog::unix(Formatter3164::default()).unwrap(); log::set_boxed_logger(Box::new(BasicLogger::new(logger))) .map(|()| log::set_max_level(LevelFilter::Info)).unwrap_or(()) } }
We also need to import entities from the log crate, but also the syslog crate which deals with the system logger. If debug is true then we set the global logger to send to stderr, otherwise we instantiate a connection to the system logger. This function returns (), the unit object, so we cannot communicate errors, if it fails it returns to the main program but doesn't prevent it from starting a server. This is something we might want to improve on in future.
In lib.rs we have this line:
pub mod logger;
and as you see in main.rs, the public function log_init is invoked as logger::log_init(bool).
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.