Skip to main content

odbc_api/handles/
logging.rs

1#[cfg(feature = "structured_logging")]
2use super::slice_to_cow_utf8;
3use super::{DiagnosticStream, Diagnostics, Record};
4use log::{Level, warn};
5
6/// This function inspects all the diagnostics of an ODBC handle and logs their text messages. It
7/// is going to print placeholder characters, if it cannot convert the message to UTF-8.
8pub fn log_diagnostics(handle: &(impl Diagnostics + ?Sized)) {
9    if log::max_level() < Level::Warn {
10        // Early return to safe work creating all these log records in case we would not log
11        // anything.
12        return;
13    }
14
15    let mut diagnostic_stream = DiagnosticStream::new(handle);
16
17    // Log results, while there are diagnostic records
18    while let Some(record) = diagnostic_stream.next() {
19        log_diagnostic_record(record);
20    }
21}
22
23/// Emits a single diagnostic record as a `warn!`. If you want to log all the diagnostics of a
24/// handle, instead of a single one use [`log_diagnostics`] instead.
25pub fn log_diagnostic_record(record: &Record) {
26    #[cfg(not(feature = "structured_logging"))]
27    warn!("{record}");
28    #[cfg(feature = "structured_logging")]
29    warn!(
30        target: "odbc",
31        state = record.state.as_str(),
32        native_error = record.native_error;
33        "{}", slice_to_cow_utf8(&record.message)
34    );
35}