Skip to content

Logging

pyclifer ships a Rich-enhanced logging system with a custom TRACE level (5), automatic secrets masking, and rotating file handler support.

get_logger

Main factory. Returns a logger pre-configured with Rich formatting.

pyclifer.get_logger(name=None)

Factory function for creating loggers with Rich capabilities.

This function uses the global configuration system to provide loggers that automatically benefit from Rich enhancements.

Parameters:

Name Type Description Default
name str

Logger name (optional).

None

Returns:

Type Description
SupportsTraceLogger

Logger configured with Rich capabilities.

Source code in src/pyclifer/core/log/__init__.py
def get_logger(name: str = None) -> SupportsTraceLogger:
    """Factory function for creating loggers with Rich capabilities.

    This function uses the global configuration system to provide
    loggers that automatically benefit from Rich enhancements.

    Args:
        name: Logger name (optional).

    Returns:
        Logger configured with Rich capabilities.
    """
    return get_configured_logger(name)

get_configured_logger

Returns a logger with full configuration applied (handlers, level, masker).

pyclifer.get_configured_logger(name=None)

Get a logger that automatically benefits from global Rich configuration.

This function simply retrieves a standard logger that automatically inherits the global Rich configuration.

Parameters:

Name Type Description Default
name str | None

Logger name (optional).

None

Returns:

Type Description
SupportsTraceLogger

Logger automatically configured with Rich capabilities.

Source code in src/pyclifer/core/log/config.py
def get_configured_logger(name: str | None = None) -> SupportsTraceLogger:
    """Get a logger that automatically benefits from global Rich configuration.

    This function simply retrieves a standard logger that automatically
    inherits the global Rich configuration.

    Args:
        name: Logger name (optional).

    Returns:
        Logger automatically configured with Rich capabilities.
    """
    # Lazy: pyclifer/__init__.py imports this module. The name is read when the function runs,
    # so it does not depend on the order of the imports in that file.
    from pyclifer import __app_name__

    return logging.getLogger(name or __app_name__)  # type: ignore[return-value]

configure_rich_logging

Low-level setup function. Called internally by get_configured_logger.

pyclifer.configure_rich_logging(use_rich=True, rich_tracebacks=True, enable_secrets_filter=True, sensitive_fields=None, mask_free_text=False, force_reconfigure=False, replace_root_handlers=False)

Configure the Rich logging system once and centrally.

This function sets up the entire logging system in one place: - Global configuration via basicConfig - Adds trace() method to all Python loggers - Prevents multiple configurations with built-in checks

Parameters:

Name Type Description Default
use_rich bool

Enable Rich logging capabilities.

True
rich_tracebacks bool

Enable Rich tracebacks for exceptions.

True
enable_secrets_filter bool

Enable automatic secrets filtering.

True
sensitive_fields list[str] | None

Additional field names to mask on top of the defaults. Merged into SecretsMasker.DEFAULT_FIELDS — does not replace them.

None
mask_free_text bool

Also mask key=value pairs written inside the text of a message.

False
force_reconfigure bool

Force reconfiguration even if already configured.

False
replace_root_handlers bool

