DEV Community

Cover image for Basic Logging with Python
Ruan Bekker
Ruan Bekker

Posted on

Basic Logging with Python

I'm trying to force myself to move away from using the print() function as I'm pretty much using print all the time to cater for logging, and using the logging package instead.

This is a basic example of using logging in a basic python app:

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s %(message)s",
    handlers=[
        logging.StreamHandler()
    ]
)

messagestring = {'info': 'info message', 'warn': 'this is a warning', 'err': 'this is a error'}

logger = logging.getLogger('thisapp')
logger.info('message: {}'.format(messagestring['info']))
logger.warning('message: {}'.format(messagestring['warn']))
logger.error('message: {}'.format(messagestring['err']))
Enter fullscreen mode Exit fullscreen mode

When running this example, this is the output that you will see:

$ python app.py
2021-07-19 13:07:43,647 [INFO] thisapp message: info message
2021-07-19 13:07:43,647 [WARNING] thisapp message: this is a warning
2021-07-19 13:07:43,647 [ERROR] thisapp message: this is a error
Enter fullscreen mode Exit fullscreen mode

More more info on this package, see it's documentation:

Thanks for reading, if you like my content, check out my website or follow me at @ruanbekker on Twitter.

Top comments (1)

Collapse
 
thoroc profile image
thoroc

Seriously consider using Loguru instead ;)

loguru.readthedocs.io/en/stable/