click_extra.logging module¶
classDiagram
ExtraOption <|-- _VerbosityOption
Formatter <|-- Formatter
IntEnum <|-- LogLevel
StreamHandler <|-- StreamHandler
StreamHandler <|-- _InvocationHandler
_CounterOption <|-- QuietOption
_CounterOption <|-- VerboseOption
_VerbosityOption <|-- DebugOption
_VerbosityOption <|-- VerbosityOption
_VerbosityOption <|-- _CounterOption
Logging utilities.
Todo
Let the -v/-q counter reach beyond the LogLevel range, where it
clamps at DEBUG and CRITICAL:
a
TRACEpseudo-level belowLogLevel.DEBUG(numeric value5, mirroringlogging.DEBUG - 5) so repeated-vcan surface finer-grained tracing pastDEBUG;a
SILENTpseudo-level aboveLogLevel.CRITICAL(any value abovelogging.CRITICAL) so repeated-qcan suppress every record, includingLogLevel.CRITICAL.
Both require extending LogLevel, which ripples into the --verbosity
EnumChoice, the Formatter level-name color
lookup and the level-ordering tests.
- class click_extra.logging.LogLevel(*values)[source]¶
Bases:
IntEnumMapping of canonical log level names to their integer level.
Mirrors logging._nameToLevel, but:
sorted from lowest to highest verbosity,
- excludes the following levels:
NOTSET, which is considered internalWARN, whichis obsoleteFATAL, which shouldn’t be used and has been replaced by CRITICAL
- CRITICAL = 50¶
- ERROR = 40¶
- WARNING = 30¶
- INFO = 20¶
- DEBUG = 10¶
- click_extra.logging.DEFAULT_FORMAT = '{levelname}: {message}'¶
Format of a log record, written in the style of
DEFAULT_STYLE.The default of
basicConfig(), and the format of the handler an option of Click Extra attaches to therootlogger for the time of a run.
- click_extra.logging.DEFAULT_LEVEL: LogLevel = LogLevel.WARNING¶
The level a logger starts its life at:
WARNING.It is the level Python sets its global root logger up at.
This value is also the default level of
VerbosityOption.
- click_extra.logging.DEFAULT_STYLE: Literal['%', '{', '$'] = '{'¶
Style of the format strings:
{is the one ofstr.format().The default of
basicConfig(), wherelogging.basicConfig()defaults to%.
- class click_extra.logging.StreamHandler(stream=None)[source]¶
Bases:
StreamHandlerA handler to output logs to the console.
Wraps
logging.StreamHandler, but usesclick.echo()to support color printing.Only
sys.stderrorsys.stdoutare allowed as output stream, andsys.stderris the default.Initialize the handler.
If stream is not specified, sys.stderr is used.
- property stream: IO[Any]¶
The stream to which logs are written.
A proxy of the parent
logging.StreamHandler’s stream attribute.Redefined here to enforce checks on the stream value.
- emit(record)[source]¶
Use
click.echo()to print to the console.Cooperates with any live terminal line currently drawing on the same stream (a
Spinner, or anOperationTrailprogress bar): the record is then printed through itsecho, which erases the in-progress render first, so a log line emitted mid-draw lands on its own line instead of garbling the indicator (and vice versa).The color tri-state is resolved through
invocation_color()rather than left toclick.echo()’s own context lookup: a record emitted from a background thread (a subprocess stream reader, a fan-out worker) has no reachable Click context, and would otherwise ignore--no-colorand keep its ANSI codes on a TTY.- Return type:
- class click_extra.logging.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]¶
Bases:
FormatterClick Extra’s default log formatter.
Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.
Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting,
str.format()({}) formatting orstring.Templateformatting in your format string.Changed in version 3.2: Added the
styleparameter.- formatMessage(record)[source]¶
Colorize the record’s log level name before calling the standard formatter.
Colors are sourced from a
click_extra.theme.HelpTheme, resolved per-invocation viaclick_extra.theme.get_current_theme().A record carrying a
labelattribute (each linerun_cli()streams from a subprocess is tagged with its caller-provided label) renders it glued to the level name, styled like an invoked command:debug:mas: Warning: .... The tag stays out of the message text itself, so a foreign formatter is free to renderrecord.labelits own way.A message spanning several lines starts on the line below its prefix. Glued to the prefix, the first line of a block (a command’s captured output, a table) shifts right by the width of that prefix while the lines below stay at the margin, which breaks the block’s columns.
The record’s
levelnameandmessageare restored afterwards: a record may be formatted more than once (several handlers, a captured then re-rendered record), and must not accumulate styling, glued labels or line breaks.- Return type:
- click_extra.logging.basicConfig(*, filename=None, filemode='a', format='{levelname}: {message}', datefmt=None, style='{', level=None, stream=None, handlers=None, force=False, encoding=None, errors='backslashreplace', stream_handler_class=<class 'click_extra.logging.StreamHandler'>, file_handler_class=<class 'logging.FileHandler'>, formatter_class=<class 'click_extra.logging.Formatter'>)[source]¶
Configure the global
rootlogger.This function is a wrapper around Python standard library’s
logging.basicConfig(), but with additional parameters and tweaked defaults.It sets up the global
rootlogger, and optionally adds a file or stream handler to it.Differences in default values:
Argument
basicConfig()defaultlogging.basicConfig()defaultstyle{%format{levelname}: {message}%(levelname)s:%(name)s:%(message)sThis function takes the same parameters as
logging.basicConfig(), but require them to be all passed as explicit keywords arguments.- Parameters:
filename (
str|None) – Specifies that alogging.FileHandlerbe created, using the specified filename, rather than aStreamHandler.filemode (
str) –If filename is specified, open the file in this
mode.Defaults to
a.Use the specified format string for the handler.
Defaults to
{levelname}: {message}.datefmt (
str|None) – Use the specified date/time format, as accepted bytime.strftime().style (
Literal['%','{','$']) –If format is specified, use this style for the format string:
%for printf-style,{forstr.format(),$forstring.Template.
Defaults to
{.level (
int|str|None) – Set therootlogger level to the specified level.stream (
IO[Any] |None) – Use the specified stream to initialize theStreamHandler. Note that this argument is incompatible with filename - if both are present, aValueErroris raised.handlers (
Iterable[Handler] |None) – If specified, this should be an iterable of already created handlers to add to therootlogger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with filename or stream - if both are present, aValueErroris raised.force (
bool) – If this argument is specified asTrue, any existing handlers attached to therootlogger are removed and closed, before carrying out the configuration as specified by the other arguments.encoding (
str|None) – Name of the encoding used to decode or encode the file. To be specified along with filename, and passed tologging.FileHandlerfor opening the output file.errors (
str|None) – Optional string that specifies how encoding and decoding errors are to be handled by thelogging.FileHandler. Defaults tobackslashreplace. Note that ifNoneis specified, it will be passed as such toopen().
- Return type:
Important
Always keep the signature of this function, the default values of its parameters and its documentation in sync with the one from Python’s standard library.
These new arguments are available for better configurability:
- Parameters:
stream_handler_class (
type[Handler]) – Alogging.Handlerclass that will be used inlogging.basicConfig()to create a default stream-based handler. Defaults toStreamHandler.file_handler_class (
type[Handler]) – Alogging.Handlerclass that will be used inlogging.basicConfig()to create a default file-based handler. Defaults tologging.FileHandler.formatter_class (
type[Formatter]) – Alogging.Formatterclass of the formatter that will be used inlogging.basicConfig()to setup the default formatter. Defaults toFormatter.
Note
The camel-cased name mirrors the one of Python’s standard library
logging.basicConfig().
- click_extra.logging.new_logger(name='root', *, propagate=False, force=True, **kwargs)[source]¶
Setup a logger in the style of Click Extra.
By default, this helper will:
Fetch the loggerregistered under thenameparameter, or creates a new one with that name if it doesn’t exist,Set the logger’s
propagateattribute toFalse,Force removal of any existing handlers and formatters attached to the logger,
Attach a new
StreamHandlerwithFormatter,Return the logger object.
This function is a wrapper around
basicConfig()and takes the same keywords arguments.Warning
The removal reaches every handler of the logger, not only the ones Click Extra attached. Left on its default
name, this function sets up therootlogger, which the whole process shares: the handlers an application or a test runner attached to it are removed and closed.Call it from the entry point of a program instead of at import time, or name a logger of your own. With
force=Falsethe handlers stay, and the function sets nothing up on a logger that already has one.Note
The options of Click Extra do not call this function for the
rootlogger. They attach their handler beside the others, for the time of a run. Seeadd_to_parser().- Parameters:
name (
str) – ID of the logger to setup. Defaults to the name of Python’srootlogger. If a logger with the provided name is not found in the global registry, a new logger with that name will be created.propagate (
bool) – Sets the logger’spropagateattribute. Defaults toFalse.force (
bool) – Same as the force parameter fromlogging.basicConfig()andbasicConfig(). Defaults toTrue.kwargs – Any other keyword parameters supported by
logging.basicConfig()andbasicConfig().
- Return type:
- class click_extra.logging.VerbosityOption(param_decls=None, *, default_logger='root', default=LogLevel.WARNING, metavar='LEVEL', type=EnumChoice('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'), help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', **kwargs)[source]¶
Bases:
_VerbosityOption--verbosity LEVELoption to set the log level of_VerbosityOption.Set up a verbosity-altering option.
- Parameters:
default_logger (
Logger|str) –The logger the option sets the level of:
A
logging.Loggerobject is used as it is.The name of the
rootlogger, which is the default, selects it.A name found in the global registry selects that logger as it is.
Any other name creates the logger with
new_logger().
Building the option never touches the
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extra’s handler for the time of each run of the command: seeadd_to_parser().
- class click_extra.logging.DebugOption(param_decls=None, *, default_logger='root', is_flag=True, default=False, help='Shorthand for --verbosity DEBUG.', **kwargs)[source]¶
Bases:
_VerbosityOption--debugflag, a shorthand for--verbosity DEBUG.The one level people reach for by name, so it gets a flag of its own. The quiet end of the scale needs no such thing:
-qwalks down it, repeatably.Note
It outranks
--verbosity,-vand-qalike rather than joining their arithmetic, because it asks for the loudest level there is and no combination of the other three can ask for more. See_VerbosityOption.resolve_level().Set up a verbosity-altering option.
- Parameters:
default_logger (
Logger|str) –The logger the option sets the level of:
A
logging.Loggerobject is used as it is.The name of the
rootlogger, which is the default, selects it.A name found in the global registry selects that logger as it is.
Any other name creates the logger with
new_logger().
Building the option never touches the
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extra’s handler for the time of each run of the command: seeadd_to_parser().
- class click_extra.logging.VerboseOption(param_decls=None, **kwargs)[source]¶
Bases:
_CounterOption--verbose/-voption to raise the log level of_VerbosityOptionby one step per repetition.Each
-vraises the verbosity by oneLogLevelstep. The option can be repeated, so-vv(or-v -v) raises it by two steps.The base level the counter starts from is sourced from
VerbosityOption.default. So with--verbosity’s default left atWARNING:-vraises the level toINFO,-vvraises the level toDEBUG,any further repetition is clamped at the loudest level, so
-vvvvvfor example resolves toDEBUG.
-vshares a single signed counter withQuietOption’s-q, so the two cancel out:-v -qleaves the level unchanged. See_VerbosityOption.resolve_levelfor the full reconciliation rule with--verbosity.Set up a verbosity-altering option.
- Parameters:
default_logger –
The logger the option sets the level of:
A
logging.Loggerobject is used as it is.The name of the
rootlogger, which is the default, selects it.A name found in the global registry selects that logger as it is.
Any other name creates the logger with
new_logger().
Building the option never touches the
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extra’s handler for the time of each run of the command: seeadd_to_parser().
- class click_extra.logging.QuietOption(param_decls=None, **kwargs)[source]¶
Bases:
_CounterOption--quiet/-qoption to lower the log level of_VerbosityOptionby one step per repetition.The symmetric counterpart of
VerboseOption: where-vraises the verbosity oneLogLevelstep at a time,-qlowers it. Starting fromVerbosityOption.default(WARNINGby default):-qlowers the level toERROR,-qqlowers the level toCRITICAL,any further repetition is clamped at the quietest level, so
-qqqqqfor example resolves toCRITICAL.
-qshares a single signed counter withVerboseOption’s-v, so the two cancel out:-v -qleaves the level unchanged. See_VerbosityOption.resolve_levelfor the full reconciliation rule with--verbosity.Set up a verbosity-altering option.
- Parameters:
default_logger –
The logger the option sets the level of:
A
logging.Loggerobject is used as it is.The name of the
rootlogger, which is the default, selects it.A name found in the global registry selects that logger as it is.
Any other name creates the logger with
new_logger().
Building the option never touches the
rootlogger, which the whole process shares. Whichever logger is selected, therootone gets Click Extra’s handler for the time of each run of the command: seeadd_to_parser().
- click_extra.logging.requested_level(ctx, opts)[source]¶
The level the verbosity options of
ctx.commandwill settle on.Read from the parsed
opts, the environment and the defaults, without running any of the options’ callbacks, so an eager option processed before them can honor it.ConfigOptionrelies on it: it loads the configuration before any verbosity option applies a level, yet-qand a quieter--verbositystill silence its status lines.Returns
Nonewhen the command carries no verbosity option, or when a value does not convert: the regular parse reports that error in its turn.