Skip to content

Commit

Permalink
Migrate to proper logging
Browse files Browse the repository at this point in the history
  • Loading branch information
jieyouxu authored and trumank committed Aug 12, 2023
1 parent b5bd68d commit 6acca34
Show file tree
Hide file tree
Showing 9 changed files with 46 additions and 52 deletions.
15 changes: 0 additions & 15 deletions src/gui/log.rs

This file was deleted.

11 changes: 6 additions & 5 deletions src/gui/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use tokio::{
sync::mpsc::{self, Sender},
task::JoinHandle,
};
use tracing::{error, info};

use crate::state::{ModData_v0_1_0 as ModData, ModOrGroup};
use crate::{
Expand Down Expand Up @@ -155,7 +156,7 @@ impl ResolveMods {
LastActionStatus::Failure("no provider".to_string());
}
Err(e) => {
app.log.println(format!("{:#?}\n{}", e, e.backtrace()));
error!("{:#?}\n{}", e, e.backtrace());
app.last_action_status = LastActionStatus::Failure(e.to_string());
}
},
Expand Down Expand Up @@ -197,7 +198,7 @@ impl Integrate {
if Some(self.rid) == app.integrate_rid.as_ref().map(|r| r.rid) {
match self.result {
Ok(()) => {
app.log.println("Integration complete");
info!("integration complete");
app.last_action_status =
LastActionStatus::Success("integration complete".to_string());
}
Expand All @@ -209,7 +210,7 @@ impl Integrate {
LastActionStatus::Failure("no provider".to_string());
}
Err(e) => {
app.log.println(format!("{:#?}\n{}", e, e.backtrace()));
error!("{:#?}\n{}", e, e.backtrace());
app.last_action_status = LastActionStatus::Failure(e.to_string());
}
},
Expand Down Expand Up @@ -265,7 +266,7 @@ impl UpdateCache {
if Some(self.rid) == app.update_rid.as_ref().map(|r| r.rid) {
match self.result {
Ok(()) => {
app.log.println("Cache update complete");
info!("cache update complete");
app.last_action_status =
LastActionStatus::Success("successfully updated cache".to_string());
}
Expand All @@ -278,7 +279,7 @@ impl UpdateCache {
LastActionStatus::Failure("no provider".to_string());
}
Err(e) => {
app.log.println(format!("{:#?}", e));
error!("{:#?}\n{}", e, e.backtrace());
app.last_action_status = LastActionStatus::Failure(e.to_string());
}
},
Expand Down
17 changes: 4 additions & 13 deletions src/gui/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
mod find_string;
mod log;
mod message;
mod named_combobox;
mod request_counter;
Expand All @@ -21,6 +20,7 @@ use tokio::{
sync::mpsc::{self, Receiver, Sender},
task::JoinHandle,
};
use tracing::{debug, info};

use crate::state::ModOrGroup;
use crate::{
Expand All @@ -31,7 +31,6 @@ use crate::{
state::{ModConfig, ModData_v0_1_0 as ModData, State},
};
use find_string::FindString;
use log::Log;
use message::MessageHandle;
use request_counter::{RequestCounter, RequestID};

Expand All @@ -57,7 +56,6 @@ pub struct App {
tx: Sender<message::Message>,
rx: Receiver<message::Message>,
state: State,
log: Log,
resolve_mod: String,
resolve_mod_rid: Option<MessageHandle<()>>,
integrate_rid: Option<MessageHandle<HashMap<ModSpecification, SpecFetchProgress>>>,
Expand All @@ -84,24 +82,16 @@ enum LastActionStatus {
impl App {
fn new(args: Option<Vec<String>>) -> Result<Self> {
let (tx, rx) = mpsc::channel(10);
let mut log = Log::default();
let state = State::init()?;
log.println(format!(
"config dir: {}",
state.project_dirs.config_dir().display()
));
log.println(format!(
"cache dir: {}",
state.project_dirs.cache_dir().display()
));
info!("config dir = {}", state.project_dirs.config_dir().display());
info!("cache dir = {}", state.project_dirs.cache_dir().display());

Ok(Self {
args,
tx,
rx,
request_counter: Default::default(),
state,
log,
resolve_mod: Default::default(),
resolve_mod_rid: None,
integrate_rid: None,
Expand Down Expand Up @@ -819,6 +809,7 @@ impl eframe::App for App {
}
});

debug!("uninstalling mods: pak_path = {}", pak_path.display());
match uninstall(pak_path, mods) {
Ok(()) => {
self.last_action_status =
Expand Down
5 changes: 4 additions & 1 deletion src/integrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use repak::PakWriter;
use tracing::info;

use crate::providers::{ModInfo, ReadSeek};
use crate::splice::TrackedStatement;
Expand Down Expand Up @@ -39,6 +40,7 @@ use unreal_asset::{
/// back to the config so they will be disabled when the game is launched again. Since we have
/// Modio IDs anyway, with just a little more effort we can make the 'uninstall' button work as an
/// 'install' button for the official integration. Best anti-feature ever.
#[tracing::instrument(level = "debug", skip(path_pak))]
pub fn uninstall<P: AsRef<Path>>(path_pak: P, modio_mods: HashSet<u32>) -> Result<()> {
let installation = DRGInstallation::from_pak_path(path_pak)?;
let path_mods_pak = installation.paks_path().join("mods_P.pak");
Expand All @@ -59,6 +61,7 @@ pub fn uninstall<P: AsRef<Path>>(path_pak: P, modio_mods: HashSet<u32>) -> Resul
Ok(())
}

#[tracing::instrument(level = "debug")]
fn uninstall_modio(installation: &DRGInstallation, modio_mods: HashSet<u32>) -> Result<()> {
#[derive(Debug, serde::Deserialize)]
struct ModioState {
Expand Down Expand Up @@ -419,7 +422,7 @@ pub fn integrate<P: AsRef<Path>>(path_pak: P, mods: Vec<(ModInfo, PathBuf)>) ->

mod_pak.write_index()?;

println!(
info!(
"{} mods installed to {}",
mods.len(),
path_mod_pak.display()
Expand Down
12 changes: 9 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@ use anyhow::{bail, Context, Result};
use error::IntegrationError;
use providers::{ModSpecification, ProviderFactory};
use state::State;
use tracing::{info, warn};

#[derive(Debug)]
pub enum DRGInstallationType {
Steam,
Xbox,
}

impl DRGInstallationType {
pub fn from_pak_path<P: AsRef<Path>>(pak: P) -> Result<Self> {
let pak_name = pak
Expand Down Expand Up @@ -50,6 +53,7 @@ impl DRGInstallationType {
}
}

#[derive(Debug)]
pub struct DRGInstallation {
pub root: PathBuf,
pub installation_type: DRGInstallationType,
Expand Down Expand Up @@ -139,6 +143,7 @@ pub fn is_drg_pak<P: AsRef<Path>>(path: P) -> Result<()> {
Ok(())
}

#[tracing::instrument(level = "debug", skip(path_game, state))]
pub async fn resolve_and_integrate<P: AsRef<Path>>(
path_game: P,
state: &State,
Expand All @@ -163,9 +168,9 @@ pub async fn resolve_and_integrate<P: AsRef<Path>>(
})
.collect::<HashSet<_>>();
if !missing_deps.is_empty() {
println!("WARNING: The following dependencies are missing:");
warn!("the following dependencies are missing:");
for d in missing_deps {
println!(" {d}");
warn!(" {d}");
}
}

Expand All @@ -178,12 +183,13 @@ pub async fn resolve_and_integrate<P: AsRef<Path>>(
.map(|m| &m.resolution)
.collect::<Vec<_>>();

println!("fetching mods...");
info!("fetching mods...");
let paths = state.store.fetch_mods(&urls, update, None).await?;

integrate::integrate(path_game, to_integrate.into_iter().zip(paths).collect())
}

#[tracing::instrument(level = "debug", skip(path_game, state, init))]
pub async fn resolve_and_integrate_with_provider_init<P, F>(
path_game: P,
state: &mut State,
Expand Down
15 changes: 11 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,14 @@ struct Args {
fn main() -> Result<()> {
std::env::set_var("RUST_BACKTRACE", "1");
let _guard = setup_logging()?;
debug!("logging setup complete");

let rt = tokio::runtime::Runtime::new().expect("Unable to create Runtime");
debug!("tokio runtime created");
let _enter = rt.enter();

let args = Args::parse();
debug!(?args);

match args.action {
Some(Action::Integrate(action)) => rt.block_on(async {
Expand Down Expand Up @@ -153,9 +156,7 @@ fn setup_logging() -> Result<WorkerGuard> {
.with_writer(log_file_appender)
.fmt_fields(NewType(Pretty::default()))
.with_ansi(false)
.with_filter(filter::filter_fn(|metadata| {
*metadata.level() <= Level::DEBUG && metadata.target() == "drg_mod_integration"
}));
.with_filter(filter::Targets::new().with_target("drg_mod_integration", Level::DEBUG));
let stdout_log = fmt::layer()
.compact()
.with_level(true)
Expand Down Expand Up @@ -184,8 +185,10 @@ fn setup_logging() -> Result<WorkerGuard> {
Ok(guard)
}

#[tracing::instrument(skip(state))]
fn init_provider(state: &mut State, url: String, factory: &ProviderFactory) -> Result<()> {
println!("Initializing provider for {:?}", url);
info!("initializing provider for {:?}", url);

let params = state
.config
.provider_parameters
Expand All @@ -205,6 +208,7 @@ fn init_provider(state: &mut State, url: String, factory: &ProviderFactory) -> R
state.store.add_provider(factory, params)
}

#[tracing::instrument]
async fn action_integrate(action: ActionIntegrate) -> Result<()> {
let path_game_pak = action
.fsd_pak
Expand All @@ -214,6 +218,7 @@ async fn action_integrate(action: ActionIntegrate) -> Result<()> {
.map(DRGInstallation::main_pak)
})
.context("Could not find DRG pak file, please specify manually with the --fsd_pak flag")?;
debug!(?path_game_pak);

let mut state = State::init()?;

Expand All @@ -233,6 +238,7 @@ async fn action_integrate(action: ActionIntegrate) -> Result<()> {
.await
}

#[tracing::instrument]
async fn action_integrate_profile(action: ActionIntegrateProfile) -> Result<()> {
let path_game_pak = action
.fsd_pak
Expand All @@ -242,6 +248,7 @@ async fn action_integrate_profile(action: ActionIntegrateProfile) -> Result<()>
.map(DRGInstallation::main_pak)
})
.context("Could not find DRG pak file, please specify manually with the --fsd_pak flag")?;
debug!(?path_game_pak);

let mut state = State::init()?;

Expand Down
3 changes: 2 additions & 1 deletion src/providers/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{collections::HashMap, sync::Arc};
use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc::Sender;
use tracing::info;

use super::{
BlobCache, BlobRef, FetchProgress, ModInfo, ModProvider, ModProviderCache, ModResolution,
Expand Down Expand Up @@ -122,7 +123,7 @@ impl ModProvider for HttpProvider {
}
path
} else {
println!("downloading mod {url}...");
info!("downloading mod {url}...");
let response = self.client.get(url).send().await?.error_for_status()?;
let size = response.content_length(); // TODO will be incorrect if compressed
if let Some(mime) = response
Expand Down
9 changes: 5 additions & 4 deletions src/providers/modio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use reqwest_middleware::{Middleware, Next};
use serde::{Deserialize, Serialize};
use task_local_extensions::Extensions;
use tokio::sync::mpsc::Sender;
use tracing::info;

use super::{
ApprovalStatus, BlobCache, BlobRef, FetchProgress, ModInfo, ModProvider, ModProviderCache,
Expand Down Expand Up @@ -176,16 +177,16 @@ impl Middleware for LoggingMiddleware {
next: Next<'_>,
) -> reqwest_middleware::Result<Response> {
loop {
println!(
"Request started {} {:?}",
info!(
"request started {} {:?}",
self.requests
.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
req.url().path()
);
let res = next.clone().run(req.try_clone().unwrap(), extensions).await;
if let Ok(res) = &res {
if let Some(retry) = res.headers().get("retry-after") {
println!("retrying after: {}...", retry.to_str().unwrap());
info!("retrying after: {}...", retry.to_str().unwrap());
tokio::time::sleep(tokio::time::Duration::from_secs(
retry.to_str().unwrap().parse::<u64>().unwrap(),
))
Expand Down Expand Up @@ -510,7 +511,7 @@ impl ModProvider for ModioProvider {
let size = file.filesize;
let download: modio::download::DownloadAction = file.into();

println!("downloading mod {url}...");
info!("downloading mod {url}...");

use futures::stream::TryStreamExt;
use tokio::io::AsyncWriteExt;
Expand Down
11 changes: 5 additions & 6 deletions src/splice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,13 @@ pub fn read_asset<P: AsRef<Path>>(
let mut out_uexp = Cursor::new(vec![]);
asset.write_data(&mut out_uasset, Some(&mut out_uexp))?;
if uasset.get_ref() != out_uasset.get_ref() || uexp.get_ref() != out_uexp.get_ref() {
println!(
"Binary equality not maintained: {}",
error!(
"binary equality not maintained: {}",
path.as_ref().display()
);
} else {
println!(
"Preliminary binary equality check passed {}",
info!(
"preliminary binary equality check passed {}",
path.as_ref().display()
);
}
Expand Down Expand Up @@ -741,7 +741,6 @@ fn resolve_tracked_statements<C: std::io::Read + std::io::Seek>(

inst.into_iter()
.map(|mut inst| {
//println!( "{:?} {} {:#?}", pi, export.get_base_export().object_name.get_content(), mappings.get(&pi));
let dest = inst.points_to.as_ref().unwrap_or(&inst.origin);
match &mut inst.ex {
// fix jumps into ubergraph
Expand Down Expand Up @@ -980,7 +979,7 @@ pub fn find_hooks<'a, C: std::io::Read + std::io::Seek>(
/*
for (a, bs) in &jumps {
for b in bs {
println!("{}:{} -> {}:{}", a.0.index, a.1, b.0.index, b.1);
trace!("{}:{} -> {}:{}", a.0.index, a.1, b.0.index, b.1);
}
}
*/
Expand Down

0 comments on commit 6acca34

Please sign in to comment.