Skip to content

Commit

Permalink
Implement logging to file
Browse files Browse the repository at this point in the history
  • Loading branch information
c-git committed Nov 17, 2023
1 parent 446b723 commit 67f46bb
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
/config.json
events/
/*.data
/log
64 changes: 64 additions & 0 deletions src/logging.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copied and edited based on https://github.com/estk/log4rs/pull/295

use anyhow::Context;
use log::LevelFilter;
use log4rs::Handle;
use log4rs::{
append::{
console::{ConsoleAppender, Target},
rolling_file::policy::compound::{
roll::fixed_window::FixedWindowRoller, trigger::size::SizeTrigger, CompoundPolicy,
},
},
config::{Appender, Config, Root},
encode::pattern::PatternEncoder,
filter::threshold::ThresholdFilter,
};

pub fn init_logging(level: LevelFilter) -> anyhow::Result<Handle> {
let file_path = "log/file.log";
let archive_pattern = "log/file_{}.log";
// Pattern: https://docs.rs/log4rs/*/log4rs/append/rolling_file/policy/compound/roll/fixed_window/struct.FixedWindowRollerBuilder.html#method.build

// Build a stderr logger.
let stderr = ConsoleAppender::builder().target(Target::Stderr).build();

// Create a policy to use with the file logging
let trigger = SizeTrigger::new(4096); // 4kb (4 * 1024)
let roller = FixedWindowRoller::builder()
.build(archive_pattern, 10) // Roll based on pattern and max 10 archive files
.expect("Failed to create FixedWindowRoller");
let policy = CompoundPolicy::new(Box::new(trigger), Box::new(roller));

// Logging to log file. (with rolling)
let log_file = log4rs::append::rolling_file::RollingFileAppender::builder()
// Pattern: https://docs.rs/log4rs/*/log4rs/encode/pattern/index.html
.encoder(Box::new(PatternEncoder::new(
"{d(%Y-%m-%d %H:%M:%S)} {l} - {m}\n",
)))
.build(file_path, Box::new(policy))
.unwrap();

let config = Config::builder()
.appender(Appender::builder().build("log_file", Box::new(log_file)))
.appender(
Appender::builder()
.filter(Box::new(ThresholdFilter::new(level)))
.build("stderr", Box::new(stderr)),
)
.build(
Root::builder()
.appender("log_file")
.appender("stderr")
.build(level),
)
.context("Failed to configure logging")?;

// Use this to change log levels at runtime.
// This means you can change the default log level to trace
// if you are trying to debug an issue and need more logs on then turn it off
// once you are done.
let handle = log4rs::init_config(config).context("Failed to init_config")?;

Ok(handle)
}

0 comments on commit 67f46bb

Please sign in to comment.