Home  >  Article  >  Backend Development  >  Python Logging Basics - A Simple Guide

Python Logging Basics - A Simple Guide

PHPz
PHPzforward
2023-09-07 19:49:021386browse

Python日志基础 - 简易指南

Logging is used to track events that occur while the software is running. Using logging, you can add logging calls in your code to indicate that certain events have occurred. This way you can learn about errors, messages, warnings, and more.

Log function

For logging, different functions are provided. You must decide when to use logging. For this purpose, Python provides the following:

  • ogging.info() - Reports events that occur during normal operation of the program.

  • logging.warning() - Issue a warning about a specific runtime event.

  • logging.error() − Report error suppression without raising an exception.

The standard severity levels for events are as follows, in order of increasing severity. These levels include DEBUG, INFO, WARNING, ERROR, CRITICAL −

  • DEBUG − This is detailed information that is usually only of interest when diagnosing a problem.

  • INFO − Used when confirming that something is working perfectly.

  • Warning - This is the default level. It indicates that something unexpected happened or indicates that there will be problems in the future, such as insufficient memory, insufficient disk space, etc.

  • Error - The software is unable to perform certain functions due to a more serious problem.

  • CRITICAL − A critical error indicating that the program itself may not be able to continue running.

Logging example

Let’s look at a simple example -

import logging

# Prints a message to the console
logging.warning('Watch out!')

Output

WARNING:root:Watch out!

Default is warning

As mentioned above, warning is the default level. If you try to print other levels, it won't be printed -

import logging

# Prints a message to the console
logging.warning('Watch out!')

# This won't get printed
logging.info('Just for demo!')

Output

WARNING:root:Watch out!

Record variable data

To log variable data, you need to use the format string of the event description message and append the variable data as a parameter.

import logging
logging.warning('%s before you %s', 'Look', 'leap!')

Output

WARNING:root:Look before you leap!

Add date/time to log message

When we talk about logging, the key is to include the date/time of the event. This is mainly to record when warnings or errors occur −

import logging

logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is the Log Time.')

Output

2022-09-19 17:42:47,365 is the Log Time.

The above is the detailed content of Python Logging Basics - A Simple Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete