~vpzom/lotide

6dd651ac975eb4f21353ac0c7db26f2f99ae5079 — Matthias Beyer 2 months ago c1cf009
Introduce logging via log crate

This patch introduces logging via the `log` and `env_logger` crate.
All `eprintln!()` calls were replaced with `log::error!()` and all
`println!()` calls with `log::debug!()`.

Signed-off-by: Matthias Beyer <mail@beyermatthias.de>
Tested-by: Matthias Beyer <mail@beyermatthias.de>
M Cargo.lock => Cargo.lock +41 -0
@@ 103,6 103,17 @@ dependencies = [
]

[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
 "hermit-abi",
 "libc",
 "winapi 0.3.9",
]

[[package]]
name = "autocfg"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"


@@ 439,6 450,19 @@ dependencies = [
]

[[package]]
name = "env_logger"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26ecb66b4bdca6c1409b40fb255eefc2bd4f6d135dab3c3124f80ffa2a9661e"
dependencies = [
 "atty",
 "humantime",
 "log",
 "regex",
 "termcolor",
]

[[package]]
name = "error-chain"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"


@@ 866,6 890,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd179ae861f0c2e53da70d892f5f3029f9594be0c41dc5269cd371691b1dc2f9"

[[package]]
name = "humantime"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c1ad908cc71012b7bea4d0c53ba96a8cba9962f048fa68d143376143d863b7a"

[[package]]
name = "hyper"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"


@@ 1110,6 1140,7 @@ dependencies = [
 "chrono",
 "deadpool-postgres",
 "either",
 "env_logger",
 "fast_chemail",
 "fluent",
 "fluent-langneg",


@@ 1122,6 1153,7 @@ dependencies = [
 "hyper-tls",
 "lazy_static",
 "lettre",
 "log",
 "migrant_lib",
 "mime",
 "openssl",


@@ 2134,6 2166,15 @@ dependencies = [
]

[[package]]
name = "termcolor"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dfed899f0eb03f32ee8c6a0aabdb8a7949659e3466561fc0adf54e26d88c5f4"
dependencies = [
 "winapi-util",
]

[[package]]
name = "thiserror"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"

M Cargo.toml => Cargo.toml +2 -0
@@ 52,6 52,8 @@ base64 = "0.13.0"
pulldown-cmark = "0.8.0"
migrant_lib = { version = "0.30.0", features = ["d-postgres"] }
pdcm-linkify = "0.1.0"
log = "0.4"
env_logger = "0.8"

[dev-dependencies]
rand = "0.7.3"

M src/apub_util/ingest.rs => src/apub_util/ingest.rs +1 -1
@@ 194,7 194,7 @@ pub async fn ingest_object(
                                );
                            }
                        } else {
                            eprintln!("Warning: recieved follow for unknown community");
                            log::error!("Warning: recieved follow for unknown community");
                        }
                    }
                }

