MacOS unified log with oslog crate

382 Views Asked by At

I'd like to write to Apple's unified log on macOS from Rust.

I found the oslog crate which seems promising and I have the following code so far:

#[macro_use]
extern crate log;
use oslog::OsLogger;

fn main() {
    //env_logger::init();

    OsLogger::new("com.rust")
        //.level_filter(LevelFilter::Trace)
        .init()
        .unwrap();

    info!("starting up");
}

If I use the commented env_logger I can see the logs show up in Terminal, but with OSLogger - nothing shows up in the Console.app on macOS or if I stream the log like so:

log stream --predicate 'subsystem == "com.rust"'

Anyone here have done this? Maybe I'm missing something obvious, no experience with Rust yet.

1

There are 1 best solutions below

0
Marin Todorov On

Ok, so there were 2 parts to solving this and I'm posting the full code below.

First of all, you have to set an environment variable that enables logging when running the program. The value sets the level of log filtering to apply:

$ RUST_LOG=trace ./myrustprogram

Secondly, you have to set matching log levels when creating the oslog facade via level_filter(...):

#[macro_use]
extern crate log;
use oslog::OsLogger;
use log::LevelFilter;

fn main() {
    OsLogger::new("com.rust")
        .level_filter(LevelFilter::Info)
        .init()
        .unwrap();

    info!("Hello from Rust: true");
    info!("Velocity: 2");
}

This writes to the unified log and can be observed via Console.app on macOS