|
| 1 | +""" |
| 2 | + EarlyFilteredLogger(filter, logger) |
| 3 | +
|
| 4 | +Wraps `logger` in an filter that runs before the log message is created. |
| 5 | +
|
| 6 | +For contrast see the [`ActiveFilteredLogger`](@ref) which has full control, |
| 7 | +but runs after the log message content is computed. |
| 8 | +In most circumstances this is fine, but if your log messages are expensive |
| 9 | +to create (e.g. they include summary statistics), then the `EarlyFilteredLogger` |
| 10 | +is going to be better. |
| 11 | +
|
| 12 | +The `filter` should be a function that returns a boolean. |
| 13 | +`true` if the message should be logged and `false` if not. |
| 14 | +As input it will be given a named tuple with the following fields: |
| 15 | +`(level, _module, group, id)` |
| 16 | +See `?LoggingExtra.shouldlog_args` for more information on what each is. |
| 17 | +""" |
| 18 | +struct EarlyFilteredLogger{T <: AbstractLogger, F} <: AbstractLogger |
| 19 | + filter::F |
| 20 | + logger::T |
| 21 | +end |
| 22 | + |
| 23 | + |
| 24 | +function handle_message(logger::EarlyFilteredLogger, args...; kwargs...) |
| 25 | + if comp_handle_message_check(logger.logger, args...; kwargs...) |
| 26 | + return handle_message(logger.logger, args...; kwargs...) |
| 27 | + end |
| 28 | +end |
| 29 | + |
| 30 | +function shouldlog(logger::EarlyFilteredLogger, args...) |
| 31 | + log_args = shouldlog_args(args...) |
| 32 | + comp_shouldlog(logger.logger, args...) && logger.filter(log_args) |
| 33 | +end |
| 34 | + |
| 35 | +min_enabled_level(logger::EarlyFilteredLogger) = min_enabled_level(logger.logger) |
| 36 | +catch_exceptions(logger::EarlyFilteredLogger) = catch_exceptions(logger.logger) |
| 37 | + |
| 38 | +""" |
| 39 | + shouldlog_args |
| 40 | +
|
| 41 | +This returns a NamedTuple containing all the arguments the logger gives |
| 42 | +to `shouldlog` |
| 43 | +It is passed to the early logger filter. |
| 44 | +These argument come from the logging macro (@info`, `@warn` etc). |
| 45 | +
|
| 46 | + * `level::LogLevel` Warn, Info, etc, |
| 47 | + * `_module::Module` can be used to specify a different originating module from |
| 48 | + the source location of the message. |
| 49 | + * `group::Symbol` can be used to override the message group (this is |
| 50 | + normally derived from the base name of the source file). |
| 51 | + * `id::Symbol` can be used to override the automatically generated unique |
| 52 | + message identifier. This is useful if you need to very closely associate |
| 53 | + messages generated on different source lines. |
| 54 | +""" |
| 55 | +function shouldlog_args(fieldvals...) |
| 56 | + fieldnames = (:level, :_module, :group, :id) |
| 57 | + return NamedTuple{fieldnames, typeof(fieldvals)}(fieldvals) |
| 58 | +end |
0 commit comments