M src/apub_util/mod.rs => src/apub_util/mod.rs +4 -4
@@ 726,7 726,7 @@ pub fn spawn_announce_community_post(
    match local_community_post_announce_ap(community, post_local_id, post_ap_id, &ctx.host_url_apub)
    {
        Err(err) => {
            eprintln!("Failed to create Announce: {:?}", err);
            log::error!("Failed to create Announce: {:?}", err);
        }
        Ok(announce) => {
            crate::spawn_task(enqueue_send_to_community_followers(


@@ 879,7 879,7 @@ pub fn spawn_enqueue_send_community_follow_accept(
        };

        let accept = community_follow_accept_to_ap(community_ap_id, follower, follow_ap_id)?;
        println!("{:?}", accept);
        log::debug!("{:?}", accept);

        let body = serde_json::to_string(&accept)?;



@@ 1400,8 1400,8 @@ pub async fn check_signature_for_actor(
            })
        }).transpose()?;

    println!("signature: {:?}", signature);
    println!("found_key: {:?}", found_key.is_some());
    log::debug!("signature: {:?}", signature);
    log::debug!("found_key: {:?}", found_key.is_some());

    let signature = hancock::Signature::parse(signature)?;


M src/main.rs => src/main.rs +9 -8
@@ 545,7 545,7 @@ impl Translator {
            &mut errors,
        );
        if !errors.is_empty() {
            eprintln!("Errors in translation: {:?}", errors);
            log::error!("Errors in translation: {:?}", errors);
        }

        out


@@ 578,7 578,7 @@ pub fn get_lang_for_req(req: &impl ReqParts) -> Translator {
                match err {
                    fluent::FluentError::Overriding { .. } => {}
                    _ => {
                        eprintln!("Failed to add language resource: {:?}", err);
                        log::error!("Failed to add language resource: {:?}", err);
                        break;
                    }
                }


@@ 661,7 661,7 @@ pub async fn is_local_user(db: &tokio_postgres::Client, user: UserLocalID) -> Re
pub fn spawn_task<F: std::future::Future<Output = Result<(), Error>> + Send + 'static>(task: F) {
    use futures::future::TryFutureExt;
    tokio::spawn(task.map_err(|err| {
        eprintln!("Error in task: {:?}", err);
        log::error!("Error in task: {:?}", err);
    }));
}



@@ 682,7 682,7 @@ pub fn on_local_community_add_post(
    post_ap_id: url::Url,
    ctx: Arc<crate::RouteContext>,
) {
    println!("on_community_add_post");
    log::debug!("on_community_add_post");
    crate::apub_util::spawn_announce_community_post(community, post_local_id, post_ap_id, ctx);
}



@@ 703,7 703,7 @@ pub fn on_local_community_add_comment(
pub fn on_post_add_comment(comment: CommentInfo<'static>, ctx: Arc<crate::RouteContext>) {
    use futures::future::TryFutureExt;

    println!("on_post_add_comment");
    log::debug!("on_post_add_comment");
    spawn_task(async move {
        let db = ctx.db_pool.get().await?;



@@ 910,6 910,7 @@ pub fn on_post_add_comment(comment: CommentInfo<'static>, ctx: Arc<crate::RouteC
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    env_logger::init();
    let mut args = std::env::args();
    args.next(); // discard first element
    match args.next().as_deref() {


@@ 1100,7 1101,7 @@ async fn run() -> Result<(), Box<dyn std::error::Error>> {
                            Err(Error::UserError(res)) => res,
                            Err(Error::RoutingError(err)) => err.to_simple_response(),
                            Err(Error::Internal(err)) => {
                                eprintln!("Error: {:?}", err);
                                log::error!("Error: {:?}", err);

                                simple_response(
                                    hyper::StatusCode::INTERNAL_SERVER_ERROR,


@@ 1108,7 1109,7 @@ async fn run() -> Result<(), Box<dyn std::error::Error>> {
                                )
                            }
                            Err(Error::InternalStr(err)) => {
                                eprintln!("Error: {}", err);
                                log::error!("Error: {}", err);

                                simple_response(
                                    hyper::StatusCode::INTERNAL_SERVER_ERROR,


@@ 1116,7 1117,7 @@ async fn run() -> Result<(), Box<dyn std::error::Error>> {
                                )
                            }
                            Err(Error::InternalStrStatic(err)) => {
                                eprintln!("Error: {}", err);
                                log::error!("Error: {}", err);

                                simple_response(
                                    hyper::StatusCode::INTERNAL_SERVER_ERROR,

M src/migrate.rs => src/migrate.rs +2 -2
@@ 74,7 74,7 @@ pub fn run(mut args: std::env::Args) {

        match action {
            "up" => {
                println!("Applying migrations...");
                log::debug!("Applying migrations...");
                migrant_lib::Migrator::with_config(&config)
                    .all(true)
                    .swallow_completion(true)


@@ 82,7 82,7 @@ pub fn run(mut args: std::env::Args) {
                    .expect("Failed to apply migrations");
            }
            "down" => {
                println!("Unapplying migration...");
                log::debug!("Unapplying migration...");
                migrant_lib::Migrator::with_config(&config)
                    .direction(migrant_lib::Direction::Down)
                    .all(false)

M src/routes/api/mod.rs => src/routes/api/mod.rs +6 -6
@@ 274,7 274,7 @@ async fn route_unstable_actors_lookup(
    _req: hyper::Request<hyper::Body>,
) -> Result<hyper::Response<hyper::Body>, crate::Error> {
    let (query,) = params;
    println!("lookup {}", query);
    log::debug!("lookup {}", query);

    let lookup = parse_lookup(&query)?;



@@ 289,14 289,14 @@ async fn route_unstable_actors_lookup(
                    rel: Some("self".into()),
                })?
            );
            println!("{}", uri);
            log::debug!("{}", uri);
            let res = ctx
                .http_client
                .request(hyper::Request::get(uri).body(Default::default())?)
                .await?;

            if res.status() == hyper::StatusCode::NOT_FOUND {
                println!("not found");
                log::debug!("not found");
                None
            } else {
                let res = crate::res_to_error(res).await?;


@@ 578,7 578,7 @@ async fn route_unstable_objects_lookup(
    _req: hyper::Request<hyper::Body>,
) -> Result<hyper::Response<hyper::Body>, crate::Error> {
    let (query,) = params;
    println!("lookup {}", query);
    log::debug!("lookup {}", query);

    let lookup = parse_lookup(&query)?;



@@ 593,14 593,14 @@ async fn route_unstable_objects_lookup(
                    rel: Some("self".into()),
                })?
            );
            println!("{}", uri);
            log::debug!("{}", uri);
            let res = ctx
                .http_client
                .request(hyper::Request::get(uri).body(Default::default())?)
                .await?;

            if res.status() == hyper::StatusCode::NOT_FOUND {
                println!("not found");
                log::debug!("not found");
                None
            } else {
                let res = crate::res_to_error(res).await?;

M src/routes/apub/communities.rs => src/routes/apub/communities.rs +1 -1
@@ 112,7 112,7 @@ async fn handler_communities_get(
                    .and_then(|bytes| match std::str::from_utf8(bytes) {
                        Ok(key) => Some(key),
                        Err(err) => {
                            eprintln!("Warning: public_key is not UTF-8: {:?}", err);
                            log::error!("Warning: public_key is not UTF-8: {:?}", err);
                            None
                        }
                    });

M src/routes/apub/mod.rs => src/routes/apub/mod.rs +1 -1
@@ 143,7 143,7 @@ async fn handler_users_get(
                    .and_then(|bytes| match std::str::from_utf8(bytes) {
                        Ok(key) => Some(key),
                        Err(err) => {
                            eprintln!("Warning: public_key is not UTF-8: {:?}", err);
                            log::error!("Warning: public_key is not UTF-8: {:?}", err);
                            None
                        }
                    });

M src/tasks.rs => src/tasks.rs +1 -1
@@ 82,7 82,7 @@ impl<'a> TaskDef for DeliverToInbox<'a> {

        let res = crate::res_to_error(ctx.http_client.request(req).await?).await?;

        println!("{:?}", res);
        log::debug!("{:?}", res);

        Ok(())
    }