add logging to the functions

This commit is contained in:
jb-alvarado 2022-02-24 17:28:51 +01:00
parent 9a78018e15
commit e8d828f60d
10 changed files with 161 additions and 90 deletions

View File

@ -20,15 +20,17 @@ mail:
mail_level: "ERROR"
logging:
helptext: Logging to file, if 'log_to_file' False log to console. 'backup_count'
says how long log files will be saved in days. Path to /var/log/ only if you
run this program as daemon. 'log_level' can be DEBUG, INFO, WARNING,
ERROR. 'ffmpeg_level' can be INFO, WARNING, ERROR.
log_to_file: true
helptext: Logging to file, if 'log_to_file' false log to console. 'backup_count'
says how long log files will be saved in days. 'local_time' to false will set
log timestamps to UTC. Path to /var/log/ only if you run this program as daemon.
'log_level' can be DEBUG, INFO, WARNING, ERROR. 'ffmpeg_level' can be info,
warning, error.
log_to_file: false
backup_count: 7
local_time: true
log_path: "/var/log/ffplayout/"
log_level: "DEBUG"
ffmpeg_level: "ERROR"
ffmpeg_level: "error"
processing:
helptext: Set playing mode, like playlist; folder, or you own custom one.

View File

@ -3,18 +3,9 @@ extern crate simplelog;
use simplelog::*;
use file_rotate::{FileRotate, ContentLimit, suffix::AppendCount, compression::Compression};
use file_rotate::{compression::Compression, suffix::AppendCount, ContentLimit, FileRotate};
fn main() {
//TermLogger::init(LevelFilter::Debug, Config::default(), TerminalMode::Mixed, ColorChoice::Auto).unwrap();
//SimpleLogger::init(LevelFilter::Debug, Config::default()).unwrap();
// CombinedLogger::init(
// vec![
// TermLogger::new(LevelFilter::Debug, Config::default(), TerminalMode::Mixed, ColorChoice::Auto),
// WriteLogger::new(LevelFilter::Debug, Config::default(), File::create("my_rust_binary.log").unwrap()),
// ]
// ).unwrap();
let log = || {
FileRotate::new(
"logs/ffplayout.log",
@ -24,9 +15,41 @@ fn main() {
)
};
WriteLogger::init(LevelFilter::Debug, Config::default(), log()).unwrap();
let def_config = simplelog::ConfigBuilder::new()
.set_target_level(LevelFilter::Off)
.set_thread_level(LevelFilter::Off)
.set_level_padding(LevelPadding::Left)
.set_time_to_local(true).clone();
for idx in 1..1500 {
let term_config = def_config.clone()
.set_level_color(Level::Debug, Some(Color::Ansi256(12)))
.set_level_color(Level::Info, Some(Color::Ansi256(10)))
.set_level_color(Level::Warn, Some(Color::Ansi256(208)))
.set_level_color(Level::Error, Some(Color::Ansi256(9)))
.set_time_format_str("\x1b[30;1m[%Y-%m-%d %H:%M:%S%.3f]\x1b[0m")
.build();
let file_config = def_config.clone()
.set_time_format_str("[%Y-%m-%d %H:%M:%S%.3f]")
.build();
CombinedLogger::init(vec![
TermLogger::new(
LevelFilter::Debug,
term_config,
TerminalMode::Stderr,
ColorChoice::Auto,
),
WriteLogger::new(LevelFilter::Debug, file_config, log()),
])
.unwrap();
debug!("this is a <b>debug</> message");
info!("this is a info message");
warn!("this is a warning message");
error!("this is a error message");
for idx in 1..10 {
info!("{idx}");
}
}

View File

@ -9,10 +9,10 @@ fn main() {
let config = get_config();
let msg = Messenger::new(&config);
msg.debug("this is a debug");
msg.info("this is a info");
msg.warning("this is a warning");
msg.error("this is a error");
// msg.debug("this is a debug");
// msg.info("this is a info");
// msg.warning("this is a warning");
// msg.error("this is a error");
// println!("{:#?}", config);
// folder::walk(&config.storage.path, config.storage.shuffle, &config.storage.extensions);
@ -29,5 +29,5 @@ fn main() {
// println!("{:#?}", utils::get_sec());
// println!("{:#?}", utils::get_timestamp());
desktop::play(config).expect("Play on desktop failed!");
desktop::play(msg, config).expect("Play on desktop failed!");
}

View File

@ -4,16 +4,17 @@ use std::{
process::{Command, Stdio},
};
use crate::utils::{program, sec_to_time, Config};
use crate::utils::{sec_to_time, Config, CurrentProgram, Messenger};
pub fn play(config: Config) -> io::Result<()> {
let get_source = program(config.clone());
pub fn play(msg: Messenger, config: Config) -> io::Result<()> {
let get_source = CurrentProgram::new(&msg, config.clone());
let dec_settings = config.processing.settings.unwrap();
let ff_log_format = format!("level+{}", config.logging.ffmpeg_level);
let mut enc_cmd = vec![
"-hide_banner",
"-nostats",
"-v",
"level+error",
ff_log_format.as_str(),
"-i",
"pipe:0",
];
@ -32,7 +33,7 @@ pub fn play(config: Config) -> io::Result<()> {
enc_cmd.append(&mut enc_filter.iter().map(String::as_str).collect());
println!("Encoder CMD: '{:?}'", enc_cmd);
msg.debug(format!("Encoder CMD: <bright-blue>{:?}</>", enc_cmd));
let mut enc_proc = Command::new("ffplay")
.args(enc_cmd)
@ -46,13 +47,18 @@ pub fn play(config: Config) -> io::Result<()> {
if let Some(mut enc_input) = enc_proc.stdin.take() {
for node in get_source {
println!("Node begin: {:?}", sec_to_time(node.begin.unwrap()));
println!("Play: {:#?}", node.source);
// println!("Node begin: {:?}", sec_to_time(node.begin.unwrap()));
msg.info(format!("Play: <b><magenta>{}</></b>", node.source));
let cmd = node.cmd.unwrap();
let filter = node.filter.unwrap();
let mut dec_cmd = vec!["-v", "level+error", "-hide_banner", "-nostats"];
let mut dec_cmd = vec![
"-v",
ff_log_format.as_str(),
"-hide_banner",
"-nostats",
];
dec_cmd.append(&mut cmd.iter().map(String::as_str).collect());
@ -61,7 +67,7 @@ pub fn play(config: Config) -> io::Result<()> {
}
dec_cmd.append(&mut dec_settings.iter().map(String::as_str).collect());
println!("Decoder CMD: '{:?}'", dec_cmd);
msg.debug(format!("Decoder CMD: <bright-blue>{:?}</>", dec_cmd));
let mut dec_proc = Command::new("ffmpeg")
.args(dec_cmd)
@ -77,20 +83,20 @@ pub fn play(config: Config) -> io::Result<()> {
let dec_output = dec_proc.wait_with_output()?;
if dec_output.stderr.len() > 0 {
println!(
"[Encoder] {}",
msg.error(format!(
"[Encoder] <red>{:?}</red>",
String::from_utf8(dec_output.stderr).unwrap()
);
));
}
}
}
enc_proc.wait()?;
let enc_output = enc_proc.wait_with_output()?;
println!(
msg.debug(format!(
"[Encoder] {}",
String::from_utf8(enc_output.stderr).unwrap()
);
));
}
Ok(())

View File

@ -8,6 +8,9 @@ pub struct Args {
#[clap(short, long, help = "file path to ffplayout.conf")]
pub config: Option<String>,
#[clap(short, long, help = "file path for logging")]
pub log: Option<String>,
#[clap(long, help = "playing mode: folder, playlist, custom...")]
pub play_mode: Option<String>,

View File

@ -3,7 +3,7 @@ use serde_yaml::{self};
use std::{fs::File, path::Path, process};
// use regex::Regex;
use crate::utils::get_args;
use crate::utils::{get_args, Messenger};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Config {
@ -38,6 +38,7 @@ pub struct Mail {
pub struct Logging {
pub log_to_file: bool,
pub backup_count: u32,
pub local_time: bool,
pub log_path: String,
pub log_level: String,
pub ffmpeg_level: String,
@ -115,18 +116,18 @@ pub fn get_config() -> Config {
config_path = "/etc/ffplayout/ffplayout.yml".to_string();
}
if !Path::new(&config_path).is_file() {
println!(
"{} '{config_path}'\n{}\nYou found it in 'assets' folders...",
"ffplayout config doesn't exists:",
"Put 'ffplayout.yml' in '/etc/playout/' or beside the executable!"
);
process::exit(0x0100);
}
let f = match File::open(&config_path) {
Ok(file) => file,
Err(err) => {
println!(
"'{config_path}' doesn't exists!\n{}\n\nSystem error: {err}",
"Put 'ffplayout.yml' in '/etc/playout/' or beside the executable!"
);
process::exit(0x0100);
}
};
let f = File::open(config_path).expect("Could not open config file.");
let mut config: Config = serde_yaml::from_reader(f).expect("Could not read config file.");
let fps = config.processing.fps.to_string();
let bitrate = config.processing.width * config.processing.height / 10;
@ -158,10 +159,17 @@ pub fn get_config() -> Config {
"-f",
"mpegts",
"-",
].iter().map(|&s|s.into()).collect();
]
.iter()
.map(|&s| s.into())
.collect();
config.processing.settings = Some(settings);
if args.log.is_some() {
config.logging.log_path = args.log.unwrap();
}
if args.playlist.is_some() {
config.playlist.path = args.playlist.unwrap();
}
@ -194,5 +202,5 @@ pub fn get_config() -> Config {
config.processing.volume = args.volume.unwrap();
}
config
return config;
}

View File

@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use std::{fs::File, path::Path};
use crate::utils::{get_date, get_sec, modified_time, time_to_sec, Config, MediaProbe};
use crate::utils::{get_date, get_sec, modified_time, time_to_sec, Config, MediaProbe, Messenger};
#[derive(Debug, Serialize, Deserialize)]
pub struct Playlist {
@ -29,7 +29,7 @@ pub struct Program {
pub next_ad: Option<bool>,
}
pub fn read_json(config: &Config, seek: bool) -> Playlist {
pub fn read_json(msg: &Messenger, config: &Config, seek: bool) -> Playlist {
let mut playlist_path = Path::new(&config.playlist.path).to_owned();
let start = &config.playlist.day_start;
let length = &config.playlist.length;
@ -53,7 +53,7 @@ pub fn read_json(config: &Config, seek: bool) -> Playlist {
length_sec = time_to_sec(length);
}
println!("Read Playlist: {}", &current_file);
msg.info(format!("Read Playlist: <b><magenta>{}</></b>", &current_file));
let modify = modified_time(current_file.clone());
let f = File::open(&current_file).expect("Could not open json playlist file.");
@ -112,7 +112,5 @@ pub fn read_json(config: &Config, seek: bool) -> Playlist {
item.cmd = Some(source_cmd);
}
// println!("{:#?}", playlist);
playlist
}

View File

@ -1,16 +1,18 @@
extern crate log;
extern crate simplelog;
use std::path::Path;
use file_rotate::{compression::Compression, suffix::AppendCount, ContentLimit, FileRotate};
use simplelog::*;
use std::fs::File;
use crate::utils::Config;
#[derive(Debug, Clone)]
pub struct Messenger {
message: String,
log_to_file: bool,
backup_count: u32,
path: String,
level: String,
ffmpeg_level: String,
}
@ -18,22 +20,54 @@ pub struct Messenger {
impl Messenger {
pub fn new(config: &Config) -> Self {
let conf = config.logging.clone();
let logger_config = simplelog::ConfigBuilder::new()
.set_level_color(Level::Info, Some(Color::Green))
.build();
let log_config = simplelog::ConfigBuilder::new()
.set_thread_level(LevelFilter::Off)
.set_target_level(LevelFilter::Off)
.set_level_padding(LevelPadding::Left)
.set_time_to_local(conf.local_time)
.clone();
if conf.log_to_file {
WriteLogger::init(
LevelFilter::Debug,
simplelog::Config::default(),
File::create("ffplayout.log").unwrap(),
)
.unwrap();
let file_config = log_config
.clone()
.set_time_format("[%Y-%m-%d %H:%M:%S%.3f]".into())
.build();
let mut log_path = "logs/ffplayout.log".to_string();
if Path::new(&conf.log_path).is_dir() {
log_path = Path::new(&conf.log_path)
.join("ffplayout.log")
.display()
.to_string();
} else if Path::new(&conf.log_path).is_file() {
log_path = conf.log_path
} else {
println!("Logging path not exists!")
}
let log = || {
FileRotate::new(
log_path,
AppendCount::new(7),
ContentLimit::Lines(1000),
Compression::None,
)
};
WriteLogger::init(LevelFilter::Debug, file_config, log()).unwrap();
} else {
let term_config = log_config
.clone()
.set_level_color(Level::Debug, Some(Color::Ansi256(12)))
.set_level_color(Level::Info, Some(Color::Ansi256(10)))
.set_level_color(Level::Warn, Some(Color::Ansi256(208)))
.set_level_color(Level::Error, Some(Color::Ansi256(9)))
.set_time_format_str("\x1b[30;1m[%Y-%m-%d %H:%M:%S%.3f]\x1b[0m")
.build();
TermLogger::init(
LevelFilter::Debug,
logger_config,
term_config,
TerminalMode::Mixed,
ColorChoice::Auto,
)
@ -44,19 +78,18 @@ impl Messenger {
message: "".to_string(),
log_to_file: conf.log_to_file,
backup_count: conf.backup_count,
path: conf.log_path,
level: conf.log_level,
ffmpeg_level: conf.ffmpeg_level,
}
}
pub fn debug(&self, msg: &str) {
pub fn debug(&self, msg: String) {
if self.level.to_lowercase() == "debug".to_string() {
debug!("{}", msg)
}
}
pub fn info(&self, msg: &str) {
pub fn info(&self, msg: String) {
if self.level.to_lowercase() == "debug".to_string()
|| self.level.to_lowercase() == "info".to_string()
{
@ -64,7 +97,7 @@ impl Messenger {
}
}
pub fn warning(&self, msg: &str) {
pub fn warning(&self, msg: String) {
if self.level.to_lowercase() == "debug".to_string()
|| self.level.to_lowercase() == "info".to_string()
|| self.level.to_lowercase() == "warning".to_string()
@ -73,7 +106,7 @@ impl Messenger {
}
}
pub fn error(&self, msg: &str) {
pub fn error(&self, msg: String) {
if self.level.to_lowercase() == "debug".to_string()
|| self.level.to_lowercase() == "info".to_string()
|| self.level.to_lowercase() == "warning".to_string()

View File

@ -15,7 +15,7 @@ pub use config::{get_config, Config};
// pub use folder::walk;
pub use json_reader::{read_json, Program};
pub use messenger::Messenger;
pub use playlist::program;
pub use playlist::CurrentProgram;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MediaProbe {
@ -120,7 +120,7 @@ pub fn modified_time(path: String) -> Option<DateTime<Local>> {
pub fn time_to_sec(time_str: &String) -> f64 {
if ["now", "", "none"].contains(&time_str.as_str()) || !time_str.contains(":") {
return 0.0
return get_sec()
}
let t: Vec<&str> = time_str.split(':').collect();

View File

@ -3,12 +3,13 @@ use std::path::Path;
use crate::utils::{
check_sync, gen_dummy, get_delta,
json_reader::{read_json, Program},
modified_time, Config, MediaProbe,
modified_time, Config, MediaProbe, Messenger,
};
use crate::filter::filter_chains;
pub struct CurrentProgram {
msg: Messenger,
config: Config,
json_mod: String,
json_path: String,
@ -18,10 +19,11 @@ pub struct CurrentProgram {
}
impl CurrentProgram {
fn new(config: Config) -> Self {
let json = read_json(&config, true);
pub fn new(msg: &Messenger, config: Config) -> Self {
let json = read_json(&msg, &config, true);
Self {
msg: msg.clone(),
config: config,
json_mod: json.modified.unwrap(),
json_path: json.current_file.unwrap(),
@ -36,7 +38,7 @@ impl CurrentProgram {
if !mod_time.unwrap().to_string().eq(&self.json_mod) {
// when playlist has changed, reload it
let json = read_json(&self.config, false);
let json = read_json(&self.msg, &self.config, false);
self.json_mod = json.modified.unwrap();
self.nodes = json.program.into();
@ -66,8 +68,8 @@ impl Iterator for CurrentProgram {
last = true
}
println!("Last: {}", self.nodes[self.idx - 1].source);
println!("Next: {}", self.nodes[self.idx + 1].source);
self.msg.debug(format!("Last: {}", self.nodes[self.idx - 1].source));
self.msg.debug(format!("Next: {}", self.nodes[self.idx + 1].source));
self.idx += 1;
@ -78,7 +80,7 @@ impl Iterator for CurrentProgram {
if !self.init {
let delta = get_delta(&current.begin.unwrap(), &self.config);
println!("Delta: {delta}");
self.msg.debug(format!("Delta: {delta}"));
check_sync(delta, &self.config);
}
@ -86,7 +88,7 @@ impl Iterator for CurrentProgram {
self.append_probe(&mut current);
self.add_filter(&mut current, last, next);
} else {
println!("File not found: {}", current.source);
self.msg.error(format!("File not found: {}", current.source));
let dummy = gen_dummy(current.out - current.seek, &self.config);
current.source = dummy.0;
current.cmd = Some(dummy.1);
@ -103,7 +105,7 @@ impl Iterator for CurrentProgram {
last = true
}
let json = read_json(&self.config, false);
let json = read_json(&self.msg, &self.config, false);
self.json_mod = json.modified.unwrap();
self.json_path = json.current_file.unwrap();
self.nodes = json.program.into();
@ -117,7 +119,7 @@ impl Iterator for CurrentProgram {
if !self.init {
let delta = get_delta(&current.begin.unwrap(), &self.config);
println!("Delta: {delta}");
self.msg.debug(format!("Delta: {delta}"));
check_sync(delta, &self.config);
}
@ -125,7 +127,7 @@ impl Iterator for CurrentProgram {
self.append_probe(&mut current);
self.add_filter(&mut current, last, next);
} else {
println!("File not found: {}", current.source);
self.msg.error(format!("File not found: {}", current.source));
let dummy = gen_dummy(current.out - current.seek, &self.config);
current.source = dummy.0;
current.cmd = Some(dummy.1);
@ -136,7 +138,3 @@ impl Iterator for CurrentProgram {
}
}
}
pub fn program(config: Config) -> CurrentProgram {
CurrentProgram::new(config)
}