freebird_common/lib.rs
1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5// http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12pub mod api;
13pub mod duration;
14pub mod federation;
15pub mod logging {
16 use std::sync::Once;
17 use tracing::level_filters::LevelFilter;
18 use tracing_subscriber::{fmt, EnvFilter};
19
20 static INIT: Once = Once::new();
21
22 /// Initialize global tracing subscriber with env-driven config.
23 ///
24 /// Env:
25 /// - RUST_LOG (e.g., "info,axum=warn,tower_http=off")
26 /// - LOG_FORMAT ("plain" [default] | "json")
27 ///
28 /// `default_filter` is used if RUST_LOG is unset.
29 pub fn init(default_filter: &str) {
30 INIT.call_once(|| {
31 // Build env filter with sane fallback
32 let env_filter = EnvFilter::try_from_env("RUST_LOG")
33 .or_else(|_| EnvFilter::try_new(default_filter))
34 .unwrap_or_else(|_| {
35 EnvFilter::from_default_env().add_directive(LevelFilter::INFO.into())
36 });
37
38 let json = std::env::var("LOG_FORMAT")
39 .map(|v| v.eq_ignore_ascii_case("json"))
40 .unwrap_or(false);
41
42 if json {
43 // JSON formatter branch
44 fmt()
45 .with_env_filter(env_filter)
46 .json()
47 .with_timer(fmt::time::UtcTime::rfc_3339())
48 .with_file(true)
49 .with_line_number(true)
50 .with_target(true)
51 .with_thread_ids(true)
52 .with_thread_names(true)
53 .with_ansi(false)
54 .init();
55 } else {
56 // Plain formatter branch
57 fmt()
58 .with_env_filter(env_filter)
59 .with_timer(fmt::time::UtcTime::rfc_3339())
60 .with_file(true)
61 .with_line_number(true)
62 .with_target(true)
63 .with_thread_ids(true)
64 .with_thread_names(true)
65 .with_ansi(cfg!(unix))
66 .init();
67 }
68
69 tracing::info!("logging initialized");
70 });
71 }
72}