Rich Logging¶
pyclifer integrates Rich into the logging system while maintaining full compatibility with click-extra and
preserving the SecretsMasker filter and custom TRACE level.
Overview¶
The Rich logging integration provides:
- Colored output: Beautiful, colored log messages with Rich formatting
- Rich tracebacks: Enhanced exception display with syntax highlighting
- Security filtering: Automatic masking of sensitive information
- TRACE level: Custom debug level (value 5) for detailed troubleshooting
- File logging: Time-based rotating log files with configurable verbosity
- Click-extra compatibility: Seamless integration with existing CLI infrastructure
Architecture¶
The logging system lives in src/pyclifer/core/log/:
-
levels.py— Custom logging levels and utilitiesTRACElevel (value 5)PYCLIFER_LOG_LEVELSextending click-extra's log levelsadd_trace_method()for adding trace capability to loggers
-
handlers.py— Rich-enhanced stream handlersRichExtraStreamHandler: click-extra compatible Rich handler- Automatic Rich tracebacks support
- Built-in
SecretsMaskerintegration
-
formatters.py— Enhanced log formattersRichExtraFormatter: Rich markup support with TRACE level styling
-
filters.py— Log filtering utilitiesSecretsMasker: Automatic masking of passwords, keys, tokens, etc.
-
config.py— Configuration utilitiesconfigure_rich_logging(): Global logging configurationget_configured_logger(): Factory for Rich-enabled loggersPycliferVerbosityOption: Verbosity option with TRACE supportsetup_file_logging(): Time-based rotating log filescreate_log_file_callback(): Click callback for--log-file
PYCLIFER_LOG_LEVELS extends click-extra's standard levels with TRACE:
from pyclifer import PYCLIFER_LOG_LEVELS
# {"TRACE": 5, "DEBUG": 10, "INFO": 20, "WARNING": 30, "ERROR": 40, "CRITICAL": 50}
For advanced handler setup — when wiring pyclifer logging into an existing logging config:
from pyclifer import (
RichExtraFormatter,
RichExtraStreamHandler,
add_trace_method,
TRACE,
)
import logging
# Every logger has .trace() as soon as pyclifer is imported, no application needed
logger = logging.getLogger("myapp")
logger.trace("low-level trace message") # level 5
# add_trace_method takes a logger CLASS, for a custom logger class
class MyLogger(logging.Logger): ...
add_trace_method(MyLogger)
# Build a handler manually
handler = RichExtraStreamHandler()
handler.setFormatter(RichExtraFormatter())
handler.setLevel(TRACE)
Most projects use configure_rich_logging() or @app_group(use_rich_logging=True) instead —
these primitives are for custom setups.
Usage¶
Automatic Rich Logging with @app_group¶
from pyclifer import app_group
@app_group() # Rich logging enabled by default
def cli():
"""My CLI with beautiful Rich logging."""
pass
@app_group(
use_rich_logging=True,
enable_secrets_filter=True,
add_log_file_option=True,
log_file_default_level="TRACE",
)
def advanced_cli():
"""CLI with explicit Rich configuration."""
pass
@app_group(
enable_secrets_filter=True,
sensitive_fields=["bearer_token", "api_secret_key"],
)
def secure_cli():
"""CLI that masks custom sensitive fields in addition to the defaults."""
pass
Logging from Code¶
from pyclifer import logger, get_logger
# Use the pre-configured global logger
logger.info("Application starting...")
logger.trace("Checking internal state")
# Or create a named logger
app_logger = get_logger("my-app")
app_logger.warning("Something might be wrong")
Command Line Usage¶
# Use TRACE level for detailed debugging
myapp --verbosity TRACE command
# Supported levels: TRACE, DEBUG, INFO, WARNING, ERROR, CRITICAL
myapp --verbosity DEBUG command
# Environment variable support
MYAPP_VERBOSITY=TRACE myapp command
The level goes both ways. The default is WARNING (change it with verbosity_default_level), and a
level you choose replaces it, whether it is more or less verbose:
myapp --verbosity DEBUG command # warnings, plus info and debug messages
myapp --verbosity ERROR command # only errors and critical messages
myapp command --verbosity ERROR # the option is accepted after the subcommand too
If you give two levels on the same command line, the most verbose one wins.
--verbosity comes from add_verbosity_option, which is True by default on @app_group. With
add_verbosity_option=False the option is not declared, and the console is still set up with the
settings of the group.
File Logging¶
from pyclifer import app_group
@app_group(
add_log_file_option=True, # Adds --log-file option
log_file_default_level="TRACE", # Default file log level
log_file_rotation_when="midnight",
log_file_rotation_interval=1, # one rotation per `when` unit
log_file_rotation_backup_count=7
)
def cli():
pass
Console verbosity (--verbosity) and file log level are independent.
Centralized Configuration¶
from pyclifer import get_logger, configure_rich_logging
# Done automatically by @app_group — shown here for reference
configure_rich_logging(
use_rich=True,
rich_tracebacks=True,
enable_secrets_filter=True,
sensitive_fields=["bearer_token", "api_secret_key"], # merged into defaults
)
logger = get_logger() # Automatically Rich-enabled
Features¶
Custom Sensitive Fields¶
SecretsMasker ships with a built-in set of field names it always masks. Pass sensitive_fields
to extend this list — the defaults are never removed.
Default masked fields (SecretsMasker.DEFAULT_FIELDS):
access_token, api_key, apikey, authorization, keyfile_dict,
passphrase, passwd, password, private_key, pwd,
secret, service_account, token
@app_group(
sensitive_fields=["bearer_token", "api_secret_key"],
)
def cli():
"""bearer_token and api_secret_key are masked in addition to the defaults."""
pass
sensitive_fields propagates to both the console handler and the file handler (if --log-file
is active). The complete default list is available as SecretsMasker.DEFAULT_FIELDS.
A field matches when its name contains one of the listed names, ignoring case: with token in the
list, bearer_token and Token are masked too. Set enable_secrets_filter=False to turn the
filter off.
By default, masking works on keys, not on free text
The filter hides the value of a key, in a dict, a named tuple or a log record attribute:
log.warning("payload %s", {"password": "hunter2", "user": "bob"})
# payload {'password': '*CENSORED*', 'user': 'bob'}
A plain message such as log.warning("password=hunter2") is logged as is, unless you turn on
mask_free_text.
Masking Free Text¶
Set mask_free_text=True to also mask key=value pairs written inside a message:
@app_group(mask_free_text=True, sensitive_fields=["mycode"])
def cli():
"""Masks secrets written in the text of a message."""
log.warning("login password=hunter2 mycode=mc-777 for bob")
# login password=*CENSORED* mycode=*CENSORED* for bob
It finds a sensitive name followed by = or :: password=x, password: x, JSON such as
{"password": "x"}, a query string ?api_key=x&user=bob, and an Authorization: Bearer x header.
It applies to the console (Rich or plain) and to the log file. It is off by default.
Know its limits before turning it on:
- A secret with no name next to it is not found.
"the password is hunter2"is logged as is. - It can mask too much. The rule is the same as for keys: a name that contains a sensitive
field matches, whatever its value means.
max_tokens=100andtoken: expiredare masked. - The source lines of a traceback are not scanned. A traceback shows the line of code that
raised, so a secret written as a literal in that line (
raise Error("token=abc")) still appears. Build the message from a variable instead. enable_secrets_filter=Falseturns it off too.
The text of the exceptions you log is masked as well, in the console (Rich or plain) and in the log
file. This covers the message of the exception, its cause and context, the exceptions of an
ExceptionGroup and its notes. The Rich traceback keeps its rendering:
try:
client.get("https://api.example.com/?api_key=abc123")
except ConnectionError:
log.exception("call failed")
# ConnectionError: GET https://api.example.com/?api_key=*CENSORED* failed
The exception that you catch is never modified: the handlers receive a masked copy with the same type, the same name and the same traceback.
Handlers From Other Libraries¶
When pyclifer sets up the console, it replaces only its own console handler. A handler that another
library put on the root logger (Sentry, syslog, pytest's caplog) is kept and keeps receiving the
records, also after --verbosity rebuilds the console. File handlers are kept as well.
@app_group()
def cli():
"""Replaces its own console handler only: a handler added elsewhere keeps receiving records."""
To remove every other handler of the root logger as well, ask for it:
@app_group(replace_root_handlers=True)
def cli():
"""Removes every handler of the root logger when it sets up the console."""
The console handler that logging.basicConfig() installs with its default arguments (a plain
StreamHandler on stderr with the standard format) is replaced like pyclifer's own: kept, it would
write every record a second time, without the secrets filter. A StreamHandler you wrote yourself
is never taken for it, since it does not carry that formatter. A handler from
logging.basicConfig(format=...) is kept too, and the console then shows each record twice: pass
replace_root_handlers=True in that case. It gives back the previous behaviour: every handler of the
root logger that pyclifer did not create is removed, whatever its type.
Preserved Functionality¶
- TRACE level: Custom debug level (value 5)
- SecretsMasker filter: Automatic masking of sensitive data — extensible via
sensitive_fields - Full compatibility: Works with existing code without modifications
Rich Capabilities¶
- Colored output: Automatic colorization of log levels and messages
- Rich tracebacks: Syntax-highlighted exception traces
- Timestamp display: Automatic
[MM/DD/YY HH:MM:SS]formatting - File rotation: Fine-grained control over log file rotation policies
- Global logger: Pre-instantiated
loggeravailable for immediate use
Click-Extra Integration¶
- Extended verbosity: TRACE level in
--verbosityoption - Environment variables: Full
<PREFIX>_VERBOSITYsupport - Automatic configuration: No manual setup required
Examples¶
Basic CLI with Rich Logging¶
from pyclifer import app_group, logger
@app_group()
def cli():
"""CLI with automatic Rich logging."""
pass
@cli.command()
def test():
"""Test command."""
logger.trace("Detailed debug information")
logger.info("Operation successful")
logger.warning("Warning message")
logger.error("Error occurred")
Advanced Configuration¶
from pyclifer import app_group
@app_group(
use_rich_logging=True,
enable_secrets_filter=True
)
def secure_cli():
"""CLI with Rich logging and secrets filtering."""
pass
@app_group(use_rich_logging=False)
def simple_cli():
"""CLI with standard logging."""
pass
With use_rich_logging=False the console uses click-extra's standard handler: one line per record,
written as level: message (lowercase level, no timestamp).
Everything else behaves as with Rich: --verbosity sets the level, enable_secrets_filter and
sensitive_fields mask secrets, and --log-file writes the rotating file.
Rich Markup in Log Messages¶
from pyclifer import logger
logger.info("[green]✓[/green] Success!")
logger.warning("[yellow]⚠[/yellow] Warning!")
try:
risky_operation()
except Exception:
logger.exception("Rich will display beautiful tracebacks")