1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::log as glib_log;
use crate::translate::*;

// rustdoc-stripper-ignore-next
/// Enumeration of the possible formatting behaviours for a
/// [`GlibLogger`](struct.GlibLogger.html).
///
/// In order to use this type, `glib` must be built with the `log` feature
/// enabled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlibLoggerFormat {
    // rustdoc-stripper-ignore-next
    /// A simple format, writing only the message on output.
    Plain,
    // rustdoc-stripper-ignore-next
    /// A simple format, writing file, line and message on output.
    LineAndFile,
    // rustdoc-stripper-ignore-next
    /// A logger using glib structured logging. Structured logging is available
    /// only on features `v2_50` and later.
    #[cfg(any(feature = "v2_50", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_50")))]
    Structured,
}

// rustdoc-stripper-ignore-next
/// Enumeration of the possible domain handling behaviours for a
/// [`GlibLogger`](struct.GlibLogger.html).
///
/// In order to use this type, `glib` must be built with the `log` feature
/// enabled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlibLoggerDomain {
    // rustdoc-stripper-ignore-next
    /// Logs will have no domain specified.
    None,
    // rustdoc-stripper-ignore-next
    /// Logs will use the `target` of the log crate as a domain; this allows
    /// Rust code, like `warn!(target: "my-domain", "...");` to log to the glib
    /// logger using the specified domain.
    CrateTarget,
    // rustdoc-stripper-ignore-next
    /// Logs will use the crate path as the log domain.
    CratePath,
}

// rustdoc-stripper-ignore-next
/// An implementation of a [`log`](https://crates.io/crates/log) compatible
/// logger which logs over glib logging facilities.
///
/// In order to use this type, `glib` must be built with the `log` feature
/// enabled.
///
/// Use this if you want to use glib as the main logging output in your application,
/// and want to route all logging happening through the log crate to glib logging.
/// If you want the opposite, see
/// [`rust_log_handler`](fn.rust_log_handler.html).
///
/// NOTE: This should never be used when
/// [`rust_log_handler`](fn.rust_log_handler.html) has
/// been registered as a default glib log handler, otherwise a stack overflow
/// will occur.
///
/// Example:
///
/// ```no_compile
/// static glib_logger: glib::GlibLogger = glib::GlibLogger::new(
///     glib::GlibLoggerFormat::Plain,
///     glib::GlibLoggerDomain::CrateTarget,
/// );
///
/// log::set_logger(&glib_logger);
/// log::set_max_level(log::LevelFilter::Debug);
///
/// log::info!("This line will get logged by glib");
/// ```
#[derive(Debug)]
pub struct GlibLogger {
    format: GlibLoggerFormat,
    domain: GlibLoggerDomain,
}

impl GlibLogger {
    // rustdoc-stripper-ignore-next
    /// Creates a new instance of [`GlibLogger`](struct.GlibLogger.html).
    /// See documentation of [`GlibLogger`](struct.GlibLogger.html) for more
    /// information.
    ///
    /// Example:
    ///
    /// ```no_compile
    /// static glib_logger: glib::GlibLogger = glib::GlibLogger::new(
    ///     glib::GlibLoggerFormat::Plain,
    ///     glib::GlibLoggerDomain::CrateTarget,
    /// );
    ///
    /// log::set_logger(&glib_logger);
    /// log::set_max_level(log::LevelFilter::Debug);
    ///
    /// log::info!("This line will get logged by glib");
    /// ```
    pub const fn new(format: GlibLoggerFormat, domain: GlibLoggerDomain) -> Self {
        Self { format, domain }
    }

    fn level_to_glib(level: rs_log::Level) -> crate::LogLevel {
        match level {
            // Errors are mapped to critical to avoid automatic termination
            rs_log::Level::Error => crate::LogLevel::Critical,
            rs_log::Level::Warn => crate::LogLevel::Warning,
            rs_log::Level::Info => crate::LogLevel::Info,
            rs_log::Level::Debug => crate::LogLevel::Debug,
            // There is no equivalent to trace level in glib
            rs_log::Level::Trace => crate::LogLevel::Debug,
        }
    }

    #[doc(alias = "g_log")]
    fn write_log(domain: Option<&str>, level: rs_log::Level, message: &str) {
        unsafe {
            crate::ffi::g_log(
                domain.to_glib_none().0,
                GlibLogger::level_to_glib(level).into_glib(),
                b"%s\0".as_ptr() as *const _,
                ToGlibPtr::<*const std::os::raw::c_char>::to_glib_none(message).0,
            );
        }
    }

