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 TRACE pseudo-level below LogLevel.DEBUG (numeric value 5, mirroring logging.DEBUG - 5) so repeated -v can surface finer-grained tracing past DEBUG;

  • a SILENT pseudo-level above LogLevel.CRITICAL (any value above logging.CRITICAL) so repeated -q can suppress every record, including LogLevel.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: IntEnum

Mapping of canonical log level names to their integer level.

Mirrors logging._nameToLevel, but:

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 the root logger 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 of str.format().

The default of basicConfig(), where logging.basicConfig() defaults to %.

class click_extra.logging.StreamHandler(stream=None)[source]

Bases: StreamHandler

A handler to output logs to the console.

Wraps logging.StreamHandler, but uses click.echo() to support color printing.

Only sys.stderr or sys.stdout are allowed as output stream, and sys.stderr is 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 an OperationTrail progress bar): the record is then printed through its echo, 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 to click.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-color and keep its ANSI codes on a TTY.

Return type:

None

class click_extra.logging.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]

Bases: Formatter

Click 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 or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

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 via click_extra.theme.get_current_theme().

A record carrying a label attribute (each line run_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 render record.label its 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 levelname and message are 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:

str

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 root logger.

This function is a wrapper around Python standard library’s logging.basicConfig(), but with additional parameters and tweaked defaults.

It sets up the global root logger, and optionally adds a file or stream handler to it.

Differences in default values:

Argument

basicConfig() default

logging.basicConfig() default

style

{

%

format

{levelname}: {message}

%(levelname)s:%(name)s:%(message)s

This 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 a logging.FileHandler be created, using the specified filename, rather than a StreamHandler.

  • filemode (str) –

    If filename is specified, open the file in this mode.

    Defaults to a.

  • format (str | None) –

    Use the specified format string for the handler.

    Defaults to {levelname}: {message}.

  • datefmt (str | None) – Use the specified date/time format, as accepted by time.strftime().

  • style (Literal['%', '{', '$']) –

    If format is specified, use this style for the format string:

    Defaults to {.

  • level (int | str | None) – Set the root logger level to the specified level.

  • stream (IO[Any] | None) – Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, a ValueError is raised.

  • handlers (Iterable[Handler] | None) – If specified, this should be an iterable of already created handlers to add to the root logger. 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, a ValueError is raised.

  • force (bool) – If this argument is specified as True, any existing handlers attached to the root logger 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 to logging.FileHandler for opening the output file.

  • errors (str | None) – Optional string that specifies how encoding and decoding errors are to be handled by the logging.FileHandler. Defaults to backslashreplace. Note that if None is specified, it will be passed as such to open().

Return type:

None

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:

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 logger registered under the name parameter, or creates a new one with that name if it doesn’t exist,

  • Set the logger’s propagate attribute to False,

  • Force removal of any existing handlers and formatters attached to the logger,

  • Attach a new StreamHandler with Formatter,

  • 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 the root logger, 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=False the 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 root logger. They attach their handler beside the others, for the time of a run. See add_to_parser().

Parameters:
  • name (str) – ID of the logger to setup. Defaults to the name of Python’s root logger. 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’s propagate attribute. Defaults to False.

  • force (bool) – Same as the force parameter from logging.basicConfig() and basicConfig(). Defaults to True.

  • kwargs – Any other keyword parameters supported by logging.basicConfig() and basicConfig().

Return type:

Logger

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 LEVEL option 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.Logger object is used as it is.

  • The name of the root logger, 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 root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

set_level(ctx, param, value)[source]

Record the --verbosity value, then reconcile.

The value passed to --verbosity is saved in ctx.meta[click_extra.context.VERBOSITY].

Return type:

None

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

--debug flag, 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: -q walks down it, repeatably.

Note

It outranks --verbosity, -v and -q alike 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.Logger object is used as it is.

  • The name of the root logger, 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 root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

set_level(ctx, param, value)[source]

Record that --debug was passed, then reconcile.

The flag is saved in ctx.meta[click_extra.context.DEBUG], so downstream code can tell a level that came from --debug from the same level spelled --verbosity DEBUG.

Return type:

None

class click_extra.logging.VerboseOption(param_decls=None, **kwargs)[source]

Bases: _CounterOption

--verbose/-v option to raise the log level of _VerbosityOption by one step per repetition.

Each -v raises the verbosity by one LogLevel step. 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 at WARNING:

  • -v raises the level to INFO,

  • -vv raises the level to DEBUG,

  • any further repetition is clamped at the loudest level, so -vvvvv for example resolves to DEBUG.

-v shares a single signed counter with QuietOption’s -q, so the two cancel out: -v -q leaves the level unchanged. See _VerbosityOption.resolve_level for 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.Logger object is used as it is.

  • The name of the root logger, 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 root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

class click_extra.logging.QuietOption(param_decls=None, **kwargs)[source]

Bases: _CounterOption

--quiet/-q option to lower the log level of _VerbosityOption by one step per repetition.

The symmetric counterpart of VerboseOption: where -v raises the verbosity one LogLevel step at a time, -q lowers it. Starting from VerbosityOption.default (WARNING by default):

  • -q lowers the level to ERROR,

  • -qq lowers the level to CRITICAL,

  • any further repetition is clamped at the quietest level, so -qqqqq for example resolves to CRITICAL.

-q shares a single signed counter with VerboseOption’s -v, so the two cancel out: -v -q leaves the level unchanged. See _VerbosityOption.resolve_level for 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.Logger object is used as it is.

  • The name of the root logger, 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 root logger, which the whole process shares. Whichever logger is selected, the root one gets Click Extra’s handler for the time of each run of the command: see add_to_parser().

click_extra.logging.requested_level(ctx, opts)[source]

The level the verbosity options of ctx.command will 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. ConfigOption relies on it: it loads the configuration before any verbosity option applies a level, yet -q and a quieter --verbosity still silence its status lines.

Returns None when the command carries no verbosity option, or when a value does not convert: the regular parse reports that error in its turn.

Return type:

LogLevel | None