f_lib.logging package

Logging utilities.

class f_lib.logging.ConsoleHandler[source]

Bases: RichHandler

Custom console RichHandler.

__init__(level: int | str = logging.NOTSET, console: Console | None = None, *, enable_link_path: bool = True, highlighter: Highlighter | None = None, keywords: list[str] | None = None, locals_max_length: int = 10, locals_max_string: int = 80, log_render_kls: type[FluidLogRender] | None = None, log_time_format: str | Callable[[datetime], Text] = '[%x %X]', markup: bool = False, name: str = 'rich.console', omit_repeated_times: bool = True, rich_tracebacks: bool = False, show_level: bool = True, show_path: bool = True, show_time: bool = True, tracebacks_code_width: int = 88, tracebacks_extra_lines: int = 3, tracebacks_max_frames: int = 100, tracebacks_show_locals: bool = False, tracebacks_suppress: Iterable[str | ModuleType] = (), tracebacks_theme: str | None = None, tracebacks_width: int | None = None, tracebacks_word_wrap: bool = True, **kwargs: object) None[source]

Instantiate class.

Parameters:
  • level – Log level.

  • console – Optional console instance to write logs. Default will use a global console instance writing to stdout.

  • enable_link_path – Enable terminal link of path column to file.

  • highlighter – Highlighter to style log messages, or None to use ReprHighlighter.

  • keywords – List of words to highlight instead of RichHandler.KEYWORDS.

  • locals_max_length – Maximum length of containers before abbreviating, or None for no abbreviation.

  • locals_max_string – Maximum length of string before truncating, or None to disable.

  • log_render_kls – Custom log rendering class. If not provided, will use the one provided by rich.

  • log_time_format – If log_time is enabled, either string for strftime or callable that formats the time.

  • markup – Enable console markup in log messages.

  • name – Name of the handler. Can be used to check for existence.

  • omit_repeated_times – Omit repetition of the same time.

  • rich_tracebacks – Enable rich tracebacks with syntax highlighting and formatting.

  • show_level – Show a column for the level.

  • show_path – Show the path to the original log call.

  • show_time – Show a column for the time.

  • tracebacks_code_width – Number of code characters used to render tracebacks, or None for full width.

  • tracebacks_extra_lines – Additional lines of code to render tracebacks, or None for full width.

  • tracebacks_max_frames – Optional maximum number of frames returned by traceback.

  • tracebacks_show_locals – Enable display of locals in tracebacks.

  • tracebacks_suppress – Optional sequence of modules or paths to exclude from traceback.

  • tracebacks_theme – Override pygments theme used in traceback.

  • tracebacks_width – Number of characters used to render tracebacks, or None for full width.

  • tracebacks_word_wrap – Enable word wrapping of long tracebacks lines.

  • **kwargs – Additional options added to RichHandler that are not explicitly listed here. This is to provide support for future releases without requiring a new release here to support it.

get_level_text(record: LogRecord) Text[source]

Get the level name from the record.

Parameters:

record – LogRecord instance.

Returns:

A tuple of the style and level name.

Return type:

Text

render_message(record: logging.LogRecord, message: str) ConsoleRenderable[source]

Render message text in to Text.

Parameters:
  • record – logging Record.

  • message – String containing log message.

Returns:

Renderable to display log message.

Return type:

ConsoleRenderable

class f_lib.logging.ExtendableHighlighter[source]

Bases: Highlighter

Extendable Highlighter.

highlight(text: Text) None[source]

Highlight rich.text.Text using regular expressions.

Parameters:

text – Text to highlighted.

property highlights: tuple[HighlightTypedDict, ...]

All highlights of this highlighter.

class f_lib.logging.FluidLogRender[source]

Bases: object

Renders log by not using a table and avoiding any wrapping.

__init__(*, show_time: bool = True, show_level: bool = False, show_path: bool = True, time_format: str | Callable[[datetime], Text] = '[%x %X]', omit_repeated_times: bool = True, level_width: int | None = 8) None[source]

Instantiate class.

class f_lib.logging.HighlightTypedDict[source]

Bases: TypedDict

typing.TypedDict for highlights.

Used with f_lib.logging.ExtendableHighlighter.

base_style: str

Base name used for applying styles.

highlights: list[str] | tuple[str, ...]

Regex patterns to highlight.

class f_lib.logging.LogLevel[source]

Bases: IntEnum

Log level enum.

__new__(value)
classmethod from_verbosity(verbosity: int) LogLevel[source]

Determine appropriate log level from verbosity.

Parameters:

verbosity – Requested level of verbosity.

Returns:

A log level based on the table above.

classmethod has_value(value: int) bool[source]

Check if f_lib.logging.LogLevel has a value.

NOTSET = 0

When set on a logger, indicates that ancestor loggers are to be consulted to determine the effective level.

If that still resolves to NOTSET, then all events are logged. When set on a handler, all events are handled.

SPAM = 5

Custom level for spam messages.

DEBUG = 10

Detailed information, typically only of interest to a developer trying to diagnose a problem.

VERBOSE = 15

Custom level between INFO and DEBUG.

Useful where some additional information might be desirable but does not cause full information dumps everywhere.

INFO = 20

Confirmation that things are working as expected.

This is the default level most things will want to set at.

NOTICE = 25

Custom level situated between INFO and WARNING to draw attention without raising concern.

WARNING = 30

An indication that something unexpected happened, or that a problem might occur in the near future (e.g. disk space low).

The software is still working as expected.

SUCCESS = 35

Custom log level used when something good happens.

ERROR = 40

Due to a more serious problem, the software has not been able to perform some function.

CRITICAL = 50

