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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use serde::Deserialize;
use serde_json::Value;

/// Observability module configuration.
///
/// This is the top-level object consumed by `init_observability`. It configures
/// local logging, optional remote OpenTelemetry logs, and optional tracing
/// export. Log filtering is shared by all log outputs.
#[derive(Debug, Clone, Deserialize)]
pub struct ObservabilityConfig {
    /// Log output and shared filtering configuration.
    pub log: LogConfig,
    /// OpenTelemetry trace export configuration.
    pub trace: TraceConfig,
    /// OpenTelemetry metrics export configuration.
    ///
    /// Missing value disables metrics export.
    pub metrics: Option<MetricsConfig>,
}

/// Log subsystem configuration.
///
/// `filter` is intentionally shared by all outputs. Use `console`, `local`
/// and `remote` only to decide where already accepted events are written.
#[derive(Debug, Clone, Deserialize)]
pub struct LogConfig {
    /// Console and local file format. Missing value defaults to `json`.
    pub format: Option<LogFormat>,
    /// Shared ordered filter configuration.
    pub filter: LogFilterConfig,
    /// Console output configuration.
    pub console: Option<LogConsoleConfig>,
    /// Local rolling file output configuration.
    pub local: LogLocalConfig,
    /// Remote OpenTelemetry log output configuration.
    pub remote: LogRemoteConfig,
    /// Runtime reload configuration.
    pub dynamic: DynamicLogConfig,
}

/// Console and local file log format.
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LogFormat {
    /// Structured JSON output.
    Json,
    /// Compact text output.
    Compact,
    /// Full text output.
    Full,
    /// Pretty multi-line text output.
    Pretty,
}

impl Default for LogFormat {
    fn default() -> Self {
        Self::Json
    }
}

/// Console output configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct LogConsoleConfig {
    /// Enables stdout output. Missing value defaults to false.
    pub enabled: Option<bool>,
}

/// Shared log filter configuration.
///
/// Filtering uses a default level plus optional override rules. Events that do
/// not match any override are filtered by `default_level`. Events that match
/// one or more overrides use the highest-priority override, including that
/// override's level and optional field rules.
#[derive(Debug, Clone, Deserialize)]
pub struct LogFilterConfig {
    /// Default minimum level for modules that do not match any override.
    ///
    /// Supported values are `trace`, `debug`, `info`, `warn`, `error`, and
    /// `off`. For example, `info` accepts `info`, `warn`, and `error` events.
    pub default_level: String,
    /// Target/span override rules.
    ///
    /// Overrides are useful for temporarily changing a group of modules to
    /// `debug` or `trace`, or for making noisy modules stricter with `warn` or
    /// `error`. When multiple overrides match, the one with the highest
    /// `priority` wins.
    #[serde(default)]
    pub overrides: Vec<LogFilterOverrideConfig>,
}

/// Target/span-specific log filter override.
#[derive(Debug, Clone, Deserialize)]
pub struct LogFilterOverrideConfig {
    /// Human-readable rule name used for configuration diagnostics.
    ///
    /// Names must be unique within one `LogFilterConfig`. Runtime reload APIs
    /// can use this value to enable or disable a specific override.
    pub name: String,
    /// Enables this override. Missing value defaults to true.
    pub enabled: Option<bool>,
    /// Minimum level used when this override matches.
    ///
    /// Supported values are `trace`, `debug`, `info`, `warn`, `error`, and
    /// `off`. This value replaces `default_level` for matching events.
    pub level: String,
    /// Rule priority. Higher values win when multiple overrides match.
    #[serde(default)]
    pub priority: i64,
    /// Target/span fuzzy matchers that select the modules or call chains this
    /// override applies to. An empty list means the override can match all
    /// targets, so use that form only for intentional global overrides.
    #[serde(default)]
    pub fuzzy_rules: Vec<FuzzyRuleConfig>,
    /// Event field rules applied after this override matches.
    ///
    /// Multiple field rules use AND semantics. These rules do not affect
    /// modules that do not match this override.
    #[serde(default)]
    pub field_rules: Vec<FieldRuleConfig>,
}

/// Local rolling file output configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct LogLocalConfig {
    /// Enables local file output. Missing value defaults to true.
    pub enabled: Option<bool>,
    /// Directory where rolling log files are written.
    pub file_dir: String,
    /// Rolling log file name.
    pub file_name: String,
}

