java_bindgen/
logger.rs

1use crate::{interop::*, prelude::JavaCatch, JResult};
2
3#[derive(Default)]
4pub struct JLoggerCore<'a> {
5    logger_obj: jni::objects::JObject<'a>,
6}
7
8impl<'a> JLoggerCore<'a> {
9    pub fn new(env: &mut jni::JNIEnv<'a>, lib_class_path: &str) -> JResult<Self> {
10        let class = env.find_class(lib_class_path).j_catch(env)?;
11        let logger = env
12            .get_static_field(&class, "logger", "Lorg/slf4j/Logger;")
13            .j_catch(env)?;
14        let logger_obj = logger.l().j_catch(env)?;
15
16        Ok(JLoggerCore { logger_obj })
17    }
18
19    fn _log<T: Into<String>>(&self, msg: T, level: &str, env: &mut jni::JNIEnv<'a>) {
20        let has_exception = env.exception_check().unwrap_or_default();
21
22        if let Ok(msg) = msg.into().into_j_value(env) {
23            env.call_method(
24                &self.logger_obj,
25                level,
26                "(Ljava/lang/String;)V",
27                &[msg.borrow()],
28            )
29            .j_catch(env)
30            .ok();
31        }
32
33        if !has_exception {
34            env.exception_clear().ok();
35        }
36    }
37
38    pub fn info<T: Into<String>>(&self, msg: T, env: &mut jni::JNIEnv<'a>) {
39        self._log(msg, "info", env);
40    }
41
42    pub fn warn<T: Into<String>>(&self, msg: T, env: &mut jni::JNIEnv<'a>) {
43        self._log(msg, "warn", env);
44    }
45
46    pub fn error<T: Into<String>>(&self, msg: T, env: &mut jni::JNIEnv<'a>) {
47        self._log(msg, "error", env);
48    }
49
50    pub fn debug<T: Into<String>>(&self, msg: T, env: &mut jni::JNIEnv<'a>) {
51        self._log(msg, "debug", env);
52    }
53
54    pub fn trace<T: Into<String>>(&self, msg: T, env: &mut jni::JNIEnv<'a>) {
55        self._log(msg, "trace", env);
56    }
57}