Skip to content

Commit 6a999bb

Browse files
committed
Add logging utils to common crate
1 parent 014eaee commit 6a999bb

File tree

6 files changed

+90
-58
lines changed

6 files changed

+90
-58
lines changed

Cargo.lock

Lines changed: 5 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

apps/labrinth/Cargo.toml

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ clap = { workspace = true, features = ["derive"] }
3737
clickhouse = { workspace = true, features = ["time", "uuid"] }
3838
color-eyre = { workspace = true }
3939
color-thief = { workspace = true }
40-
console-subscriber = { workspace = true }
4140
const_format = { workspace = true }
4241
dashmap = { workspace = true }
4342
deadpool-redis.workspace = true
@@ -72,6 +71,7 @@ json-patch = { workspace = true }
7271
lettre = { workspace = true }
7372
meilisearch-sdk = { workspace = true, features = ["reqwest"] }
7473
modrinth-maxmind = { workspace = true }
74+
modrinth-util = { workspace = true }
7575
muralpay = { workspace = true, features = ["utoipa"] }
7676
murmur2 = { workspace = true }
7777
paste = { workspace = true }
@@ -120,8 +120,6 @@ tokio-stream = { workspace = true }
120120
totp-rs = { workspace = true, features = ["gen_secret"] }
121121
tracing = { workspace = true }
122122
tracing-actix-web = { workspace = true }
123-
tracing-ecs = { workspace = true }
124-
tracing-subscriber = { workspace = true }
125123
url = { workspace = true }
126124
urlencoding = { workspace = true }
127125
utoipa = { workspace = true }

apps/labrinth/src/main.rs

Lines changed: 1 addition & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,8 @@ use labrinth::{check_env_vars, clickhouse, database, file_hosting};
1919
use std::ffi::CStr;
2020
use std::str::FromStr;
2121
use std::sync::Arc;
22-
use tracing::level_filters::LevelFilter;
2322
use tracing::{Instrument, error, info, info_span};
2423
use tracing_actix_web::TracingLogger;
25-
use tracing_ecs::ECSLayerBuilder;
26-
use tracing_subscriber::EnvFilter;
27-
use tracing_subscriber::layer::SubscriberExt;
28-
use tracing_subscriber::util::SubscriberInitExt;
2924
use utoipa::OpenApi;
3025
use utoipa_actix_web::AppExt;
3126
use utoipa_swagger_ui::SwaggerUi;
@@ -59,59 +54,13 @@ struct Args {
5954
run_background_task: Option<BackgroundTask>,
6055
}
6156

