Contents

logzero code examples

0

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")
logger.info("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")
logger.info("This message will be logged to the file")

JSON logging with logzero

import logzero
from logzero import logger

logzero.json()

logger.info("This message will be logged in JSON format")

/code/logzero-code-examples/logzero-json-logging-output.webp

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
logger.info("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")
logger.info("this is an info message")
logger.warning("this is a warning message")
logger.error("this is an error message")

/code/logzero-code-examples/logzero.color-terminal-output.webp


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)
logger.info("test log output")
logger.warning("test warning log output")
logger.error("test error log output")
logger.debug("test debug log output")

/code/logzero-code-examples/logzero.logformatter-example.webp


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.