-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathlogging.rs
More file actions
209 lines (181 loc) · 7.14 KB
/
Copy pathlogging.rs
File metadata and controls
209 lines (181 loc) · 7.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use anyhow::Result;
use tracing::Level;
use tracing_appender::rolling;
use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};
/// Output format for log messages.
#[derive(Debug, Clone, PartialEq)]
pub enum LogFormat {
/// Human-readable coloured output (default for terminals)
Human,
/// Newline-delimited JSON (useful for CI/CD and log aggregators)
Json,
}
/// Configuration for the logging subsystem.
pub struct LogConfig {
/// Minimum log level to emit (default: `warn` for normal use, `debug` with `RUST_LOG`)
pub level: Level,
/// Output format
pub format: LogFormat,
/// Optional directory to write rolling log files into
pub log_dir: Option<std::path::PathBuf>,
/// Log file prefix (e.g. "starforge")
pub file_prefix: String,
}
impl Default for LogConfig {
fn default() -> Self {
Self {
level: Level::WARN,
format: LogFormat::Human,
log_dir: None,
file_prefix: "starforge".to_string(),
}
}
}
/// Initialise the global tracing subscriber.
///
/// Call this once at the start of `main()` before any commands run.
/// The `RUST_LOG` environment variable overrides `config.level` when set.
///
/// # Examples
/// ```no_run
/// use starforge::utils::logging::{LogConfig, LogFormat, init};
/// init(LogConfig { format: LogFormat::Json, ..Default::default() }).unwrap();
/// ```
pub fn init(config: LogConfig) -> Result<()> {
// RUST_LOG takes precedence; fall back to the configured level.
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(config.level.as_str()));
match (config.format, config.log_dir) {
// ── JSON + file rotation ──────────────────────────────────────────
(LogFormat::Json, Some(dir)) => {
let file_appender = rolling::daily(&dir, &config.file_prefix);
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
let file_layer = fmt::layer()
.json()
.with_writer(non_blocking)
.with_filter(env_filter.clone());
let stderr_layer = fmt::layer()
.json()
.with_writer(std::io::stderr)
.with_filter(env_filter);
tracing_subscriber::registry()
.with(file_layer)
.with(stderr_layer)
.try_init()
.map_err(|e| anyhow::anyhow!("Failed to init logger: {}", e))?;
}
// ── JSON, stderr only ─────────────────────────────────────────────
(LogFormat::Json, None) => {
let layer = fmt::layer()
.json()
.with_writer(std::io::stderr)
.with_filter(env_filter);
tracing_subscriber::registry()
.with(layer)
.try_init()
.map_err(|e| anyhow::anyhow!("Failed to init logger: {}", e))?;
}
// ── Human + file rotation ─────────────────────────────────────────
(LogFormat::Human, Some(dir)) => {
let file_appender = rolling::daily(&dir, &config.file_prefix);
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
let file_layer = fmt::layer()
.with_ansi(false)
.with_writer(non_blocking)
.with_filter(env_filter.clone());
let stderr_layer = fmt::layer()
.with_writer(std::io::stderr)
.with_filter(env_filter);
tracing_subscriber::registry()
.with(file_layer)
.with(stderr_layer)
.try_init()
.map_err(|e| anyhow::anyhow!("Failed to init logger: {}", e))?;
}
// ── Human, stderr only (default) ──────────────────────────────────
(LogFormat::Human, None) => {
let layer = fmt::layer()
.with_writer(std::io::stderr)
.with_filter(env_filter);
tracing_subscriber::registry()
.with(layer)
.try_init()
.map_err(|e| anyhow::anyhow!("Failed to init logger: {}", e))?;
}
}
Ok(())
}
/// Redact a public Stellar key unless the current log level is debug or trace.
///
/// Public keys are safe to display to users, but log streams should avoid
/// including raw account IDs in info-level logs unless the log level is explicitly
/// opted into debug.
pub fn redact_public_key(public_key: &str, level: Level) -> String {
if matches!(level, Level::DEBUG | Level::TRACE) {
public_key.to_string()
} else if public_key.len() > 8 {
let prefix = &public_key[..4];
let suffix = &public_key[public_key.len().saturating_sub(4)..];
format!("{}...{}", prefix, suffix)
} else {
"[REDACTED]".to_string()
}
}
/// Always redact secret values when they are written to logs.
///
/// Secret keys and passphrases should never appear in info-level or debug-level
/// logs.
pub fn redact_secret_value(_value: &str) -> &'static str {
"[REDACTED]"
}
/// Always redact signed XDR payloads when they are written to logs.
///
/// XDR envelopes containing signatures are secret and must not be emitted at
/// info level.
pub fn redact_signed_xdr(_xdr: &str) -> &'static str {
"[REDACTED]"
}
/// Build a `LogConfig` from CLI flags / environment.
///
/// - `--log-format json` → `LogFormat::Json`
/// - `--log-dir <path>` → file rotation into that directory
/// - `RUST_LOG` → overrides level at the filter level
pub fn config_from_env(format: Option<&str>, log_dir: Option<std::path::PathBuf>) -> LogConfig {
let format = match format {
Some("json") => LogFormat::Json,
_ => LogFormat::Human,
};
LogConfig {
format,
log_dir,
..Default::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use tracing::Level;
#[test]
fn redact_public_key_hides_value_at_info_level() {
let key = "GDRXMZDQW34QHX6F5U6FFWJZZZDQ4KYWJO65HS4CUT62X7Y7RXYWXE4T";
let redacted = redact_public_key(key, Level::INFO);
assert!(redacted.starts_with("GDRX"));
assert!(redacted.ends_with("4T"));
assert!(redacted.contains("..."));
assert_ne!(redacted, key);
}
#[test]
fn redact_public_key_returns_full_value_at_debug_level() {
let key = "GDRXMZDQW34QHX6F5U6FFWJZZZDQ4KYWJO65HS4CUT62X7Y7RXYWXE4T";
assert_eq!(redact_public_key(key, Level::DEBUG), key);
assert_eq!(redact_public_key(key, Level::TRACE), key);
}
#[test]
fn redact_secret_value_always_redacts() {
assert_eq!(redact_secret_value("super-secret"), "[REDACTED]");
}
#[test]
fn redact_signed_xdr_always_redacts() {
assert_eq!(redact_signed_xdr("signed-xdr-payload"), "[REDACTED]");
}
}