Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Debug implementation for AndroidLogger to facilitate use with log4rs #79

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ edition = "2021"
[features]
default = ["regex"]
regex = ["env_filter/regex"]
log4rs = ["derivative"]

[dependencies]
derivative = { version = "2.2.0", optional = true }

[dependencies.log]
version = "0.4"
Expand All @@ -25,3 +29,6 @@ version = "0.3"
[dependencies.env_filter]
version = "0.1"
default-features = false

[dev-dependencies]
log4rs = "1.3.0"
6 changes: 6 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ use std::sync::OnceLock;

pub use env_filter::{Builder as FilterBuilder, Filter};

#[cfg(feature = "log4rs")]
use derivative::Derivative;

pub(crate) type FormatFn = Box<dyn Fn(&mut dyn fmt::Write, &Record) -> fmt::Result + Sync + Send>;

/// Possible identifiers of a specific buffer of Android logging system for
Expand Down Expand Up @@ -160,7 +163,10 @@ fn android_log(
fn android_log(_buf_id: Option<LogId>, _priority: Level, _tag: &CStr, _msg: &CStr) {}

/// Underlying android logger backend
#[cfg_attr(feature = "log4rs", derive(Derivative))]
Copy link
Collaborator

@Dushistov Dushistov Sep 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

derivative is not supported.
But even if supported, why use extract crate, when you can write just
5 lines of code?

impl std::fmt::Debug for AndroidLogger {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AndroidLogger").finish()
    }
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about unconditionally (i.e. remove feature = "log4rs" - that's irrelevant) implementing Debug on Config? It looks like all fields except the function can be formatted, so if we take some inspiration from the ndk crate you end up with a much simpler change.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed changes so this is no longer feature gated and is simpler. Thanks for the suggestions. I was trying to leave the default builds as they were, but that's probably overkill here.

#[cfg_attr(feature = "log4rs", derivative(Debug))]
pub struct AndroidLogger {
#[cfg_attr(feature = "log4rs", derivative(Debug = "ignore"))]
config: OnceLock<Config>,
}

Expand Down
52 changes: 52 additions & 0 deletions tests/log4rs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#![cfg(feature = "log4rs")]

use android_logger::AndroidLogger;
use log::{debug, error, info, trace, warn, LevelFilter};
use std::sync::OnceLock;

#[test]
fn test_log4rs() {
use android_logger::Config as AndroidConfig;
use log4rs::append::console::ConsoleAppender;
use log4rs::config::{Appender, Root};
use log4rs::encode::pattern::PatternEncoder;
use log4rs::Config;

static ANDROID_LOGGER: OnceLock<AndroidLogger> = OnceLock::new();
let android_logger = ANDROID_LOGGER.get_or_init(|| {
AndroidLogger::new(AndroidConfig::default().with_max_level(LevelFilter::Trace))
});
let stdout = ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new("{m}{n}")))
.build();
match Config::builder()
.appender(Appender::builder().build("stdout", Box::new(stdout)))
.appender(Appender::builder().build("android_logger", Box::new(android_logger)))
.build(
Root::builder()
.appender("stdout")
.appender("android_logger")
.build(LevelFilter::Debug),
) {
Ok(config) => {
let handle = log4rs::init_config(config);
if let Err(e) = handle {
println!("ERROR: failed to configure logging for stdout with {e:?}");
}
}
Err(e) => {
println!("ERROR: failed to prepare default logging configuration with {e:?}");
}
}
// This will not be logged to the Console because of its category's custom level filter.
info!(target: "Settings", "Info");

warn!(target: "Settings", "Warn");
error!(target: "Settings", "Error");

trace!("Trace");
debug!("Debug");
info!("Info");
warn!(target: "Database", "Warn");
error!("Error");
}
Loading