|
| 1 | +// Copyright 2021 Datafuse Labs |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +/// A mapping between a module path prefix and a short log label. |
| 16 | +#[derive(Debug)] |
| 17 | +pub struct ModuleTag { |
| 18 | + pub prefix: &'static str, |
| 19 | + pub label: &'static str, |
| 20 | +} |
| 21 | + |
| 22 | +inventory::collect!(ModuleTag); |
| 23 | + |
| 24 | +/// Resolve the best matching label for the provided module path. |
| 25 | +pub fn label_for_module<'a>(full_name: &'a str) -> &'a str { |
| 26 | + inventory::iter::<ModuleTag> |
| 27 | + .into_iter() |
| 28 | + .filter_map(|entry| { |
| 29 | + full_name |
| 30 | + .starts_with(entry.prefix) |
| 31 | + .then_some((entry.prefix.len(), entry.label)) |
| 32 | + }) |
| 33 | + .max_by_key(|(len, _)| *len) |
| 34 | + .map(|(_, label)| label) |
| 35 | + .unwrap_or(full_name) |
| 36 | +} |
| 37 | + |
| 38 | +#[macro_export] |
| 39 | +macro_rules! register_module_tag { |
| 40 | + ($label:expr $(,)?) => { |
| 41 | + inventory::submit! { |
| 42 | + #![crate = databend_common_tracing] |
| 43 | + |
| 44 | + databend_common_tracing::module_tag::ModuleTag { |
| 45 | + prefix: module_path!(), |
| 46 | + label: $label, |
| 47 | + } |
| 48 | + } |
| 49 | + }; |
| 50 | + ($label:expr, $prefix:expr $(,)?) => { |
| 51 | + inventory::submit! { |
| 52 | + #![crate = databend_common_tracing] |
| 53 | + |
| 54 | + databend_common_tracing::module_tag::ModuleTag { |
| 55 | + prefix: $prefix, |
| 56 | + label: $label, |
| 57 | + } |
| 58 | + } |
| 59 | + }; |
| 60 | +} |
| 61 | + |
| 62 | +#[cfg(test)] |
| 63 | +mod tests { |
| 64 | + use super::*; |
| 65 | + |
| 66 | + inventory::submit! { |
| 67 | + ModuleTag { |
| 68 | + prefix: "module::submodule", |
| 69 | + label: "[SUB]", |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + inventory::submit! { |
| 74 | + ModuleTag { |
| 75 | + prefix: "module", |
| 76 | + label: "[MODULE]", |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + #[test] |
| 81 | + fn chooses_longest_prefix() { |
| 82 | + assert_eq!(label_for_module("module::submodule::leaf"), "[SUB]"); |
| 83 | + } |
| 84 | + |
| 85 | + #[test] |
| 86 | + fn falls_back_to_full_module_name() { |
| 87 | + assert_eq!(label_for_module("unknown::module"), "unknown::module"); |
| 88 | + } |
| 89 | +} |
0 commit comments