Skip to content

Commit

Permalink
Merge branch 'master' into dependabot/cargo/thiserror-1.0.50
Browse files Browse the repository at this point in the history
  • Loading branch information
ibigbug authored Oct 20, 2023
2 parents eacf92d + 98df5c1 commit ad6ee8d
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 12 deletions.
23 changes: 23 additions & 0 deletions Cargo.lock

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

4 changes: 1 addition & 3 deletions clash/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ struct Cli {
default_value = "config.yaml"
)]
config: PathBuf,

#[clap(short, long, action)]
test: bool,
}

fn main() {
Expand All @@ -36,6 +33,7 @@ fn main() {
),
cwd: cli.directory.map(|x| x.to_string_lossy().to_string()),
rt: Some(TokioRuntime::MultiThread),
log_file: None,
})
.unwrap();
}
1 change: 1 addition & 0 deletions clash_lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ tokio-tungstenite = "0.20.0"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing-oslog = "0.1"
tracing-appender = "0.2.2"


shadowsocks = { git = "https://github.com/Watfaq/shadowsocks-rust.git", optional = true, features=["aead-cipher-2022"], rev = "2021741" }
Expand Down
45 changes: 41 additions & 4 deletions clash_lib/src/app/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use serde::Serialize;
use tokio::sync::broadcast::Sender;

use tracing::debug;
use tracing_appender::non_blocking::NonBlocking;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_oslog::OsLogger;
use tracing_subscriber::filter::Directive;
use tracing_subscriber::prelude::*;
Expand Down Expand Up @@ -68,10 +70,34 @@ where
}
}

pub fn setup_logging(level: LogLevel, collector: EventCollector) -> anyhow::Result<()> {
struct W(Option<NonBlocking>);

impl std::io::Write for W {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
match self.0 {
Some(ref mut w) => w.write(buf),
None => Ok(buf.len()),
}
}

fn flush(&mut self) -> std::io::Result<()> {
match self.0 {
Some(ref mut w) => w.flush(),
None => Ok(()),
}
}
}

pub fn setup_logging(
level: LogLevel,
collector: EventCollector,
cwd: &str,
log_file: Option<String>,
) -> anyhow::Result<Option<WorkerGuard>> {
#[cfg(feature = "tracing")]
{
console_subscriber::init();
Ok(None)
}
#[cfg(not(feature = "tracing"))]
{
Expand Down Expand Up @@ -104,6 +130,14 @@ pub fn setup_logging(level: LogLevel, collector: EventCollector) -> anyhow::Resu
None
};

let (appender, g) = if let Some(log_file) = log_file {
let file_appender = tracing_appender::rolling::daily(cwd, log_file);
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
(Some(non_blocking), Some(guard))
} else {
(None, None)
};

let subscriber = tracing_subscriber::registry()
.with(jaeger)
.with(filter)
Expand All @@ -114,7 +148,10 @@ pub fn setup_logging(level: LogLevel, collector: EventCollector) -> anyhow::Resu
.pretty()
.with_file(true)
.with_line_number(true)
.with_writer(std::io::stdout),
.with_writer(std::io::stdout)
.with_writer(move || -> Box<dyn std::io::Write> {
Box::new(W(appender.clone()))
}),
)
.with(ios_os_log);

Expand All @@ -124,9 +161,9 @@ pub fn setup_logging(level: LogLevel, collector: EventCollector) -> anyhow::Resu
if let Ok(jager_endpiont) = std::env::var("JAGER_ENDPOINT") {
debug!("jager endpoint: {}", jager_endpiont);
}
}

Ok(())
Ok(g)
}
}

struct EventVisitor<'a>(&'a mut Vec<String>);
Expand Down
17 changes: 12 additions & 5 deletions clash_lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ pub struct Options {
pub config: Config,
pub cwd: Option<String>,
pub rt: Option<TokioRuntime>,
pub log_file: Option<String>,
}

pub enum TokioRuntime {
Expand Down Expand Up @@ -128,19 +129,24 @@ async fn start_async(opts: Options) -> Result<(), Error> {
Config::Str(s) => s.parse::<def::Config>()?.try_into()?,
};

let cwd = opts.cwd.unwrap_or_else(|| ".".to_string());
let cwd = std::path::Path::new(&cwd);

let (log_tx, _) = broadcast::channel(100);

let log_collector = app::logging::EventCollector::new(vec![log_tx.clone()]);

app::logging::setup_logging(config.general.log_level, log_collector)
.map_err(|x| Error::InvalidConfig(format!("failed to setup logging: {}", x.to_string())))?;
let _g = app::logging::setup_logging(
config.general.log_level,
log_collector,
cwd.to_str().unwrap(),
opts.log_file,
)
.map_err(|x| Error::InvalidConfig(format!("failed to setup logging: {}", x.to_string())))?;

let mut tasks = Vec::<Runner>::new();
let mut runners = Vec::new();

let cwd = opts.cwd.unwrap_or_else(|| ".".to_string());
let cwd = std::path::Path::new(&cwd);

let system_resolver =
Arc::new(SystemResolver::new().map_err(|x| Error::DNSError(x.to_string()))?);
let client = new_http_client(system_resolver).map_err(|x| Error::DNSError(x.to_string()))?;
Expand Down Expand Up @@ -293,6 +299,7 @@ mod tests {
config: Config::Str(conf.to_string()),
cwd: None,
rt: None,
log_file: None,
})
.unwrap()
});
Expand Down

0 comments on commit ad6ee8d

Please sign in to comment.