Version

Quick search

Kivy Logging

By default, Kivy provides a logging system based on the standard Python logging module with several additional features designed to be more convenient. These features include:

  • simplied usage (single instance, simple configuration, works by default)

  • color-coded output on supported terminals

  • output to stderr by default

  • message categorization via colon separation

  • access to log history even if logging is disabled

  • built-in handling of various cross-platform considerations

  • any stray output written to sys.stderr is captured, and stored in the log file as a warning.

These features are configurable via the Config file or environment variables - including falling back to only using the standard Python system.

Logger object

The Kivy Logger class provides a singleton logging.logger instance.

As well as the standard logging levels (debug, info, warning, error and critical), an additional trace level is available.

Example Usage

Use the Logger as you would a standard Python logger.

from kivy.logger import Logger

Logger.info('title: This is a info message.')
Logger.debug('title: This is a debug message.')

try:
    raise Exception('bleh')
except Exception:
    Logger.exception('Something happened!')

The message passed to the logger is split into two parts separated by a colon (:). The first part is used as a title and the second part is used as the message. This way, you can “categorize” your messages easily.

Logger.info('Application: This is a test')

# will appear as

[INFO   ] [Application ] This is a test

You can change the logging level at any time using the setLevel method.

from kivy.logger import Logger, LOG_LEVELS

Logger.setLevel(LOG_LEVELS["debug"])

Changed in version 2.2.0.

Interaction with other logging

The Kivy logging system will, by default, present all log messages sent from any logger - e.g. from third-party libraries.

Additional handlers may be added.

Warning

Handlers that output to sys.stderr may cause loops, as stderr output is reported as a warning log message.

Logger Configuration

Kivy Log Mode

At the highest level, Kivy’s logging system is controlled by an environment variable KIVY_LOG_MODE. It may be given any of three values: KIVY, PYTHON, MIXED

KIVY Mode (default)

In KIVY mode, all Kivy handlers are attached to the root logger, so all log messages in the system are output to the Kivy log files and to the console. Any stray output to sys.stderr is logged as a warning.

If you are writing an entire Kivy app from scratch, this is the most convenient mode.

PYTHON Mode

In PYTHON mode, no handlers are added, and sys.stderr output is not captured. It is left to the client to add appropriate handlers. (If none are added, the logging module will output them to stderr.)

Messages logged with Logger will be propagated to the root logger, from a logger named kivy.

If the Kivy app is part of a much larger project which has its own logging regimen, this is the mode that gives most control.

The kivy.logger file contains a number of logging.handler, logging.formatter, and other helper classes to allow users to adopt the features of Kivy logging that they like, including the stderr redirection.

MIXED Mode

In MIXED mode, handlers are added to the Kivy’s Logger object directly, and propagation is turned off. sys.stderr is not redirected.

Messages logged with Kivy’s Logger will appear in the Kivy log file and output to the Console.

However, messages logged with other Python loggers will not be handled by Kivy handlers. The client will need to add their own.

If you like the features of Kivy Logger, but are writing a Kivy app that relies on third-party libraries that don’t use colon-separation of categorise or depend on the display of the logger name, this mode provides a compromise.

Again, the kivy.logger file contains re-usable logging features that can be used to get the best of both systems.

Config Files

In KIVY and MIXED modes, the logger handlers can be controlled via the Kivy configuration file:

[kivy]
log_level = info
log_enable = 1
log_dir = logs
log_name = kivy_%y-%m-%d_%_.txt
log_maxfiles = 100

More information about the allowed values are described in the kivy.config module.

In addition, the environment variables KIVY_NO_FILELOG and KIVY_NO_CONSOLELOG can be used to turn off the installation of the corresponding handlers.

Logger History

Even if the logger is not enabled, you still have access to the last 100 LogRecords:

from kivy.logger import LoggerHistory

print(LoggerHistory.history)
class kivy.logger.ColonSplittingLogRecord(logrecord)[source]

Bases: logging.LogRecord

Clones an existing logRecord, but reformats the message field if it contains a colon.

New in version 2.2.0.

class kivy.logger.ColoredLogRecord(logrecord)[source]

Bases: logging.LogRecord

Clones an existing logRecord, but reformats the levelname to add color, and the message to add bolding (where indicated by $BOLD and $RESET in the message).

New in version 2.2.0.

class kivy.logger.ConsoleHandler(stream=None)[source]

Bases: logging.StreamHandler

Emits records to a stream (by default, stderr).

However, if the msg starts with “stderr:” it is not formatted, but written straight to the stream.

New in version 2.2.0.

filter(record)[source]

Determine if a record is loggable by consulting all the filters.

The default is to allow the record to be logged; any filter can veto this by returning a false value. If a filter attached to a handler returns a log record instance, then that instance is used in place of the original log record in any further processing of the event by that handler. If a filter returns any other true value, the original log record is used in any further processing of the event by that handler.

If none of the filters return false values, this method returns a log record. If any of the filters return a false value, this method returns a false value.

Changed in version 3.2: Allow filters to be just callables.

Changed in version 3.12: Allow filters to return a LogRecord instead of modifying it in place.

class kivy.logger.FileHandler(level=0)[source]

Bases: logging.Handler

emit(message)[source]

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

purge_logs()[source]

Purge logs which exceed the maximum amount of log files, starting with the oldest creation timestamp (or edit-timestamp on Linux)

class kivy.logger.KivyFormatter(*args, use_color=True, **kwargs)[source]

Bases: logging.Formatter

Split out first field in message marked with a colon, and either apply terminal color codes to the record, or strip out color markup if colored logging is not available.

New in version 2.2.0.

format(record)[source]

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

class kivy.logger.LoggerHistory(level=0)[source]

Bases: logging.Handler

emit(message)[source]

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

flush()[source]

Ensure all logging output has been flushed.

This version does nothing and is intended to be implemented by subclasses.

class kivy.logger.ProcessingStream(channel, func)[source]

Bases: builtins.object

Stream-like object that takes each completed line written to it, adds a given prefix, and applies the given function to it.

New in version 2.2.0.

class kivy.logger.UncoloredLogRecord(logrecord)[source]

Bases: logging.LogRecord

Clones an existing logRecord, but reformats the message to remove $BOLD/$RESET markup.

New in version 2.2.0.

kivy.logger.add_kivy_handlers(logger)[source]

Add Kivy-specific handlers to a logger.

New in version 2.2.0.

kivy.logger.is_color_terminal()[source]

Detect whether the environment supports color codes in output.

New in version 2.2.0.