Also remove the handlers of the root logger that pyclifer did not create (Sentry, syslog, pytest's caplog). By default only the console handler of pyclifer is replaced and those are kept.

False
Source code in src/pyclifer/core/log/config.py
def configure_rich_logging(
    use_rich: bool = True,
    rich_tracebacks: bool = True,
    enable_secrets_filter: bool = True,
    sensitive_fields: list[str] | None = None,
    mask_free_text: bool = False,
    force_reconfigure: bool = False,
    replace_root_handlers: bool = False,
) -> None:
    """Configure the Rich logging system once and centrally.

    This function sets up the entire logging system in one place:
    - Global configuration via basicConfig
    - Adds trace() method to all Python loggers
    - Prevents multiple configurations with built-in checks

    Args:
        use_rich: Enable Rich logging capabilities.
        rich_tracebacks: Enable Rich tracebacks for exceptions.
        enable_secrets_filter: Enable automatic secrets filtering.
        sensitive_fields: Additional field names to mask on top of the defaults.
                          Merged into SecretsMasker.DEFAULT_FIELDS — does not replace them.
        mask_free_text: Also mask key=value pairs written inside the text of a message.
        force_reconfigure: Force reconfiguration even if already configured.
        replace_root_handlers: Also remove the handlers of the root logger that pyclifer did not
            create (Sentry, syslog, pytest's caplog). By default only the console handler of
            pyclifer is replaced and those are kept.
    """
    # Check if the console is already configured, with Rich or without
    if not force_reconfigure:
        root_logger = logging.getLogger()
        if any(_is_console_handler(handler) for handler in root_logger.handlers):
            return  # Already configured, do nothing

    if use_rich and rich_tracebacks:
        # Deferred import: keeps rich.traceback (about 10 ms) off the startup path of every CLI.
        from rich.traceback import install as install_rich_traceback

        # noinspection PyArgumentEqualDefault
        install_rich_traceback(show_locals=False)

    if use_rich:
        shared_handler = RichExtraStreamHandler(
            rich_tracebacks=rich_tracebacks,
            enable_secrets_filter=enable_secrets_filter,
            sensitive_fields=sensitive_fields,
            mask_free_text=mask_free_text,
        )
        shared_handler.setFormatter(RichExtraFormatter())

        # Save the handlers to keep before force configuration wipes them
        root_logger = logging.getLogger()
        kept_handlers = _handlers_to_keep(replace_root_handlers)

        _preconfigure_click_extra_logger(shared_handler)

        basicConfig(
            stream_handler_class=RichExtraStreamHandler,
            formatter_class=RichExtraFormatter,
            force=True,
        )

        # Replace the generic handler added by basicConfig with our configured shared instance
        root_logger = logging.getLogger()
        for h in list(root_logger.handlers):
            if type(h) is RichExtraStreamHandler and h is not shared_handler:
                root_logger.removeHandler(h)

        if shared_handler not in root_logger.handlers:  # pragma: no branch
            root_logger.addHandler(shared_handler)

        # Restore the saved handlers
        for h in kept_handlers:
            if h not in root_logger.handlers:  # pragma: no branch
                root_logger.addHandler(h)

    else:
        _configure_plain_logging(
            enable_secrets_filter, sensitive_fields, mask_free_text, replace_root_handlers
        )

add_trace_method

Patches a logger instance with a .trace() method at level 5.

pyclifer.add_trace_method(logger_class)

Add a trace method to a logger class.

Parameters:

Name Type Description Default
logger_class type

Logger class to extend.

required

Returns:

Type Description
type

The updated logger class.

Source code in src/pyclifer/core/log/levels.py
def add_trace_method(logger_class: type) -> type:
    """Add a trace method to a logger class.

    Args:
        logger_class: Logger class to extend.

    Returns:
        The updated logger class.
    """

    # noinspection PyIncorrectDocstring
    def trace(self, msg: str, *args: Any, **kwargs: Any) -> None:
        """Log a message at TRACE level.

        Args:
            msg: Message to log.
            *args: Additional positional arguments for formatting.
            **kwargs: Additional keyword arguments for logging.
        """
        if self.isEnabledFor(TRACE):
            kwargs["stacklevel"] = kwargs.get("stacklevel", 1) + _TRACE_STACKLEVEL_OFFSET
            self._log(TRACE, msg, args, **kwargs)

    logger_class.trace = trace
    return logger_class

SecretsMasker

Log filter that redacts sensitive values from log records.

pyclifer.SecretsMasker

Bases: Filter

Redact secrets from logs.

Source code in src/pyclifer/core/log/filters.py
class SecretsMasker(logging.Filter):
    """Redact secrets from logs."""

    ALREADY_FILTERED_FLAG = "__SecretsMasker_filtered"
    DEFAULT_FIELDS: ClassVar[frozenset[str]] = DEFAULT_SENSITIVE_FIELDS

    def __init__(
        self, sensitive_fields: list[str] | None = None, mask_free_text: bool = False
    ) -> None:
        """Initialize the masker, merging sensitive_fields into DEFAULT_FIELDS.

        Args:
            sensitive_fields: Additional field names to mask on top of DEFAULT_FIELDS.
                              None and [] are equivalent — only DEFAULT_FIELDS are used.
            mask_free_text: Also mask key=value pairs written inside the text of a message and
                            of the exception it carries (message, cause, context, group, notes).
                            Off by default: a name that contains a sensitive field is masked
                            whatever its value means, so max_tokens=100 is masked too.
        """
        super().__init__()
        all_fields = self.DEFAULT_FIELDS | set(sensitive_fields or [])
        pattern = "|".join(re.escape(f) for f in sorted(all_fields))
        self._regex = re.compile(rf"\b({pattern})\b", re.IGNORECASE)
        # The fields this masker hides, lowercase, matched as substrings of a key name.
        self._fields = frozenset(field.strip().lower() for field in all_fields)
        self._mask_free_text = mask_free_text
        self._text_regex = self._build_text_regex(self._fields)

    def filter(self, record: logging.LogRecord) -> bool:
        """Filter a log record by redacting sensitive values.

        Checks whether the record was already processed to avoid duplicate
        redaction. If not processed, applies redaction to all record fields
        containing sensitive data.

        Args:
            record: The log record to filter.

        Returns:
            True if the record was successfully filtered or already processed,
            False if no regex is configured.
        """
        record_dict = record.__dict__

        if self.ALREADY_FILTERED_FLAG in record_dict:
            return True

        if self._regex:
            for k, v in record_dict.items():
                record_dict[k] = self.redact(v)
        else:
            return False

        if self._mask_free_text:
            self._mask_message(record)
            self._mask_exception(record)

        record_dict[self.ALREADY_FILTERED_FLAG] = True
        return True

    @staticmethod
    def _build_text_regex(fields: frozenset[str]) -> re.Pattern[str]:
        """Compile the pattern that finds a sensitive key and its value inside a text.

        The key is any name that contains a sensitive field, possibly quoted. It is followed by
        = or :, an optional authorization scheme, then the value: quoted up to the closing
        quote, or unquoted up to a space or a delimiter.

        The key can only start at the beginning of a word. Without that anchor, every position
        inside a long run of word characters restarted the greedy prefix, which made the cost
        grow with the square of the text.
        """
        alternatives = "|".join(re.escape(f) for f in sorted(fields, key=len, reverse=True))
        return re.compile(
            rf"""
            (?<![\w.\-])
            (?P<key>["']?[\w.\-]*(?:{alternatives})[\w.\-]*["']?)
            (?P<separator>\s*[:=]\s*)
            (?P<scheme>(?:Bearer|Basic|Token)\s+)?
            (?:"(?P<double>[^"]*)"|'(?P<single>[^']*)'|(?P<bare>[^\s"',;&)\]}}]+))
            """,
            re.IGNORECASE | re.VERBOSE,
        )

    def redact_text(self, text: str) -> str:
        """Mask the value of every sensitive key written as key=value inside a text.

        Args:
            text: The text to scan, for example a log message.

        Returns:
            The text with those values replaced by a placeholder. A secret with no key next to it,
            as in "the password is hunter2", cannot be found and is kept.
        """

        def replace(match: re.Match[str]) -> str:
            quote = (
                '"' if match["double"] is not None else "'" if match["single"] is not None else ""
            )
            return (
                f"{match['key']}{match['separator']}{match['scheme'] or ''}{quote}*CENSORED*{quote}"
            )

        return self._text_regex.sub(replace, text)

    def _mask_message(self, record: logging.LogRecord) -> None:
        """Replace a record's message by its formatted and masked text.

        The arguments are folded into the message first, since a secret can sit in either, and
        emptied afterwards. A message that cannot be formatted is left to logging to report.
        """
        try:
            message = record.getMessage()
        except (TypeError, ValueError):  # bad format string or arguments: logging will report it
            return
        record.msg = self.redact_text(message)
        record.args = ()

    def _mask_exception(self, record: logging.LogRecord) -> None:
        """Mask the secrets written in the exception a record carries.

        The exception of exc_info is replaced by a masked copy, so that a handler still renders it
        itself, with its Rich traceback. A text another handler already formatted and cached in
        exc_text is masked too, since the formatter would reuse it. The source lines a traceback
        shows are not touched.
        """
        if record.exc_text:
            record.exc_text = self.redact_text(record.exc_text)
        if record.exc_info and record.exc_info[1] is not None:
            _, exception, traceback = record.exc_info
            masked = self._masked_exception(exception, {})
            record.exc_info = (type(masked), masked, traceback)

    def _masked_exception(
        self, exception: BaseException | None, copies: dict[int, BaseException]
    ) -> BaseException | None:
        """Copy an exception so that its text is masked, with the same type name and traceback.

        The copy is an instance of a subclass of the original type that has the same name and
        module and whose str() is the masked text of the original. The cause, the context, the
        exceptions of a group and the notes are masked the same way.

        Args:
            exception: The exception to copy, or None.
            copies: The copies already made, by the id of the original, which stops a chain that
                loops back to an exception already met.

        Returns:
            The masked copy, or None when there is no exception.
        """
        if exception is None:
            return None
        if id(exception) in copies:
            return copies[id(exception)]

        text = self.redact_text(str(exception))
        original_type = type(exception)
        try:
            masked_type = type(
                original_type.__name__,
                (original_type,),
                {
                    "__str__": lambda self: text,
                    "__module__": original_type.__module__,
                    "__qualname__": original_type.__qualname__,
                },
            )
            if _EXCEPTION_GROUP is not None and isinstance(exception, _EXCEPTION_GROUP):
                members = [
                    self._masked_exception(member, copies) for member in exception.exceptions
                ]
                masked = masked_type.__new__(masked_type, exception.message, members)
            else:
                masked = masked_type.__new__(masked_type, *exception.args)
        except (TypeError, ValueError):  # a type that cannot be subclassed or built from its args
            masked = RuntimeError(text)

        masked.__dict__.update(exception.__dict__)
        copies[id(exception)] = masked
        notes = getattr(exception, "__notes__", None)
        if isinstance(notes, list):
            masked.__notes__ = [self.redact_text(str(note)) for note in notes]
        masked.__cause__ = self._masked_exception(exception.__cause__, copies)
        masked.__context__ = self._masked_exception(exception.__context__, copies)
        masked.__suppress_context__ = (
            exception.__suppress_context__
        )  # after __cause__, which sets it
        masked.__traceback__ = exception.__traceback__
        return masked

    def _hides(self, name: Any) -> bool:
        """Tell whether a key name holds one of the fields this masker hides.

        Unlike should_hide_value_for_key, which only knows the default fields, this takes the
        sensitive_fields given to the masker into account.
        """
        if isinstance(name, str):
            name = name.strip().lower()
            return any(field in name for field in self._fields)
        return False

    def _redact_all(self, item, depth):
        """Recursively replace all string values with a censored placeholder."""
        if isinstance(item, str):
            return "*CENSORED*"
        if isinstance(item, dict):
            return {
                dict_key: self._redact_all(nested_item, depth + 1)
                for dict_key, nested_item in item.items()
            }
        elif isinstance(item, (tuple, set)):
            return tuple(self._redact_all(nested_item, depth + 1) for nested_item in item)
        elif isinstance(item, list):
            return [self._redact_all(nested_item, depth + 1) for nested_item in item]
        else:
            return item

    def _redact(self, item, name, depth):
        """Recursively redact sensitive fields from a value based on the key name.

        Depth is bounded to avoid spending excessive effort on deeply nested
        structures and to prevent infinite recursion when a structure holds a
        reference to itself.
        """
        try:
            if name and self._hides(name):
                return self._redact_all(item, depth)
            if isinstance(item, dict):
                return {
                    dict_key: self._redact(nested_item, name=dict_key, depth=(depth + 1))
                    for dict_key, nested_item in item.items()
                }
            elif isinstance(item, tuple) and hasattr(item, "_asdict") and hasattr(item, "_fields"):
                named_tuple = item.__class__.__name__
                # noinspection PyProtectedMember
                item = item._asdict()
                masked_dict = {
                    dict_key: self._redact(nested_item, name=dict_key, depth=(depth + 1))
                    for dict_key, nested_item in item.items()
                }
                # noinspection PyArgumentList
                return namedtuple(named_tuple, masked_dict.keys())(**masked_dict)
            elif isinstance(item, str):
                return item
            elif isinstance(item, (tuple, set)):
                return tuple(
                    self._redact(nested_item, name=None, depth=(depth + 1)) for nested_item in item
                )
            elif isinstance(item, list):
                return [
                    self._redact(nested_element, name=None, depth=(depth + 1))
                    for nested_element in item
                ]
            else:
                return item
        except Exception as e:  # security filter must never crash — log and return item unredacted
            logging.warning(
                "Unable to redact %s. Error was: %s: %s",
                repr(item),
                type(e).__name__,
                str(e),
            )

            return item

    def redact(self, item: Any, name: str | None = None) -> Any:
        """Redact sensitive information from the given input data.

        Processes the provided item and optionally uses the name for context
        during redaction to securely obfuscate sensitive fields.

        Args:
            item: The data object to be redacted.
            name: An optional name providing context for the redaction process.

        Returns:
            The redacted version of the input data.
        """
        return self._redact(item, name, depth=0)

__init__(sensitive_fields=None, mask_free_text=False)

Initialize the masker, merging sensitive_fields into DEFAULT_FIELDS.

Parameters:

Name Type Description Default
sensitive_fields list[str] | None

Additional field names to mask on top of DEFAULT_FIELDS. None and [] are equivalent — only DEFAULT_FIELDS are used.

None
mask_free_text bool

Also mask key=value pairs written inside the text of a message and of the exception it carries (message, cause, context, group, notes). Off by default: a name that contains a sensitive field is masked whatever its value means, so max_tokens=100 is masked too.

False
Source code in src/pyclifer/core/log/filters.py
def __init__(
    self, sensitive_fields: list[str] | None = None, mask_free_text: bool = False
) -> None:
    """Initialize the masker, merging sensitive_fields into DEFAULT_FIELDS.

    Args:
        sensitive_fields: Additional field names to mask on top of DEFAULT_FIELDS.
                          None and [] are equivalent — only DEFAULT_FIELDS are used.
        mask_free_text: Also mask key=value pairs written inside the text of a message and
                        of the exception it carries (message, cause, context, group, notes).
                        Off by default: a name that contains a sensitive field is masked
                        whatever its value means, so max_tokens=100 is masked too.
    """
    super().__init__()
    all_fields = self.DEFAULT_FIELDS | set(sensitive_fields or [])
    pattern = "|".join(re.escape(f) for f in sorted(all_fields))
    self._regex = re.compile(rf"\b({pattern})\b", re.IGNORECASE)
    # The fields this masker hides, lowercase, matched as substrings of a key name.
    self._fields = frozenset(field.strip().lower() for field in all_fields)
    self._mask_free_text = mask_free_text
    self._text_regex = self._build_text_regex(self._fields)

filter(record)

Filter a log record by redacting sensitive values.

Checks whether the record was already processed to avoid duplicate redaction. If not processed, applies redaction to all record fields containing sensitive data.

Parameters:

Name Type Description Default
record LogRecord

The log record to filter.

required

Returns:

Type Description
bool

True if the record was successfully filtered or already processed,

bool

False if no regex is configured.

Source code in src/pyclifer/core/log/filters.py
def filter(self, record: logging.LogRecord) -> bool:
    """Filter a log record by redacting sensitive values.

    Checks whether the record was already processed to avoid duplicate
    redaction. If not processed, applies redaction to all record fields
    containing sensitive data.

    Args:
        record: The log record to filter.

    Returns:
        True if the record was successfully filtered or already processed,
        False if no regex is configured.
    """
    record_dict = record.__dict__

    if self.ALREADY_FILTERED_FLAG in record_dict:
        return True

    if self._regex:
        for k, v in record_dict.items():
            record_dict[k] = self.redact(v)
    else:
        return False

    if self._mask_free_text:
        self._mask_message(record)
        self._mask_exception(record)

    record_dict[self.ALREADY_FILTERED_FLAG] = True
    return True

redact_text(text)

Mask the value of every sensitive key written as key=value inside a text.

Parameters:

Name Type Description Default
text str

The text to scan, for example a log message.

required

Returns:

Type Description
str

The text with those values replaced by a placeholder. A secret with no key next to it,

str

as in "the password is hunter2", cannot be found and is kept.

Source code in src/pyclifer/core/log/filters.py
def redact_text(self, text: str) -> str:
    """Mask the value of every sensitive key written as key=value inside a text.

    Args:
        text: The text to scan, for example a log message.

    Returns:
        The text with those values replaced by a placeholder. A secret with no key next to it,
        as in "the password is hunter2", cannot be found and is kept.
    """

    def replace(match: re.Match[str]) -> str:
        quote = (
            '"' if match["double"] is not None else "'" if match["single"] is not None else ""
        )
        return (
            f"{match['key']}{match['separator']}{match['scheme'] or ''}{quote}*CENSORED*{quote}"
        )

    return self._text_regex.sub(replace, text)

redact(item, name=None)

Redact sensitive information from the given input data.

Processes the provided item and optionally uses the name for context during redaction to securely obfuscate sensitive fields.

Parameters:

Name Type Description Default
item Any

The data object to be redacted.

required
name str | None

An optional name providing context for the redaction process.

None

Returns:

Type Description
Any

The redacted version of the input data.

Source code in src/pyclifer/core/log/filters.py
def redact(self, item: Any, name: str | None = None) -> Any:
    """Redact sensitive information from the given input data.

    Processes the provided item and optionally uses the name for context
    during redaction to securely obfuscate sensitive fields.

    Args:
        item: The data object to be redacted.
        name: An optional name providing context for the redaction process.

    Returns:
        The redacted version of the input data.
    """
    return self._redact(item, name, depth=0)

RichExtraFormatter / RichExtraStreamHandler

Rich-aware formatter and stream handler. Wired up automatically by configure_rich_logging.

pyclifer.RichExtraFormatter

Bases: Formatter

Enhanced Formatter with Rich text capabilities and TRACE level support.

Extends click-extra's Formatter to support Rich markup and custom TRACE level while preserving a click-extra's colorization system.

Source code in src/pyclifer/core/log/formatters.py
class RichExtraFormatter(Formatter):
    """Enhanced Formatter with Rich text capabilities and TRACE level support.

    Extends click-extra's Formatter to support Rich markup and custom TRACE level
    while preserving a click-extra's colorization system.
    """

    def formatMessage(self, record: logging.LogRecord) -> str:
        """Enhanced formatting with Rich support and TRACE level.

        TRACE records are styled directly because click-extra's theme has no
        TRACE entry; all other levels delegate to the parent's colorization system.

        Args:
            record: LogRecord to format.

        Returns:
            Formatted message string.
        """
        if record.levelno == TRACE:
            record.levelname = style("TRACE", fg="blue", dim=True)
        else:
            level = record.levelname.lower()
            level_style = getattr(get_default_theme(), level, None)
            if level_style:
                record.levelname = level_style(record.levelname.upper())

        message = super().formatMessage(record)

        if hasattr(record, "rich") and record.rich:
            rich_text = Text.from_markup(record.getMessage())
            record.msg = rich_text.markup

        return message

formatMessage(record)

Enhanced formatting with Rich support and TRACE level.

TRACE records are styled directly because click-extra's theme has no TRACE entry; all other levels delegate to the parent's colorization system.

Parameters:

Name Type Description Default
record LogRecord

LogRecord to format.

required

Returns:

Type Description
str

Formatted message string.

Source code in src/pyclifer/core/log/formatters.py
def formatMessage(self, record: logging.LogRecord) -> str:
    """Enhanced formatting with Rich support and TRACE level.

    TRACE records are styled directly because click-extra's theme has no
    TRACE entry; all other levels delegate to the parent's colorization system.

    Args:
        record: LogRecord to format.

    Returns:
        Formatted message string.
    """
    if record.levelno == TRACE:
        record.levelname = style("TRACE", fg="blue", dim=True)
    else:
        level = record.levelname.lower()
        level_style = getattr(get_default_theme(), level, None)
        if level_style:
            record.levelname = level_style(record.levelname.upper())

    message = super().formatMessage(record)

    if hasattr(record, "rich") and record.rich:
        rich_text = Text.from_markup(record.getMessage())
        record.msg = rich_text.markup

    return message

pyclifer.RichExtraStreamHandler

Bases: StreamHandler

Enhanced StreamHandler with Rich support and built-in security filtering.

Extends click-extra's StreamHandler to use Rich for beautiful logging while maintaining compatibility with click.echo() and color support. Automatically includes SecretsMasker for sensitive data protection.

Source code in src/pyclifer/core/log/handlers.py
class RichExtraStreamHandler(StreamHandler):
    """Enhanced StreamHandler with Rich support and built-in security filtering.

    Extends click-extra's StreamHandler to use Rich for beautiful logging
    while maintaining compatibility with click.echo() and color support.
    Automatically includes SecretsMasker for sensitive data protection.
    """

    def __init__(
        self,
        stream: TextIOBase | None = None,
        rich_tracebacks: bool = True,
        enable_secrets_filter: bool = True,
        sensitive_fields: list[str] | None = None,
        mask_free_text: bool = False,
        **kwargs: Any,
    ) -> None:
        """Initialize the Rich Extra Stream Handler.

        Args:
            stream: Output stream (defaults to sys.stderr).
            rich_tracebacks: Enable Rich tracebacks.
            enable_secrets_filter: Enable automatic secrets filtering.
            sensitive_fields: Additional field names to mask on top of the defaults.
                              Merged into SecretsMasker.DEFAULT_FIELDS — does not replace them.
            mask_free_text: Also mask key=value pairs written inside the text of a message.
            **kwargs: Additional keyword arguments passed to RichHandler.
        """
        super().__init__(stream or sys.stderr)

        self.rich_console = Console(
            file=self.stream,
            stderr=(self.stream == sys.stderr),
        )

        self._rich_handler = RichHandler(
            console=self.rich_console,
            rich_tracebacks=rich_tracebacks,
            **kwargs,
        )

        if enable_secrets_filter:
            self.addFilter(
                SecretsMasker(sensitive_fields=sensitive_fields, mask_free_text=mask_free_text)
            )

    def emit(self, record: logging.LogRecord) -> None:
        """Use Rich handler for enhanced output while maintaining click-extra compatibility.

        Args:
            record: LogRecord to emit.
        """
        # noinspection PyBroadException
        try:
            # Use Rich handlers emit method for better formatting
            self._rich_handler.emit(record)
        except RecursionError:
            raise
        except Exception:
            # Fallback to parent's behavior
            super().emit(record)

__init__(stream=None, rich_tracebacks=True, enable_secrets_filter=True, sensitive_fields=None, mask_free_text=False, **kwargs)

Initialize the Rich Extra Stream Handler.

Parameters:

Name Type Description Default
stream TextIOBase | None

Output stream (defaults to sys.stderr).

None
rich_tracebacks bool

Enable Rich tracebacks.

True
enable_secrets_filter bool

Enable automatic secrets filtering.

True
sensitive_fields list[str] | None

Additional field names to mask on top of the defaults. Merged into SecretsMasker.DEFAULT_FIELDS — does not replace them.

None
mask_free_text bool

Also mask key=value pairs written inside the text of a message.

False
**kwargs Any

Additional keyword arguments passed to RichHandler.

{}
Source code in src/pyclifer/core/log/handlers.py
def __init__(
    self,
    stream: TextIOBase | None = None,
    rich_tracebacks: bool = True,
    enable_secrets_filter: bool = True,
    sensitive_fields: list[str] | None = None,
    mask_free_text: bool = False,
    **kwargs: Any,
) -> None:
    """Initialize the Rich Extra Stream Handler.

    Args:
        stream: Output stream (defaults to sys.stderr).
        rich_tracebacks: Enable Rich tracebacks.
        enable_secrets_filter: Enable automatic secrets filtering.
        sensitive_fields: Additional field names to mask on top of the defaults.
                          Merged into SecretsMasker.DEFAULT_FIELDS — does not replace them.
        mask_free_text: Also mask key=value pairs written inside the text of a message.
        **kwargs: Additional keyword arguments passed to RichHandler.
    """
    super().__init__(stream or sys.stderr)

    self.rich_console = Console(
        file=self.stream,
        stderr=(self.stream == sys.stderr),
    )

    self._rich_handler = RichHandler(
        console=self.rich_console,
        rich_tracebacks=rich_tracebacks,
        **kwargs,
    )

    if enable_secrets_filter:
        self.addFilter(
            SecretsMasker(sensitive_fields=sensitive_fields, mask_free_text=mask_free_text)
        )

emit(record)

Use Rich handler for enhanced output while maintaining click-extra compatibility.

Parameters:

Name Type Description Default
record LogRecord

LogRecord to emit.

required
Source code in src/pyclifer/core/log/handlers.py
def emit(self, record: logging.LogRecord) -> None:
    """Use Rich handler for enhanced output while maintaining click-extra compatibility.

    Args:
        record: LogRecord to emit.
    """
    # noinspection PyBroadException
    try:
        # Use Rich handlers emit method for better formatting
        self._rich_handler.emit(record)
    except RecursionError:
        raise
    except Exception:
        # Fallback to parent's behavior
        super().emit(record)

Constants

pyclifer.TRACE = 5 module-attribute

pyclifer.PYCLIFER_LOG_LEVELS = {**LOG_LEVELS, 'TRACE': TRACE} module-attribute