Logging in Python

In this article, we will learn about logging in Python and various stages in protection and security.

First of all, we need to import the logging module, followed by using the logger to checj=k the current status and log messages. We are having 5 severity levels namely −

  • Warning
  • Info
  • Error
  • Critical
  • Debug

The logging module allows us to get started directly without setting up the configuration manually.


Import logging
logging.debug('a debug message')
logging.info('an info message')
logging.warning('a warning message')
logging.error('an error message')
logging.critical('a critical message')


WARNING:root: a warning message
ERROR:root: an error message
CRITICAL:root: a critical message

As we didn’t set the configurations, by default the logging and info messages aren’t logged. To make them noticeable we need to set the configuration manually.

Now let’s see how we can implement the basic configurations.

By the help of level parameter − we can set which level of log messages must be recorded.


Import logging
logging.debug('This gets logged')


DEBUG:root: This gets logged

By using this statement all statements above the debug level get recorded.

Now switching to file logging over console logging.


Import logging
logging.basicConfig(filename='app.log', filemode='w',
format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This gets logged to a file')


root - ERROR - This gets logged to a file

Here the file mode is said to write only so we have rights to rewrite the contents of the file. By default this configuration it opens in append mode only.


In this article, we learnt about logging in Python and various levels of logging available to us.

Updated on: 29-Aug-2019


Kickstart Your Career

Get certified by completing the course

Get Started