Logs can help us monitor the running state of programs . Through the log we can see if the program raises any warnings or errors . We record time stamps 、 news 、 Stack and so on .
Before using any logging function in the program , You need to explicitly import Python Of logging library .
import logging
# then some logging statement(s)
Here are Python in logging An example of library usage .
import logging
logging.warning("This is a simple logging example")
Execution and output :
Next let's learn about the different levels of logging 、 How to set the log level and so on .
Use Python Of logging modular , You can try it out 、 Information 、 Warning 、 error 、 Serious errors are recorded in the log file , Instead of just echoing to the console .
To record data into a file , Use logging The basic configuration of , Send the address of the log file to filename Parameters . If the file does not exist ,Python The system will create a new file , So you should assign the new and write permissions of the file in the directory where the file is located to start the Python Users of the program . Use logging Modular basicConfig() Function to set filename The basic syntax for parameters is as follows .
logging.basicConfig(filename="mylog.log")
You can rewrite the file name according to your own needs .
In the next example , We will use basicConfig() Function settings logging To configure , Log the message to a message named mylog.log External files for . If the full path is not provided , This file will be created in the program's execution directory .
# Python Example for Logging Messages to Log File
import logging
logging.basicConfig(filename="mylog.log")
logging.warning("This is a WARNING message")
logging.error("This is an ERROR message")
logging.critical("This is a CRITICAL message")
Execution and output :
Check the current program directory , New documents found mylog.log Generate :
View its contents :
so logging The message has been appended to the file .
This example is improved on the previous section , Used handler To handle the writing of log files .
# Python Example for Logging Messages to Log File using Handler
import logging
# create a logger
logger = logging.getLogger("mylogger")
handler = logging.FileHandler("mylog.log")
logger.addHandler(handler)
logger.warning("This is a WARNING message by handler")
logger.error("This is an ERROR message by handler")
logger.critical("This is a CRITICAL message by handler")
Execution and output :
Check the log file again :
logging The message has been appended to the log file , But the format is slightly different from that in the previous section .
To use logging Print a row DEBUG Level of logging ,
When logging Level set to DEBUG in the future ,logging It will put DEBUG Line to print to console or log file .
When you set logging The level of INFO、WARNING、ERROR or CRITICAL when ,DEBUG The line will not be written to the log file .
logging The order of rank is :
DEBUG < INFO < WARNING < ERROR < CRITICAL
In this example , We will import logging modular , Set the log level to DEBUG, And then use debug() Method to print a DEBUG That's ok .
# Example to log DEBUG lines
import logging
# create a logger
logger = logging.getLogger("mylogger")
# set logging level
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler("mylog.log")
# create a logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# write a debug message
logger.debug("This is a debug message")
Check... After executing the program mylog.log:
You can also be right handler Filter to print only DEBUG Line to log file .
# Example to log only DEBUG Lines using Python Logger
import logging
class MyFilter(object):
def __init__(self, level):
self.__level = level
def filter(self, logRecord):
return logRecord.levelno <= self.__level
# create a logger
logger = logging.getLogger("mylogger")
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler("mylog.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
# set filter to log only DEBUG lines
handler.addFilter(MyFilter(logging.DEBUG))
logger.addHandler(handler)
# write a debug line to log file
logger.debug("This is a DEBUG message")
logger.info("This is a INFO message")
logger.warning("This is a WARNING message")
logger.error("This is an ERROR message")
logger.critical("This is a CRITICAL message")
Check... After executing the program mylog.log:
To use Python logging Print INFO That's ok ,
When logging Level set to INFO or DEBUG in the future ,logging It will put INFO Line to print to console or log file .
When you set logging The level of WARNING、ERROR or CRITICAL when ,INFO The line will not be written to the log file .
logging The order of rank is :
DEBUG < INFO < WARNING < ERROR < CRITICAL
In this example , We will import logging modular , Set the log level to INFO, And then use info() Method to print a INFO That's ok .
# Example to log INFO lines
import logging
# create a logger
logger = logging.getLogger("mylogger")
# set logging level
logger.setLevel(logging.INFO)
handler = logging.FileHandler("mylog.log")
# create a logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# write a info message
logger.info("This is a INFO message")
Check... After executing the program mylog.log:
You can also be right handler Filter to print only INFO Line to log file .
# Example to log only INFO Lines using Python Logger
import logging
class MyFilter(object):
def __init__(self, level):
self.__level = level
def filter(self, logRecord):
return logRecord.levelno == self.__level
# create a logger
logger = logging.getLogger("mylogger")
logger.setLevel(logging.INFO)
handler = logging.FileHandler("mylog.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
# set filter to log only INFO lines
handler.addFilter(MyFilter(logging.INFO))
logger.addHandler(handler)
# write a INFO line to log file
logger.debug("This is a DEBUG message")
logger.info("This is a INFO message")
logger.warning("This is a WARNING message")
logger.error("This is an ERROR message")
logger.critical("This is a CRITICAL message")
Check... After executing the program mylog.log:
To use Python logging Print WARNING That's ok ,
When logging Level set to WARNING、INFO or DEBUG in the future ,logging It will put WARNING Line to print to console or log file .
When you set logging The level of ERROR or CRITICAL when ,WARNING The line will not be written to the log file .
logging The order of rank is :
DEBUG < INFO < WARNING < ERROR < CRITICAL
In this example , We will import logging modular , Set the log level to WARNING, And then use warning() Method to print a WARNING That's ok .
# Example to log WARNING lines
import logging
# create a logger
logger = logging.getLogger("mylogger")
# set logging level
logger.setLevel(logging.WARNING)
handler = logging.FileHandler("mylog.log")
# create a logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# write a warning message
logger.warning("This is a WARNING message")
Check... After executing the program mylog.log:
You can also be right handler Filter to print only WARNING Line to log file .
# Example to log only WARNING Lines using Python Logger
import logging
class MyFilter(object):
def __init__(self, level):
self.__level = level
def filter(self, logRecord):
return logRecord.levelno == self.__level
# create a logger
logger = logging.getLogger("mylogger")
logger.setLevel(logging.WARNING)
handler = logging.FileHandler("mylog.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
# set filter to log only WARNING lines
handler.addFilter(MyFilter(logging.WARNING))
logger.addHandler(handler)
# write a WARNING line to log file
logger.debug("This is a DEBUG message")
logger.info("This is a INFO message")
logger.warning("This is a WARNING message")
logger.error("This is an ERROR message")
logger.critical("This is a CRITICAL message")
Check... After executing the program mylog.log:
To use Python logging Print ERROR That's ok ,
When logging Level set to ERROR、WARNING、INFO or DEBUG in the future ,logging It will put ERROR Line to print to console or log file .
When you set logging The level of CRITICAL when ,WARNING Lines or lower will not be written to the log file .
logging The order of rank is :
DEBUG < INFO < WARNING < ERROR < CRITICAL
In this example , We will import logging modular , Set the log level to ERROR, And then use warning() Method to print a ERROR That's ok .
# Example to log ERROR lines
import logging
# create a logger
logger = logging.getLogger("mylogger")
# set logging level
logger.setLevel(logging.ERROR)
handler = logging.FileHandler("mylog.log")
# create a logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# write an error message
logger.error("This is an ERROR message")
Check... After executing the program mylog.log:
You can also be right handler Filter to print only ERROR Line to log file .
# Example to log only ERROR Lines using Python Logger
import logging
class MyFilter(object):
def __init__(self, level):
self.__level = level
def filter(self, logRecord):
return logRecord.levelno == self.__level
# create a logger
logger = logging.getLogger("mylogger")
logger.setLevel(logging.ERROR)
handler = logging.FileHandler("mylog.log")
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
# set filter to log only ERROR lines
handler.addFilter(MyFilter(logging.ERROR))
logger.addHandler(handler)
# write a ERROR line to log file
logger.debug("This is a DEBUG message")
logger.info("This is a INFO message")
logger.warning("This is a WARNING message")
logger.error("This is an ERROR message")
logger.critical("This is a CRITICAL message")
Check... After executing the program mylog.log:
To use Python logging Print CRITICAL That's ok ,
When logging Level set to CRITICAL、ERROR、WARNING、INFO or DEBUG in the future ,logging It will put CRITICAL Line to print to console or log file .
When you set logging The level of CRITICAL when ,ERROR Lines or lower will not be written to the log file .
logging The order of rank is :
DEBUG < INFO < WARNING < ERROR < CRITICAL
In this example , We will import logging modular , Set the log level to CRITICAL, And then use critical() Method to print a CRITICAL That's ok .
# Example to log CRITICAL lines
import logging
# create a logger
logger = logging.getLogger("mylogger")
# set logging level
logger.setLevel(logging.CRITICAL)
handler = logging.FileHandler("mylog.log")
# create a logging format
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# write an CRITICAL message
logger.critical("This is a CRITICAL message")
Check... After executing the program mylog.log: