~nerosnm/oslog

ref: 0e3d740f4b1730db51f26624a578323091660a7c oslog/os_log/src/lib.rs -rw-r--r-- 1.3 KiB
0e3d740f — Søren Mortensen Wrapper library allows actually calling into os_log 3 years ago
                                                                                
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
//
//  lib.rs
//  os_log
//
//  Created by Søren Mortensen on 28/07/2018.
//  Copyright © 2018 Søren Mortensen. All rights reserved.
//

extern crate log;

pub mod os_log;

use log::{Record, Level, Log, Metadata, SetLoggerError};

use std::ffi::CString;

use os_log::*;

struct OsLog {
    level: Level,
}

#[repr(u32)]
enum OsLogType {
    Default = OS_LOG_TYPE_DEFAULT,
    Info = OS_LOG_TYPE_INFO,
    Debug = OS_LOG_TYPE_DEBUG,
    Error = OS_LOG_TYPE_ERROR,
    Fault = OS_LOG_TYPE_FAULT,
}

impl Log for OsLog {
    fn enabled(&self, metadata: &Metadata) -> bool {
        metadata.level() <= self.level
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            let string = format!("{}", record.args());
            let c_string = CString::new(string).unwrap();
            unsafe { _os_log_fault(c_string.as_ptr()); }
        }
    }

    fn flush(&self) {}
}

pub fn init_with_level(level: Level) -> Result<(), SetLoggerError> {
    log::set_boxed_logger(Box::new(OsLog { level }))
        .map(|()| log::set_max_level(level.to_level_filter()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_thing() {
        let string = format!("{}", "This is a test log from os_log");
        let c_string = CString::new(string).unwrap();
        unsafe { _os_log_fault(c_string.as_ptr()); }
    }
}