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
//! A [`tracing`] filter for enabling individual [spans] and [events] by line
//! number.
//!
//! [`tracing`] is a framework for instrumenting Rust programs to collect
//! scoped, structured, and async-aware diagnostics. The [`tracing-subscriber`]
//! crate's [`EnvFilter`] type provides a mechanism for controlling what
//! `tracing` [spans] and [events] are collected by matching their targets,
//! verbosity levels, and fields. In some cases, though, it can be useful to
//! toggle on or off individual spans or events with a higher level of
//! granularity. Therefore, this crate provides a filtering [`Layer`] that
//! enables individual spans and events based on their module path/file path and
//! line numbers.
//!
//! Since the implementation of this filter is rather simple, the source code of
//! this crate is also useful as an example to `tracing` users who want to
//! implement their own filtering logic.
//!
//! # Usage
//!
//! First, add this to your Cargo.toml:
//!
//! ```toml
//! tracing-line-filter = "0.1"
//! ```
//!
//! ## Examples
//!
//! Enabling events by line:
//!
//! ```rust
//! use tracing_line_filter::LineFilter;
//! mod some_module {
//!     pub fn do_stuff() {
//!         tracing::info!("i'm doing stuff");
//!         tracing::debug!("i'm also doing stuff!");
//!     }
//! }
//!
//! fn main() {
//!     use tracing_subscriber::prelude::*;
//!
//!     let mut filter = LineFilter::default();
//!     filter
//!         .enable_by_mod("my_crate::some_module", 6)
//!         .enable_by_mod("my_crate", 25)
//!         .enable_by_mod("my_crate", 27);
//!
//!     tracing_subscriber::registry()
//!         .with(tracing_subscriber::fmt::layer().pretty())
//!         .with(filter)
//!         .init();
//!
//!     tracing::info!("i'm not enabled");
//!     tracing::debug!("i'm enabled!");
//!     some_module::do_stuff();
//!     tracing::trace!("hi!");
//! }
//! ```
//!
//! Chaining a [`LineFilter`] with a `tracing_subscriber` [`EnvFilter`]:
//!
//! ```rust
//! use tracing_line_filter::LineFilter;
//! use tracing_subscriber::EnvFilter;
//!
//! mod some_module {
//!     pub fn do_stuff() {
//!         tracing::info!("i'm doing stuff");
//!         tracing::debug!("i'm also doing stuff!");
//!         // This won't be enabled, because it's at the TRACE level, and the
//!         // `EnvFilter` only enables up to the DEBUG level.
//!         tracing::trace!("doing very verbose stuff");
//!     }
//! }
//!
//! fn main() {
//!     use tracing_subscriber::prelude::*;
//!
//!     let mut filter = LineFilter::default();
//!     filter
//!         .enable_by_mod("with_env_filter", 30)
//!         .enable_by_mod("with_env_filter", 33)
//!         // use an `EnvFilter` that enables DEBUG and lower in `some_module`,
//!         // and everything at the ERROR level.
//!         .with_env_filter(EnvFilter::new("error,with_env_filter::some_module=debug"));
//!
//!     tracing_subscriber::registry()
//!         .with(tracing_subscriber::fmt::layer().pretty())
//!         .with(filter)
//!         .init();
//!
//!     tracing::info!("i'm not enabled");
//!     tracing::debug!("i'm enabled!!");
//!     some_module::do_stuff();
//!     tracing::trace!("hi!");
//!
//!     // This will be enabled by the `EnvFilter`.
//!     tracing::error!("an error!");
//! }
//! ```
//!
//! [`tracing`]: https://docs.rs/tracing
//! [spans]: https://docs.rs/tracing/latest/tracing/#spans
//! [events]: https://docs.rs/tracing/latest/tracing/#events
//! [`tracing-subscriber`]: https://docs.rs/tracing-subscriber
//! [`EnvFilter`]: tracing_subscriber::EnvFilter
//! [`Layer`]: tracing_subscriber::Layer

use std::borrow::Cow;
use std::collections::HashSet;
use std::fmt;
use std::path::{Path, PathBuf};
use tracing_core::{subscriber::Interest, Metadata, Subscriber};
use tracing_subscriber::{
    filter::EnvFilter,
    layer::{self, Layer},
};