    #[cfg(any(feature = "v2_50", feature = "dox"))]
    fn write_log_structured(
        domain: Option<&str>,
        level: rs_log::Level,
        file: Option<&str>,
        line: Option<u32>,
        func: Option<&str>,
        message: &str,
    ) {
        let line = line.map(|l| l.to_string());
        let line = line.as_ref().map(|s| s.as_str());

        crate::log_structured!(
            domain.unwrap_or("default"),
            GlibLogger::level_to_glib(level),
            {
                "CODE_FILE" => file.unwrap_or("<unknown file>");
                "CODE_LINE" => line.unwrap_or("<unknown line>");
                "CODE_FUNC" => func.unwrap_or("<unknown module path>");
                "MESSAGE" => message;
            }
        );
    }
}

impl rs_log::Log for GlibLogger {
    fn enabled(&self, _: &rs_log::Metadata) -> bool {
        true
    }

    fn log(&self, record: &rs_log::Record) {
        if !self.enabled(record.metadata()) {
            return;
        }

        let domain = match &self.domain {
            GlibLoggerDomain::None => None,
            GlibLoggerDomain::CrateTarget => Some(record.metadata().target()),
            GlibLoggerDomain::CratePath => record.module_path(),
        };

        match self.format {
            GlibLoggerFormat::Plain => {
                let args = record.args();
                if let Some(s) = args.as_str() {
                    GlibLogger::write_log(domain, record.level(), s);
                } else {
                    GlibLogger::write_log(domain, record.level(), &args.to_string());
                }
            }
            GlibLoggerFormat::LineAndFile => {
                match (record.file(), record.line()) {
                    (Some(file), Some(line)) => {
                        let s = format!("{}:{}: {}", file, line, record.args());
                        GlibLogger::write_log(domain, record.level(), &s);
                    }
                    (Some(file), None) => {
                        let s = format!("{}: {}", file, record.args());
                        GlibLogger::write_log(domain, record.level(), &s);
                    }
                    _ => {
                        let args = record.args();
                        if let Some(s) = args.as_str() {
                            GlibLogger::write_log(domain, record.level(), s);
                        } else {
                            GlibLogger::write_log(domain, record.level(), &args.to_string());
                        }
                    }
                };
            }
            #[cfg(any(feature = "v2_50", feature = "dox"))]
            GlibLoggerFormat::Structured => {
                let args = record.args();
                if let Some(s) = args.as_str() {
                    GlibLogger::write_log_structured(
                        domain,
                        record.level(),
                        record.file(),
                        record.line(),
                        record.module_path(),
                        s,
                    );
                } else {
                    GlibLogger::write_log_structured(
                        domain,
                        record.level(),
                        record.file(),
                        record.line(),
                        record.module_path(),
                        &args.to_string(),
                    );
                }
            }
        };
    }

    fn flush(&self) {}
}

// rustdoc-stripper-ignore-next
/// Provides a glib log handler which routes all logging messages to the
/// [`log crate`](https://crates.io/crates/log).
///
/// In order to use this function, `glib` must be built with the `log` feature
/// enabled.
///
/// Use this function if you want to use the log crate as the main logging
/// output in your application, and want to route all logging happening in
/// glib to the log crate. If you want the opposite, use [`GlibLogger`](struct.GlibLogger.html).
///
/// NOTE: This should never be used when [`GlibLogger`](struct.GlibLogger.html) is
/// registered as a logger, otherwise a stack overflow will occur.
///
/// ```no_run
/// glib::log_set_default_handler(glib::rust_log_handler);
/// ```
pub fn rust_log_handler(domain: Option<&str>, level: glib_log::LogLevel, message: &str) {
    let level = match level {
        glib_log::LogLevel::Error | glib_log::LogLevel::Critical => rs_log::Level::Error,
        glib_log::LogLevel::Warning => rs_log::Level::Warn,
        glib_log::LogLevel::Message | glib_log::LogLevel::Info => rs_log::Level::Info,
        glib_log::LogLevel::Debug => rs_log::Level::Debug,
    };

    rs_log::log!(target: domain.unwrap_or("<null>"), level, "{}", message);
}

// rustdoc-stripper-ignore-next
/// A macro which behaves exactly as `log::error!` except that it sets the
/// current log target to the contents of a `G_LOG_DOMAIN` constant (and fails
/// to build if not defined).
///
/// In order to use this macro, `glib` must be built with the `log_macros`
/// feature enabled and the [`GlibLogger`](struct.GlibLogger.html) must have been
/// initialized using [`GlibLoggerDomain::CrateTarget`](enum.GlibLoggerDomain.html).
///
/// ```no_run
/// static G_LOG_DOMAIN: &str = "my-domain";
///
/// glib::error!("This will be logged under 'my-domain'");
/// ```
#[macro_export]
#[cfg(any(feature = "dox", feature = "log_macros"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "log_macros")))]
macro_rules! error {
    (target: $target:expr, $($arg:tt)+) => (
        $crate::rs_log::log!(target: $target, $crate::rs_log::Level::Error, $($arg)+);
    );
    ($($arg:tt)+) => (
        $crate::rs_log::log!(target: G_LOG_DOMAIN, $crate::rs_log::Level::Error, $($arg)+);
    )
}

