use std::{ffi::CString}; use libc::{c_void, c_int, c_char}; extern "C" { pub fn new_appender(name: *const c_char, attributes: *const c_char) -> c_int; pub fn delete_appender(app_id: c_int) -> c_void; pub fn write(app_id: c_int, level: c_int, log: *const c_char) -> c_void; } /// 日志添加器 /// #[derive(Debug)] pub struct Appender { app_id: c_int, // 日志添加器ID } impl Appender { pub fn new(name : &str, attributes : &str) -> Option { unsafe { let name_ptr = CString::new(name).unwrap(); let attributes_ptr = CString::new(attributes).unwrap(); let appender = Appender { app_id: new_appender(name_ptr.as_ptr(), attributes_ptr.as_ptr()), }; return Some(appender); }; } pub fn verb(&mut self, log: &str) { self.write(1, log); } pub fn info(&mut self, log: &str) { self.write(2, log); } pub fn debug(&mut self, log: &str) { self.write(3, log); } pub fn warn(&mut self, log: &str) { self.write(4, log); } pub fn except(&mut self, log: &str) { self.write(5, log); } pub fn fail(&mut self, log: &str) { self.write(6, log); } pub fn fatal(&mut self, log: &str) { self.write(7, log); } fn write(&mut self, level : i32, log : &str) { unsafe { let log_ptr = CString::new(log).unwrap(); write(self.app_id, level, log_ptr.as_ptr()); } } } impl Drop for Appender { fn drop(&mut self) { unsafe { delete_appender(self.app_id); } } } #[cfg(test)] mod tests { use super::Appender; #[test] fn test_new_appender1() { let mut app = Appender::new("test", "console://;line=[%y%m%d-%H:%M:%S.%U];flush=true").unwrap(); app.verb("verb log"); app.info("info log"); app.debug("debug log"); app.warn("warn log"); app.except("except log"); app.fail("fail log"); app.fatal("fatal log"); } }