Add log_level config parameter and improve logging of activities

This commit is contained in:
silverpill 2021-12-21 00:14:12 +00:00
parent 900299b5e8
commit 2ab33f22ee
9 changed files with 41 additions and 22 deletions

5
Cargo.lock generated
View file

@ -868,9 +868,9 @@ dependencies = [
[[package]] [[package]]
name = "env_logger" name = "env_logger"
version = "0.8.4" version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3" checksum = "0b2cf0344971ee6c64c31be0d530793fba457d322dfec2810c453d0ef228f9c3"
dependencies = [ dependencies = [
"log", "log",
] ]
@ -1526,6 +1526,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710"
dependencies = [ dependencies = [
"cfg-if 1.0.0", "cfg-if 1.0.0",
"serde",
] ]
[[package]] [[package]]

View file

@ -34,8 +34,8 @@ dotenv = "0.15.0"
# Used to work with hexadecimal strings # Used to work with hexadecimal strings
hex = "0.4.3" hex = "0.4.3"
# Used for logging # Used for logging
log = "0.4.14" log = { version = "0.4.14", features = ["serde"] }
env_logger = { version = "0.8.4", default-features = false } env_logger = { version = "0.9.0", default-features = false }
# Used to guess media type of a file # Used to guess media type of a file
mime_guess = "2.0.3" mime_guess = "2.0.3"
mime-sniffer = "0.1.2" mime-sniffer = "0.1.2"

View file

@ -35,7 +35,6 @@ async fn send_activity(
activity_json: &str, activity_json: &str,
inbox_url: &str, inbox_url: &str,
) -> Result<(), DelivererError> { ) -> Result<(), DelivererError> {
log::info!("sending activity to {}: {}", inbox_url, activity_json);
let headers = create_http_signature( let headers = create_http_signature(
Method::POST, Method::POST,
inbox_url, inbox_url,
@ -54,7 +53,7 @@ async fn send_activity(
.body(activity_json.to_owned()); .body(activity_json.to_owned());
if instance.is_private { if instance.is_private {
log::info!( log::debug!(
"private mode: not sending activity to {}", "private mode: not sending activity to {}",
inbox_url, inbox_url,
); );
@ -94,6 +93,7 @@ async fn deliver_activity_worker(
.collect(); .collect();
inboxes.sort(); inboxes.sort();
inboxes.dedup(); inboxes.dedup();
log::info!("sending activity to {} inboxes: {}", inboxes.len(), activity_json);
for inbox_url in inboxes { for inbox_url in inboxes {
// TODO: retry on error // TODO: retry on error
if let Err(err) = send_activity( if let Err(err) = send_activity(
@ -103,8 +103,8 @@ async fn deliver_activity_worker(
&activity_json, &activity_json,
&inbox_url, &inbox_url,
).await { ).await {
log::error!("{}", err); log::error!("failed to deliver activity to {}: {}", inbox_url, err);
} };
}; };
Ok(()) Ok(())
} }
@ -115,6 +115,9 @@ pub fn deliver_activity(
activity: Activity, activity: Activity,
recipients: Vec<Actor>, recipients: Vec<Actor>,
) -> () { ) -> () {
if recipients.is_empty() {
return;
};
let instance = config.instance(); let instance = config.instance();
let sender = sender.clone(); let sender = sender.clone();
actix_rt::spawn(async move { actix_rt::spawn(async move {

View file

@ -338,9 +338,9 @@ pub async fn process_note(
pub async fn receive_activity( pub async fn receive_activity(
config: &Config, config: &Config,
db_pool: &Pool, db_pool: &Pool,
activity_raw: Value, activity_raw: &Value,
) -> Result<(), HttpError> { ) -> Result<(), HttpError> {
let activity: Activity = serde_json::from_value(activity_raw) let activity: Activity = serde_json::from_value(activity_raw.clone())
.map_err(|_| ValidationError("invalid activity"))?; .map_err(|_| ValidationError("invalid activity"))?;
let activity_type = activity.activity_type; let activity_type = activity.activity_type;
let maybe_object_type = activity.object.get("type") let maybe_object_type = activity.object.get("type")

View file

@ -92,20 +92,22 @@ async fn inbox(
request: HttpRequest, request: HttpRequest,
activity: web::Json<serde_json::Value>, activity: web::Json<serde_json::Value>,
) -> Result<HttpResponse, HttpError> { ) -> Result<HttpResponse, HttpError> {
let activity_type = activity["type"].as_str().unwrap_or("Unknown");
log::info!("received in {}: {}", request.uri().path(), activity_type);
log::debug!("received activity: {}", activity);
let signature_verified = verify_http_signature(&config, &db_pool, &request).await; let signature_verified = verify_http_signature(&config, &db_pool, &request).await;
if activity["type"].as_str() == Some(DELETE) && signature_verified.is_err() { if activity_type == DELETE && signature_verified.is_err() {
// Don't log Delete() activities if HTTP signature is not valid // Ignore Delete() activities if HTTP signature is not valid
log::info!("received in {}: Delete", request.uri().path()); log::info!("received in {}: Delete", request.uri().path());
} else { return Ok(HttpResponse::Ok().finish());
log::info!("received in {}: {}", request.uri().path(), activity);
}; };
match signature_verified { match signature_verified {
Ok(signer_id) => log::info!("activity signed by {}", signer_id), Ok(signer_id) => log::debug!("activity signed by {}", signer_id),
Err(err) => log::warn!("invalid signature: {}", err), Err(err) => log::warn!("invalid signature: {}", err),
}; };
receive_activity(&config, &db_pool, activity.into_inner()).await receive_activity(&config, &db_pool, &activity).await
.map_err(|err| { .map_err(|err| {
log::info!("failed to process activity: {}", err); log::warn!("failed to process activity: {}; {}", err, activity);
err err
})?; })?;
Ok(HttpResponse::Ok().finish()) Ok(HttpResponse::Ok().finish())

View file

@ -86,7 +86,7 @@ async fn main() {
subcmd => { subcmd => {
// Other commands require initialized app // Other commands require initialized app
let config = config::parse_config(); let config = config::parse_config();
configure_logger(); configure_logger(config.log_level);
let db_pool = create_pool(&config.database_url); let db_pool = create_pool(&config.database_url);
apply_migrations(&db_pool).await; apply_migrations(&db_pool).await;
let db_client = &mut **get_database_client(&db_pool).await.unwrap(); let db_client = &mut **get_database_client(&db_pool).await.unwrap();

View file

@ -1,6 +1,7 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::str::FromStr; use std::str::FromStr;
use log::{Level as LogLevel};
use rsa::RsaPrivateKey; use rsa::RsaPrivateKey;
use serde::{de, Deserialize, Deserializer}; use serde::{de, Deserialize, Deserializer};
use url::Url; use url::Url;
@ -61,6 +62,8 @@ fn parse_env() -> EnvConfig {
fn default_environment() -> Environment { Environment::Development } fn default_environment() -> Environment { Environment::Development }
fn default_log_level() -> LogLevel { LogLevel::Info }
#[derive(Clone, Deserialize)] #[derive(Clone, Deserialize)]
pub struct EthereumContract { pub struct EthereumContract {
pub address: String, pub address: String,
@ -84,6 +87,9 @@ pub struct Config {
pub http_host: String, pub http_host: String,
pub http_port: u32, pub http_port: u32,
#[serde(default = "default_log_level")]
pub log_level: LogLevel,
// Instance info // Instance info
instance_uri: String, instance_uri: String,
pub instance_title: String, pub instance_title: String,

View file

@ -1,7 +1,13 @@
use chrono::Local;
use std::io::Write; use std::io::Write;
pub fn configure_logger() -> () { use log::Level;
use chrono::Local;
pub fn configure_logger(base_level: Level) -> () {
let actix_level = match base_level {
Level::Info => Level::Warn,
other_level => other_level,
};
env_logger::Builder::new() env_logger::Builder::new()
.format(|buf, record| { .format(|buf, record| {
writeln!(buf, writeln!(buf,
@ -12,6 +18,7 @@ pub fn configure_logger() -> () {
record.args(), record.args(),
) )
}) })
.filter(None, log::LevelFilter::Info) .filter_level(base_level.to_level_filter())
.filter_module("actix_web::middleware::logger", actix_level.to_level_filter())
.init(); .init();
} }

View file

@ -30,7 +30,7 @@ const MAX_UPLOAD_SIZE: usize = 1024 * 1024 * 10;
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
let config = parse_config(); let config = parse_config();
configure_logger(); configure_logger(config.log_level);
let db_pool = create_pool(&config.database_url); let db_pool = create_pool(&config.database_url);
apply_migrations(&db_pool).await; apply_migrations(&db_pool).await;
if !config.media_dir().exists() { if !config.media_dir().exists() {