62-
#[derive(Debug, Clone, Default, PartialEq, Eq)]
63-
enum OutputFormat {
64-
#[default]
65-
Human,
66-
Json,
67-
}
68-
69-
impl FromStr for OutputFormat {
70-
type Err = ();
71-
72-
fn from_str(s: &str) -> Result<Self, Self::Err> {
73-
match s {
74-
"human" => Ok(Self::Human),
75-
"json" => Ok(Self::Json),
76-
_ => Err(()),
77-
}
78-
}
79-
}
80-
8157
#[actix_rt::main]
8258
async fn main() -> std::io::Result<()> {
8359
let args = Args::parse();
8460

8561
color_eyre::install().expect("failed to install `color-eyre`");
8662
dotenvy::dotenv().ok();
87-
let console_layer = console_subscriber::spawn();
88-
let env_filter = EnvFilter::builder()
89-
.with_default_directive(LevelFilter::INFO.into())
90-
.from_env_lossy();
91-
92-
let output_format =
93-
dotenvy::var("LABRINTH_FORMAT").map_or(OutputFormat::Human, |format| {
94-
format
95-
.parse::<OutputFormat>()
96-
.unwrap_or_else(|_| panic!("invalid output format '{format}'"))
97-
});
98-
99-
match output_format {
100-
OutputFormat::Human => {
101-
tracing_subscriber::registry()
102-
.with(console_layer)
103-
.with(env_filter)
104-
.with(tracing_subscriber::fmt::layer())
105-
.init();
106-
}
107-
OutputFormat::Json => {
108-
tracing_subscriber::registry()
109-
.with(console_layer)
110-
.with(env_filter)
111-
.with(ECSLayerBuilder::default().stdout())
112-
.init();
113-
}
114-
}
63+
modrinth_util::log::init().expect("failed to initialize logging");
11564

11665
if check_env_vars() {
11766
error!("Some environment variables are missing!");

packages/modrinth-util/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,14 @@ repository.workspace = true
66

77
[dependencies]
88
actix-web = { workspace = true }
9+
console-subscriber = { workspace = true }
910
derive_more = { workspace = true, features = ["display", "error", "from"] }
1011
dotenvy = { workspace = true }
1112
eyre = { workspace = true }
1213
serde = { workspace = true, features = ["derive"] }
14+
tracing = { workspace = true }
15+
tracing-ecs = { workspace = true }
16+
tracing-subscriber = { workspace = true }
1317

1418
[lints]
1519
workspace = true

packages/modrinth-util/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#![doc = include_str!("../README.md")]
22

33
mod error;
4+
pub mod log;
5+
46
pub use error::*;
57

68
use eyre::{Result, eyre};

packages/modrinth-util/src/log.rs

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
//! Service logging utilities.
2+
3+
use std::str::FromStr;
4+
5+
use eyre::{Result, eyre};
6+
use tracing::level_filters::LevelFilter;
7+
use tracing_ecs::ECSLayerBuilder;
8+
use tracing_subscriber::{
9+
EnvFilter, layer::SubscriberExt, util::SubscriberInitExt,
10+
};
11+
12+
use crate::{Context, env_var};
13+
14+
/// How this service will output logs to the terminal output.
15+
///
16+
/// See [`init`].
17+
#[derive(Debug, Clone, Default, PartialEq, Eq)]
18+
enum OutputFormat {
19+
/// Human-readable format using [`tracing_subscriber::fmt::layer`].
20+
#[default]
21+
Human,
22+
/// Elastic Common Schema JSON output using [`ECSLayerBuilder`].
23+
Json,
24+
}
25+
26+
impl FromStr for OutputFormat {
27+
type Err = ();
28+
29+
fn from_str(s: &str) -> Result<Self, Self::Err> {
30+
match s {
31+
"human" => Ok(Self::Human),
32+
"json" => Ok(Self::Json),
33+
_ => Err(()),
34+
}
35+
}
36+
}
37+
38+
/// Key for the environment variable that determines the output format.
39+
pub const OUTPUT_FORMAT_ENV_VAR: &str = "MODRINTH_OUTPUT_FORMAT";
40+
41+
/// Initializes logging for Modrinth services.
42+
///
43+
/// This uses [`OUTPUT_FORMAT_ENV_VAR`] to determine the [`OutputFormat`] to
44+
/// use - see that type for details of each possible format.
45+
///
46+
/// # Errors
47+
///
48+
/// Errors if logging could not be initialized.
49+
pub fn init() -> Result<()> {
50+
let output_format = match env_var(OUTPUT_FORMAT_ENV_VAR) {
51+
Ok(format) => format
52+
.parse::<OutputFormat>()
53+
.map_err(|_| eyre!("invalid output format '{format}'"))?,
54+
Err(_) => OutputFormat::Human,
55+
};
56+
57+
let console_layer = console_subscriber::spawn();
58+
let env_filter = EnvFilter::builder()
59+
.with_default_directive(LevelFilter::INFO.into())
60+
.from_env_lossy();
61+
62+
let result = match output_format {
63+
OutputFormat::Human => tracing_subscriber::registry()
64+
.with(console_layer)
65+
.with(env_filter)
66+
.with(tracing_subscriber::fmt::layer())
67+
.try_init(),
68+
OutputFormat::Json => tracing_subscriber::registry()
69+
.with(console_layer)
70+
.with(env_filter)
71+
.with(ECSLayerBuilder::default().stdout())
72+
.try_init(),
73+
};
74+
result.wrap_err("failed to initialize tracing registry")?;
75+
76+
Ok(())
77+
}

0 commit comments

Comments
 (0)