A serious error, indicating that the program itself may be unable to continue running.

FATAL = 50

A serious error, indicating that the program itself may be unable to continue running.

class f_lib.logging.Logger[source]

Bases: Logger

Customized subclass of logging.Logger.

__init__(name: str, level: LogLevel = LogLevel.NOTSET, *, settings: LoggerSettings | None = None) None[source]

Initialize the logger with a name, level, and settings.

classmethod get_logger(name: str, *, markup: bool = True) Self[source]

Return a logger with the specified name, creating it if necessary.

This class method replaces logging.getLogger() to provide the correct logger type, only needing to correct it once. However, this wrapper requires a name to be provided to avoid implicit use of the root logger.

Example

LOGGER = Logger.get_logger(__name__)
LOGGER.info("usage example")
Parameters:
  • name – Name of the logger. It is recommended to use __name__ here in most cases.

  • level – After creating the logger (if needed), set it’s level.

  • markup – Whether to enable rich markup.

Returns:

Custom logger object.

notice(msg: Exception | str, *args: object, exc_info: bool = False, extra: Mapping[str, object] | None = None, **kwargs: Any) None[source]

Log ‘msg % args’ with severity NOTICE.

Parameters:
  • msg – String template or exception to use for the log record.

  • *args – Replacement values for the string template.

  • exc_info – Include exception traceback in the log record.

  • extra – Dictionary to populated additional information in the log record.

  • **kwargs – Arbitrary keyword arguments

success(msg: Exception | str, *args: object, exc_info: bool = False, extra: Mapping[str, object] | None = None, **kwargs: Any) None[source]

Log ‘msg % args’ with severity SUCCESS.

Parameters:
  • msg – String template or exception to use for the log record.

  • *args – Replacement values for the string template.

  • exc_info – Include exception traceback in the log record.

  • extra – Dictionary to populated additional information in the log record.

  • **kwargs – Arbitrary keyword arguments

verbose(msg: Exception | str, *args: object, exc_info: bool = False, extra: Mapping[str, object] | None = None, **kwargs: Any) None[source]

Log ‘msg % args’ with severity VERBOSE.

Parameters:
  • msg – String template or exception to use for the log record.

  • *args – Replacement values for the string template.

  • exc_info – Include exception traceback in the log record.

  • extra – Dictionary to populated additional information in the log record.

  • **kwargs – Arbitrary keyword arguments

settings: LoggerSettings

Custom logger settings.

class f_lib.logging.LoggerSettings[source]

Bases: BaseModel

Logger settings.

markup: bool

Enable rich markup (if available).

class f_lib.logging.PrefixAdaptor[source]

Bases: LoggerAdapter[Logger | PrefixAdaptor]

logging.LoggerAdapter that adds prefixes to messages.

Example

logger = PrefixAdaptor("something", logging.getLogger("example"))
logger.info("my message")
__init__(prefix: str, logger: Logger | PrefixAdaptor, *, extra: Mapping[str, object] | None = None, prefix_template: str = '{prefix}: {msg}') None[source]

Instantiate class.

Parameters:
  • prefix – Message prefix.

  • logger – Logger where the prefixed messages will be sent.

  • extra – Mapping of extra values used during message processing.

  • prefix_template – String that can be used with .format(prefix=<prefix>, msg=<msg>) to produce a dynamic message prefix.

notice(msg: Exception | str, *args: object, exc_info: bool = False, extra: Mapping[str, object] | None = None, **kwargs: Any) None[source]

Delegate a notice call to the underlying logger.

Parameters:
  • msg – String template or exception to use for the log record.

  • *args – Replacement values for the string template.

  • exc_info – Include exception traceback in the log record.

  • extra – Dictionary to populated additional information in the log record.

  • **kwargs – Arbitrary keyword arguments

process(msg: object, kwargs: MutableMapping[str, Any]) tuple[str, MutableMapping[str, object]][source]

Process the message to append the prefix.

Parameters:
  • msg – Message to be prefixed.

  • kwargs – Keyword args for the message.

success(msg: Exception | str, *args: object, exc_info: bool = False, extra: Mapping[str, object] | None = None, **kwargs: Any) None[source]

Delegate a success call to the underlying logger.

Parameters:
  • msg – String template or exception to use for the log record.

  • *args – Replacement values for the string template.

  • exc_info – Include exception traceback in the log record.

  • extra – Dictionary to populated additional information in the log record.

  • **kwargs – Arbitrary keyword arguments

verbose(msg: Exception | str, *args: object, exc_info: bool = False, extra: Mapping[str, object] | None = None, **kwargs: Any) None[source]

Delegate a verbose call to the underlying logger.

Parameters:
  • msg – String template or exception to use for the log record.

  • *args – Replacement values for the string template.

  • exc_info – Include exception traceback in the log record.

  • extra – Dictionary to populated additional information in the log record.

  • **kwargs – Arbitrary keyword arguments

f_lib.logging.setup_logging(*, console: Console, formatter: logging.Formatter | None = None, handler_kls: type[ConsoleHandler] | None = None, highlighter: Highlighter | None = None, level: LogLevel | None = None, logger: logging.Logger, reconfigure: bool = False, settings: LoggingSettings | None = None, tracebacks_suppress: Iterable[ModuleType | str] = ('click',)) None[source]

Set up rich logging.

This function is similar in purpose to logging.basicConfig(). Both setup logging with a lot of optional keyword arguments with logical defaults that should cover most needs.

When using this function, DO NOT add any other handlers to a Logger that would propagate to what is passed to this function. Doing so will result in duplicate log statements. This is intended to be the last or only step when setting up logging (other than setting levels).

Parameters:

Submodules

Subpackages