/// Remote OpenTelemetry log output configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct LogRemoteConfig {
    /// Enables remote OpenTelemetry logs. Missing value defaults to false.
    pub enabled: Option<bool>,
    /// Collector endpoint. `/v1/logs` is appended when not already present.
    pub endpoint: String,
    /// Optional remote-only ordered filter configuration.
    ///
    /// When this value is present, remote OpenTelemetry logs use this filter
    /// instead of the shared `[log.filter]` used by console and local file
    /// outputs. When omitted, remote logs keep the previous behavior and reuse
    /// the shared filter.
    pub filter: Option<LogFilterConfig>,
}

/// Dynamic reload configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct DynamicLogConfig {
    /// Enables runtime reload methods on the returned handle.
    pub enabled: bool,
}

/// OpenTelemetry trace export configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct TraceConfig {
    /// Enables trace export.
    pub enabled: bool,
    /// Exporter kind. Only `otlp` is currently implemented.
    pub exporter: String,
    /// Collector endpoint. `/v1/traces` is appended when not already present.
    pub endpoint: String,
    /// OpenTelemetry `service.name`.
    pub service_name: String,
    /// Optional OpenTelemetry `service.version`.
    pub service_version: Option<String>,
    /// Optional trace-only ordered filter configuration.
    ///
    /// When omitted, traces use `trace` as the default level so existing
    /// configurations continue exporting all spans and trace events.
    pub filter: Option<LogFilterConfig>,
}

/// OpenTelemetry metrics export configuration.
#[derive(Debug, Clone, Deserialize)]
pub struct MetricsConfig {
    /// Enables metrics export.
    pub enabled: bool,
    /// Exporter kind. Only `otlp` is currently implemented.
    pub exporter: String,
    /// Collector endpoint. `/v1/metrics` is appended when not already present.
    pub endpoint: String,
    /// OpenTelemetry `service.name`.
    pub service_name: String,
    /// Optional OpenTelemetry `service.version`.
    pub service_version: Option<String>,
}

/// Fuzzy rule target.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FuzzyRuleKind {
    /// Match against `metadata.target()`.
    Target,
    /// Match against active span names.
    Span,
}

/// Fuzzy match operator.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FuzzyMatchType {
    /// Exact string equality.
    Exact,
    /// Prefix match.
    Prefix,
    /// Substring match.
    Contains,
    /// `*` and `?` glob match.
    Glob,
    /// Regular expression match.
    Regex,
}

/// Deserializable fuzzy filter rule.
#[derive(Debug, Clone, Deserialize)]
pub struct FuzzyRuleConfig {
    /// Target/span selector.
    pub kind: FuzzyRuleKind,
    /// Match operation.
    pub match_type: FuzzyMatchType,
    /// Pattern used by the match operation.
    pub pattern: String,
    /// Optional level marker retained for diagnostics and future extensions.
    pub level: Option<String>,
}

/// Event field filter operation.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FieldRuleOp {
    /// Equal.
    Eq,
    /// Not equal.
    Ne,
    /// String contains.
    Contains,
    /// String starts with.
    StartsWith,
    /// String ends with.
    EndsWith,
    /// String regular expression.
    Regex,
    /// Value is in array.
    In,
    /// Field exists.
    Exists,
    /// Field does not exist.
    NotExists,
    /// Greater than.
    Gt,
    /// Greater than or equal.
    Gte,
    /// Less than.
    Lt,
    /// Less than or equal.
    Lte,
}

