Skip to content

Commit

Permalink
Apple platform logging to oslog system and file (#1880)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmwample authored Jan 10, 2025
1 parent f6c85f7 commit 40dbaf5
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 40 deletions.
29 changes: 17 additions & 12 deletions nym-vpn-core/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion nym-vpn-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ nix = "0.29"
objc2 = "0.5"
objc2-foundation = "0.2"
once_cell = "1.20"
oslog = "0.2.0"
parity-tokio-ipc = "0.9.0"
parking_lot = "0.12"
pnet_packet = "0.35.0"
Expand Down Expand Up @@ -153,6 +152,7 @@ tower = "0.5.2"
tower-http = { version = "0.6.2", features = ["cors"] }
tracing = "0.1"
tracing-appender = "0.2.3"
tracing-oslog = "0.2.0"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
triggered = "0.1.1"
tun = { version = "0.6.1", features = ["async"] }
Expand Down
3 changes: 2 additions & 1 deletion nym-vpn-core/crates/nym-vpn-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ android_logger.workspace = true
rand.workspace = true

[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]
oslog.workspace = true
tracing-oslog.workspace = true
tracing-appender.workspace = true

[target.'cfg(target_os = "ios")'.dependencies]
debounced.workspace = true
Expand Down
11 changes: 5 additions & 6 deletions nym-vpn-core/crates/nym-vpn-lib/src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,16 +123,15 @@ pub fn configureLib(data_dir: String, credential_mode: Option<bool>) -> Result<(
}

async fn configure_lib(data_dir: String, credential_mode: Option<bool>) -> Result<(), VpnError> {
init_logger();
let network = environment::current_environment_details().await?;
account::init_account_controller(PathBuf::from(data_dir), credential_mode, network).await
}

fn init_logger() {
fn init_logger(path: Option<PathBuf>) {
let log_level = env::var("RUST_LOG").unwrap_or("info".to_string());
tracing::info!("Setting log level: {}", log_level);
tracing::info!("Setting log level: {log_level}, path?: {path:?}");
#[cfg(target_os = "ios")]
swift::init_logs(log_level);
swift::init_logs(log_level, path);
#[cfg(target_os = "android")]
android::init_logs(log_level);
}
Expand All @@ -141,8 +140,8 @@ fn init_logger() {
/// library. Thus it's only needed when `configureLib` is not used.
#[allow(non_snake_case)]
#[uniffi::export]
pub fn initLogger() {
init_logger();
pub fn initLogger(path: Option<PathBuf>) {
init_logger(path);
}

/// Returns the system messages for the current network environment
Expand Down
98 changes: 79 additions & 19 deletions nym-vpn-core/crates/nym-vpn-lib/src/platform/swift.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,91 @@
// Copyright 2023 - Nym Technologies SA <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only

use std::str::FromStr;

use log::LevelFilter;
use oslog::OsLogger;

pub fn init_logs(level: String) {
let result = OsLogger::new("net.nymtech.vpn.agent")
.level_filter(LevelFilter::from_str(&level).unwrap_or(LevelFilter::Info))
.category_level_filter("hyper", LevelFilter::Warn)
.category_level_filter("tokio_reactor", LevelFilter::Warn)
.category_level_filter("reqwest", LevelFilter::Warn)
.category_level_filter("mio", LevelFilter::Warn)
.category_level_filter("want", LevelFilter::Warn)
.category_level_filter("tungstenite", LevelFilter::Warn)
.category_level_filter("tokio_tungstenite", LevelFilter::Warn)
.category_level_filter("handlebars", LevelFilter::Warn)
.category_level_filter("sled", LevelFilter::Warn)
.init();
use std::{path::PathBuf, str::FromStr};

use tracing_oslog::OsLogger;
use tracing_subscriber::{
filter::LevelFilter, fmt::Layer, layer::SubscriberExt, util::SubscriberInitExt, Registry,
};

pub(crate) const DEFAULT_LOG_FILE: &str = "nym-vpn-lib.log";

pub fn init_logs(level: String, path: Option<PathBuf>) {
let oslogger_layer = OsLogger::new("net.nymtech.vpn.agent", "default");

let filter = tracing_subscriber::EnvFilter::builder()
.with_default_directive(
LevelFilter::from_str(&level)
.unwrap_or(LevelFilter::INFO)
.into(),
)
.from_env()
.unwrap()
.add_directive("hyper::proto=warn".parse().unwrap())
.add_directive("tokio_reactor::proto=warn".parse().unwrap())
.add_directive("reqwest::proto=warn".parse().unwrap())
.add_directive("mio::proto=warn".parse().unwrap())
.add_directive("want::proto=warn".parse().unwrap())
.add_directive("tungstenite::proto=warn".parse().unwrap())
.add_directive("tokio_tungstenite::proto=warn".parse().unwrap())
.add_directive("handlebars::proto=warn".parse().unwrap())
.add_directive("sled::proto=warn".parse().unwrap());

let registry = Registry::default().with(oslogger_layer);

let result = match path {
Some(ref log_path) => {
// If a path was provided attempt to add a tracing_subscriber Layer that logs to file
match try_make_writer(log_path.clone()) {
Some(appender) => {
let (non_blocking, _) = tracing_appender::non_blocking(appender);
let file_appender_layer = Layer::default().with_writer(non_blocking);
registry.with(file_appender_layer).with(filter).try_init()
}
None => {
// if we failed to make the file appender init just the os_log version.
tracing::error!("Failed to initialize file logger: bad path: \"{log_path:?}\"");
registry.with(filter).try_init()
}
}
}
// no file path provided -- init os_log logger
None => registry.with(filter).try_init(),
};

match result {
Ok(_) => {
tracing::debug!("Logger initialized");
tracing::debug!("Logger initialized level: {level}, path?:{path:?}");
}
Err(e) => {
tracing::error!("Failed to initialize os_log: {}", e);
}
};
}

fn try_make_writer(path: PathBuf) -> Option<tracing_appender::rolling::RollingFileAppender> {
let path = path.canonicalize().ok()?;

let (maybe_log_dir, filename) = if path.is_dir() {
(
Some(path.as_path()),
::std::path::Path::new(DEFAULT_LOG_FILE),
)
} else if path.is_file() {
(
path.parent(),
::std::path::Path::new(path.file_name().unwrap()),
)
} else {
return None;
};

// make sure that the path provides a directory, the directory exists and we have permission to access it.
if !maybe_log_dir.is_some_and(|d| d.try_exists().is_ok_and(|exists| exists)) {
return None;
};

let log_dir = maybe_log_dir.unwrap();

Some(tracing_appender::rolling::never(log_dir, filename))
}
2 changes: 1 addition & 1 deletion nym-vpn-core/crates/nym-vpnd/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub fn setup_logging(_as_service: bool) {
#[cfg(target_os = "macos")]
if _as_service {
let log_level = env::var("RUST_LOG").unwrap_or("info".to_string());
nym_vpn_lib::swift::init_logs(log_level);
nym_vpn_lib::swift::init_logs(log_level, None);
return;
}

Expand Down

0 comments on commit 40dbaf5

Please sign in to comment.