Simplify Python Logging with Loguru

Have you ever found yourself using print() instead of a proper logger due to the hassle of setup?

With Loguru, a single import is all you need to begin logging with pre-configured color and format settings.

Below is an example of how to use the standard Python logging library and Loguru to log messages at different levels.

Standard Python Logging Library

import logging

logging.basicConfig(format='%(asctime)s | %(levelname)s | %(module)s:%(funcName)s:%(lineno)d | %(message)s', level=logging.DEBUG)

def main():
    logging.debug('This is a debug message')
    logging.info('This is an info message')
    logging.warning('This is a warning message')
    logging.error('This is an error message')
    logging.critical('This is a critical message')

if __name__ == '__main__':
    main()

Output:

2023-03-13 08:46:30,802 | DEBUG | logging_example:main:6 | This is a debug message
2023-03-13 08:46:30,802 | INFO | logging_example:main:7 | This is an info message
2023-03-13 08:46:30,802 | WARNING | logging_example:main:8 | This is a warning message
2023-03-13 08:46:30,802 | ERROR | logging_example:main:9 | This is an error message
2023-03-13 08:46:30,802 | CRITICAL | logging_example:main:10 | This is a critical message

Loguru

from loguru import logger

def main():
    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")
    logger.critical("This is a critical message")

if __name__ == '__main__':
    main()

Output:

As you can see, Loguru requires minimal setup and configuration, making it easy to get started with logging right away. With Loguru, you can focus on writing your application code instead of spending time configuring your logger.

Loguru also offers other features such as descriptive exceptions, lazy evaluation, asynchronous logging, and more.

Link to loguru.

Related Posts

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran