Logging in Python

PythonServer Side ProgrammingProgramming

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.

Example

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')

Output

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.

Example

Import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This gets logged')

Output

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.

Example

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

Output

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.

Conclusion

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

raja
Published on 29-Aug-2019 06:23:13
Advertisements