// rustdoc-stripper-ignore-next
/// A macro which behaves exactly as `log::warn!` except that it sets the
/// current log target to the contents of a `G_LOG_DOMAIN` constant (and fails
/// to build if not defined).
///
/// In order to use this macro, `glib` must be built with the `log_macros`
/// feature enabled and the [`GlibLogger`](struct.GlibLogger.html) must have been
/// initialized using [`GlibLoggerDomain::CrateTarget`](enum.GlibLoggerDomain.html).
///
/// ```no_run
/// static G_LOG_DOMAIN: &str = "my-domain";
///
/// glib::warn!("This will be logged under 'my-domain'");
/// ```
#[macro_export]
#[cfg(any(feature = "dox", feature = "log_macros"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "log_macros")))]
macro_rules! warn {
    (target: $target:expr, $($arg:tt)+) => (
        $crate::rs_log::log!(target: $target, $crate::rs_log::Level::Warn, $($arg)+);
    );
    ($($arg:tt)+) => (
        $crate::rs_log::log!(target: G_LOG_DOMAIN, $crate::rs_log::Level::Warn, $($arg)+);
    )
}

// rustdoc-stripper-ignore-next
/// A macro which behaves exactly as `log::info!` except that it sets the
/// current log target to the contents of a `G_LOG_DOMAIN` constant (and fails
/// to build if not defined).
///
/// In order to use this macro, `glib` must be built with the `log_macros`
/// feature enabled and the [`GlibLogger`](struct.GlibLogger.html) must have been
/// initialized using [`GlibLoggerDomain::CrateTarget`](enum.GlibLoggerDomain.html).
///
/// ```no_run
/// static G_LOG_DOMAIN: &str = "my-domain";
///
/// glib::info!("This will be logged under 'my-domain'");
/// ```
#[macro_export]
#[cfg(any(feature = "dox", feature = "log_macros"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "log_macros")))]
macro_rules! info {
    (target: $target:expr, $($arg:tt)+) => (
        $crate::rs_log::log!(target: $target, $crate::rs_log::Level::Info, $($arg)+);
    );
    ($($arg:tt)+) => (
        $crate::rs_log::log!(target: G_LOG_DOMAIN, $crate::rs_log::Level::Info, $($arg)+);
    )
}

// rustdoc-stripper-ignore-next
/// A macro which behaves exactly as `log::debug!` except that it sets the
/// current log target to the contents of a `G_LOG_DOMAIN` constant (and fails
/// to build if not defined).
///
/// In order to use this macro, `glib` must be built with the `log_macros`
/// feature enabled and the [`GlibLogger`](struct.GlibLogger.html) must have been
/// initialized using [`GlibLoggerDomain::CrateTarget`](enum.GlibLoggerDomain.html).
///
/// ```no_run
/// static G_LOG_DOMAIN: &str = "my-domain";
///
/// glib::debug!("This will be logged under 'my-domain'");
/// ```
#[macro_export]
#[cfg(any(feature = "dox", feature = "log_macros"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "log_macros")))]
macro_rules! debug {
    (target: $target:expr, $($arg:tt)+) => (
        $crate::rs_log::log!(target: $target, $crate::rs_log::Level::Debug, $($arg)+);
    );
    ($($arg:tt)+) => (
        $crate::rs_log::log!(target: G_LOG_DOMAIN, $crate::rs_log::Level::Debug, $($arg)+);
    )
}

// rustdoc-stripper-ignore-next
/// A macro which behaves exactly as `log::trace!` except that it sets the
/// current log target to the contents of a `G_LOG_DOMAIN` constant (and fails
/// to build if not defined).
///
/// In order to use this macro, `glib` must be built with the `log_macros`
/// feature enabled and the [`GlibLogger`](struct.GlibLogger.html) must have been
/// initialized using [`GlibLoggerDomain::CrateTarget`](enum.GlibLoggerDomain.html).
///
/// ```no_run
/// static G_LOG_DOMAIN: &str = "my-domain";
///
/// glib::trace!("This will be logged under 'my-domain'");
/// ```
#[macro_export]
#[cfg(any(feature = "dox", feature = "log_macros"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "log_macros")))]
macro_rules! trace {
    (target: $target:expr, $($arg:tt)+) => (
        $crate::rs_log::log!(target: $target, $crate::rs_log::Level::Trace, $($arg)+);
    );
    ($($arg:tt)+) => (
        $crate::rs_log::log!(target: G_LOG_DOMAIN, $crate::rs_log::Level::Trace, $($arg)+);
    )
}