/// Deserializable event field rule.
#[derive(Debug, Clone, Deserialize)]
pub struct FieldRuleConfig {
    /// Event field name.
    pub field: String,
    /// Operation to apply to the field.
    pub op: FieldRuleOp,
    /// Comparison value. Not required for `exists` and `not_exists`.
    #[serde(default)]
    pub value: Value,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn toml_config_parses_filter_overrides_and_remote_filter() {
        let config: ObservabilityConfig = toml::from_str(
            r#"
            [log]
            format = "json"

            [log.filter]
            default_level = "info"

            [[log.filter.overrides]]
            name = "decoder_debug"
            enabled = true
            level = "debug"
            priority = 100

            [[log.filter.overrides.fuzzy_rules]]
            kind = "target"
            match_type = "contains"
            pattern = "decoder"

            [[log.filter.overrides.field_rules]]
            field = "id"
            op = "eq"
            value = 100

            [log.console]
            enabled = true

            [log.local]
            enabled = false
            file_dir = "logs"
            file_name = "app.log"

            [log.remote]
            enabled = true
            endpoint = "http://127.0.0.1:4318/v1/logs"

            [log.remote.filter]
            default_level = "off"

            [[log.remote.filter.overrides]]
            name = "remote_id_100"
            enabled = true
            level = "info"
            priority = 200

            [[log.remote.filter.overrides.fuzzy_rules]]
            kind = "target"
            match_type = "exact"
            pattern = "app::remote"

            [[log.remote.filter.overrides.field_rules]]
            field = "id"
            op = "eq"
            value = 100

            [log.dynamic]
            enabled = true

            [trace]
            enabled = true
            exporter = "otlp"
            endpoint = "http://127.0.0.1:4318/v1/traces"
            service_name = "pi_logger_test"
            service_version = "1.0.0"

            [trace.filter]
            default_level = "off"

            [[trace.filter.overrides]]
            name = "trace_test_on"
            enabled = true
            level = "info"
            priority = 100

            [[trace.filter.overrides.fuzzy_rules]]
            kind = "target"
            match_type = "contains"
            pattern = "trace_test"

            [metrics]
            enabled = true
            exporter = "otlp"
            endpoint = "http://127.0.0.1:4318/v1/metrics"
            service_name = "pi_logger_test"
            service_version = "1.0.0"
            "#,
        )
        .unwrap();

        assert_eq!(config.log.format, Some(LogFormat::Json));
        assert_eq!(config.log.filter.default_level, "info");
        assert_eq!(config.log.filter.overrides.len(), 1);
        assert_eq!(config.log.filter.overrides[0].name, "decoder_debug");
        assert_eq!(config.log.filter.overrides[0].enabled, Some(true));
        assert_eq!(
            config.log.filter.overrides[0].fuzzy_rules[0].kind,
            FuzzyRuleKind::Target
        );
        assert_eq!(
            config.log.filter.overrides[0].fuzzy_rules[0].match_type,
            FuzzyMatchType::Contains
        );
        assert_eq!(
            config.log.filter.overrides[0].field_rules[0].op,
            FieldRuleOp::Eq
        );

        let remote_filter = config.log.remote.filter.as_ref().unwrap();
        assert_eq!(remote_filter.default_level, "off");
        assert_eq!(remote_filter.overrides[0].name, "remote_id_100");
        assert_eq!(remote_filter.overrides[0].priority, 200);

        assert_eq!(config.log.console.unwrap().enabled, Some(true));
        assert_eq!(config.log.local.enabled, Some(false));
        assert_eq!(config.log.remote.enabled, Some(true));
        assert!(config.log.dynamic.enabled);
        assert!(config.trace.enabled);
        assert_eq!(config.trace.service_name, "pi_logger_test");
        assert_eq!(config.trace.service_version.as_deref(), Some("1.0.0"));
        assert_eq!(
            config.trace.filter.as_ref().unwrap().overrides[0].name,
            "trace_test_on"
        );
        let metrics = config.metrics.as_ref().unwrap();
        assert!(metrics.enabled);
        assert_eq!(metrics.exporter, "otlp");
        assert_eq!(metrics.service_name, "pi_logger_test");
        assert_eq!(metrics.service_version.as_deref(), Some("1.0.0"));
    }

    #[test]
    fn toml_override_defaults_empty_rule_lists_and_priority() {
        let config: LogFilterConfig = toml::from_str(
            r#"
            default_level = "warn"

            [[overrides]]
            name = "global_info"
            level = "info"
            "#,
        )
        .unwrap();

        assert_eq!(config.default_level, "warn");
        assert_eq!(config.overrides.len(), 1);
        assert_eq!(config.overrides[0].enabled, None);
        assert_eq!(config.overrides[0].priority, 0);
        assert!(config.overrides[0].fuzzy_rules.is_empty());
        assert!(config.overrides[0].field_rules.is_empty());
    }
}