/// A filter for enabling spans and events by file/module path and line number.
#[derive(Debug, Default)]
pub struct LineFilter {
    by_module: HashSet<(Cow<'static, str>, u32)>,
    by_file: HashSet<(Cow<'static, str>, u32)>,
    env: Option<EnvFilter>,
}

/// Indicates a file path was invalid for use in a `LineFilter`.
#[derive(Debug)]
pub struct BadPath {
    path: PathBuf,
    message: &'static str,
}

impl LineFilter {
    /// Returns a new `LineFilter`.
    ///
    /// By default, no spans and events are enabled.
    pub fn new() -> Self {
        Self::default()
    }

    /// Composes `self` with an [`EnvFilter`] that will be checked for spans and
    /// events if they are not in the lists of enabled `(module, line)` and
    /// `(file, line)` pairs.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_subscriber::EnvFilter;
    /// use tracing_line_filter::LineFilter;
    ///
    /// let mut filter = LineFilter::default();
    /// filter
    ///     .enable_by_mod("my_crate", 28)
    ///     .enable_by_mod("my_crate::my_module", 16)
    ///     // use an ``EnvFilter` that enables DEBUG and lower in `some_module`, and
    ///     // all ERROR spans or events, regardless of location.
    ///     .with_env_filter(EnvFilter::new("error,my_crate::some_other_module=debug"));
    /// ```
    pub fn with_env_filter(&mut self, env: EnvFilter) -> &mut Self {
        self.env = Some(env);
        self
    }

    /// Enable a span or event in the Rust module `module` on line `line`.
    ///
    /// # Notes
    ///
    /// * Module paths should include the name of the crate. For
    ///   example, the module `my_module` in `my_crate` would have path
    ///  `my_crate::my_module`.
    /// * If no span or event exists at the specified location, or if the module
    ///   path does not exist, this will silently do nothing.
    /// * Line numbers are relative to the start of the *file*, not to the start
    ///   of the module. If a module does not have its own file (i.e., it's
    ///   defined like `mod my_module { ... }`), the line number is relative to
    ///   the containing file.
    ///
    /// # Examples
    ///
    /// Enabling an event:
    /// ```
    /// use tracing_line_filter::LineFilter;
    ///
    /// mod my_module {
    ///     pub fn do_stuff() {
    ///         tracing::info!("doing stuff!")
    ///         // ...
    ///     }
    /// }
    ///
    /// // Build a line filter to enable the event in `do_stuff`.
    /// let mut filter = LineFilter::default();
    /// filter.enable_by_mod("my_crate::my_module", 5);
    ///
    /// // Build a subscriber and enable that filter.
    /// use tracing_subscriber::prelude::*;
    ///
    /// tracing_subscriber::registry()
    ///     .with(tracing_subscriber::fmt::layer())
    ///     .with(filter)
    ///     .init();
    ///
    /// // Now, the event is enabled!
    /// my_module::do_stuff();
    /// ```
    ///
    /// The [`std::module_path!()`] macro can be used to enable an event in the
    /// current module:
    /// ```
    /// use tracing_line_filter::LineFilter;
    ///
    /// pub fn do_stuff() {
    ///     tracing::info!("doing stuff!")
    ///     // ...
    /// }
    ///
    /// let mut filter = LineFilter::default();
    /// filter.enable_by_mod(module_path!(), 4);
    ///
    ///  // ...
    /// ```
    pub fn enable_by_mod(&mut self, module: impl Into<Cow<'static, str>>, line: u32) -> &mut Self {
        self.by_module.insert((module.into(), line));
        self
    }

    /// Enable a span or event in the file `file` on line `line`.
    ///
    /// # Notes
    ///
    /// These file paths must match the file paths emitted by the
    /// [`std::file!()`] macro. In particular:
    ///
    /// * Paths must be absolute.
    /// * Paths must be Rust source code files.
    /// * Paths must be valid UTF-8.
    ///
    /// This method validates paths and returns an error if the path is not
    /// valid for use in a `LineFilter`.
    ///
    /// Since these paths are absolute, files in Cargo dependencies will include
    /// their full path in the local Cargo registry. For example:
    /// ```text
    /// /home/eliza/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.0.0/src/util/trace.rs
    /// ```
    ///
    /// Therefore, it can be challenging for humans to determine the correct
    /// path to a file, especially when it is in a dependency. For this reason,
    /// it's likely best to prefer Rust module paths rather than file paths when
    /// accepting input from users directly. Enabling events and spans by file
    /// paths is primarily intended for use by automated tools.
    pub fn enable_by_file(
        &mut self,
        file: impl AsRef<Path>,
        line: u32,
    ) -> Result<&mut Self, BadPath> {
        let file = file.as_ref();
        if !file.is_absolute() {
            return Err(BadPath::new(file, "file paths must be absolute"));
        }

        if file.extension().and_then(std::ffi::OsStr::to_str) != Some("rs") {
            return Err(BadPath::new(file, "files must be Rust source code files"));
        }

        let file = file
            .to_str()
            .ok_or_else(|| BadPath::new(file, "file paths must be valid utf-8"))?
            .to_owned();

        self.by_file.insert((Cow::Owned(file), line));
        Ok(self)
    }

    /// Enable a set of spans or events by module path.
    ///
    /// This is equivalent to repeatedly calling [`enable_by_mod`].
    ///
    ///
    /// # Examples
    /// ```
    /// use tracing_line_filter::LineFilter;
    ///
    /// mod foo {
    ///     pub fn do_stuff() {
    ///         tracing::info!("doing stuff!")
    ///         // ...
    ///     }
    /// }
    ///
    /// mod bar {
    ///     pub fn do_other_stuff() {
    ///         tracing::debug!("doing some different stuff...")
    ///         // ...
    ///     }
    /// }
    ///
    /// // Build a line filter to enable the events in `do_stuff`
    /// // and `do_other_stuff`.
    /// let mut filter = LineFilter::default();
    /// filter.with_modules(vec![
    ///    ("my_crate::foo", 5),
    ///    ("my_crate::bar", 12)
    /// ]);
    ///
    /// // Build a subscriber and enable that filter.
    /// use tracing_subscriber::prelude::*;
    ///
    /// tracing_subscriber::registry()
    ///     .with(tracing_subscriber::fmt::layer())
    ///     .with(filter)
    ///     .init();
    ///
    /// // Now, the events are enabled!
    /// foo::do_stuff();
    /// bar::do_other_stuff();
    /// ```
    pub fn with_modules<I>(&mut self, modules: impl IntoIterator<Item = (I, u32)>) -> &mut Self
    where
        I: Into<Cow<'static, str>>,
    {
        let modules = modules
            .into_iter()
            .map(|(module, line)| (module.into(), line));
        self.by_module.extend(modules);
        self
    }

    /// Enable a set of spans or events by file path.
    ///
    /// This is equivalent to repeatedly calling [`enable_by_file`], and follows
    /// the same path validation rules as that method. See the documentation for
    /// [`enable_by_file`] for details.
    pub fn with_files<I>(
        &mut self,
        files: impl IntoIterator<Item = (I, u32)>,
    ) -> Result<&mut Self, BadPath>
    where
        I: AsRef<Path>,
    {
        for (file, line) in files {
            self.enable_by_file(file, line)?;
        }
        Ok(self)
    }

    fn contains(&self, metadata: &Metadata<'_>) -> bool {
        if let Some(line) = metadata.line() {
            let module = metadata.module_path().unwrap_or_else(|| metadata.target());
            let location = (Cow::Borrowed(module), line);
            if self.by_module.contains(&location) {
                return true;
            }

            if let Some(file) = metadata.file() {
                let location = (Cow::Borrowed(file), line);
                if self.by_file.contains(&location) {
                    return true;
                }
            }
        }

        false
    }
}

impl<S: Subscriber> Layer<S> for LineFilter
where
    EnvFilter: Layer<S>,
{
    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
        if self.contains(metadata) {
            return Interest::always();
        }

        self.env
            .as_ref()
            .map(|env| env.register_callsite(metadata))
            .unwrap_or_else(Interest::never)
    }

    fn enabled(&self, metadata: &Metadata<'_>, cx: layer::Context<'_, S>) -> bool {
        if self.contains(metadata) {
            return true;
        }

        self.env
            .as_ref()
            .map(|env| env.enabled(metadata, cx))
            .unwrap_or(false)
    }
}

// === impl BadPath ===

impl fmt::Display for BadPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid path '{}': {}",
            self.path.display(),
            self.message
        )
    }
}

impl std::error::Error for BadPath {}

impl BadPath {
    fn new(path: &Path, message: &'static str) -> Self {
        Self {
            path: path.to_path_buf(),
            message,
        }
    }
}