From eb1888b00c4bad1ae14736c87d68b2a39b436080 Mon Sep 17 00:00:00 2001 From: Thijs Cadier Date: Mon, 31 Aug 2015 22:58:05 +0200 Subject: [PATCH] Add log handling --- Cargo.toml | 1 + README.md | 6 ++++++ src/lib.rs | 39 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 6b3cb44..3bfd29a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ name = "tests" [dependencies] libc = "*" +log = "*" [dependencies.bson] git = "https://github.com/zonyitoo/bson-rs.git" diff --git a/README.md b/README.md index 2dd3cc9..ecef9d5 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,12 @@ set this environment var for building to work (see https://github.com/crabtw/rus export DYLD_LIBRARY_PATH=/Library/Developer/CommandLineTools/usr/lib ``` +## Logging + +All internal logging by mongoc is redirected to the macros in the [log +crate](http://doc.rust-lang.org/log/log/index.html). See the `log` docs +to configure output in your application. + ## Examples See the tests directory for examples of how to use the driver. diff --git a/src/lib.rs b/src/lib.rs index 65cbe47..0f26437 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ #![feature(convert)] +#![feature(cstr_to_str)] extern crate libc; extern crate mongoc_sys as mongoc; @@ -6,6 +7,11 @@ extern crate mongoc_sys as mongoc; #[macro_use] extern crate bson; +#[macro_use] +extern crate log; + +use std::ffi::CStr; +use std::ptr; use std::result; use std::sync::{Once,ONCE_INIT}; @@ -34,10 +40,41 @@ static MONGOC_INIT: Once = ONCE_INIT; /// anything else. fn init() { MONGOC_INIT.call_once(|| { - unsafe { bindings::mongoc_init(); } + unsafe { + // Init mongoc subsystem + bindings::mongoc_init(); + + // Set mongoc log handler + bindings::mongoc_log_set_handler( + Some(mongoc_log_handler), + ptr::null_mut() + ); + } }); } +extern fn mongoc_log_handler( + log_level: bindings::mongoc_log_level_t, + log_domain: *const ::libc::c_char, + message: *const ::libc::c_char, + _: *mut ::libc::c_void +) { + let log_domain_str = unsafe { CStr::from_ptr(log_domain).to_string_lossy() }; + let message_str = unsafe { CStr::from_ptr(message).to_string_lossy() }; + let log_line = format!("mongoc: {} - {}", log_domain_str, message_str); + + match log_level { + bindings::MONGOC_LOG_LEVEL_ERROR => error!("{}", log_line), + bindings::MONGOC_LOG_LEVEL_CRITICAL => error!("{}", log_line), + bindings::MONGOC_LOG_LEVEL_WARNING => warn!("{}", log_line), + bindings::MONGOC_LOG_LEVEL_MESSAGE => info!("{}", log_line), + bindings::MONGOC_LOG_LEVEL_INFO => info!("{}", log_line), + bindings::MONGOC_LOG_LEVEL_DEBUG => debug!("{}", log_line), + bindings::MONGOC_LOG_LEVEL_TRACE => trace!("{}", log_line), + _ => panic!("Unknown mongoc log level") + } +} + pub struct CommandAndFindOptions { pub query_flags: flags::Flags, pub skip: u32,