logzero code examples


These Python logzero examples will show you how to use the logzero python package in your project to perform logging.

Here are six standalone code snippets demonstrating how to use the logzero library:

Basic logging with logzero

from logzero import logger

logger.debug("This is a debug message")"This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")

Logging to a file with logzero

from logzero import logger, logfile

logfile("/path/to/logfile.log")"This message will be logged to the file")

JSON logging with logzero

import logzero
from logzero import logger

logzero.json()"This message will be logged in JSON format")


Now lets dive deeper into some more specific code examples.

Log file rotation

Here is a logzero code example showing how to setup the built-in log file rotatation feature. The logfile will rotate when it reaches 1 million bytes (1e6), keeping a maximum of 5 old logfiles as backup.

import logzero
from logzero import logger

# rotate logfile when it reaches 3MB, keep a total of 5 log files
logzero.logfile("/tmp/rotating-logfile.log", maxBytes=3e6, backupCount=5)

# log messages"This log message goes to the console and the logfile")

Color console logging

logzero support colorized logging to the console terminal. Here is a demo illustrating what colors are output for each logging level debug,info,warn,error.

from logzero import logger

logger.debug("hello, this a debug message")"this is an info message")
logger.warning("this is a warning message")
logger.error("this is an error message")


Define a custom formatter

logzero allows you to easily define a custom formatter for your application’s logging needs. See LogRecord attributes for a full list of supported variables.

import logzero
from logzero import logger

log_format = '%(color)s[%(levelname)1.1s %(levelname)s %(asctime)s PID:%(process)d %(filename)s:%(lineno)d]%(end_color)s %(message)s'
formatter = logzero.LogFormatter(fmt=log_format)
logzero.formatter(formatter)"test log output")
logger.warning("test warning log output")
logger.error("test error log output")
logger.debug("test debug log output")


With just a few lines of code, you can add flexible logging with support for popular logging formats such as *json logging to your python project. The best part about it is that logzero has NO additional python package dependencies!

About logzero

logzero - Robust and effective logging for Python 2 and 3, zero dependencies.