import logging # introduce logging modular
# Print the information to the console
logging.debug("debug")
logging.info("info")
logging.warning("warning")
logging.error("error")
logging.critical("critical")
The echo :
As you can see on the top, only the last three can be printed
Default generated root logger Of level yes logging.WARNING, Below this level, it will not output
Rank sort :CRITICAL > ERROR > WARNING > INFO > DEBUG
debug : Print all the logs , Details , It's usually only a diagnostic problem
info : Print info,warning,error,critical Level of logging , Make sure everything works as expected
warning : Print warning,error,critical Level of logging , A sign that , Something unexpected happened , Or show some problems in the near future ( for example . Low disk space ”), The software works as expected
error : Print error,critical Level of logging , More serious problem , The software doesn't perform some functions
critical : Print critical Level , A serious mistake , This indicates that the program itself may not continue to run
Now , If you need to display below WARNING Level content , Can be introduced NOTSET Level :
import logging # introduce logging modular
logging.basicConfig(level=logging.NOTSET) # Set the log level
logging.debug("print all levels log")
The echo :
Logging.Formatter: This class configures the format of the log , Customize the date and time in it , The output log will display the content according to the set format .
Logging.Logger:Logger yes Logging The body of the module , To carry out the following three tasks :
Common functions are :
import logging # introduce logging modular
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s-%(filename)s%(funcName)s(%(lineno)d)[%(thread)d]-[%(levelname)s]%(message)s') # Since the level in the basic log configuration is set to DEBUG, So the print information will be displayed on the console
log=logging.getLogger()
log.debug("debug")
log.info("info")
log.warning("warnign")
log.error("error")
log.critical("critical")
The above code passes logging.basicConfig Function to configure the log level and log content output format ; Because the level is DEBUG, So will DEBUG Information above the level is output and displayed on the console .
The echo :
import logging # introduce logging modular
import os.path
import time
# First step , Create a logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Log Grade master switch
# The second step , Create a handler, For writing log files
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
log_path = os.path.dirname(os.getcwd()) + '/Logs/'
log_name = log_path + rq + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG) # Output to file Of log Level switch
# The third step , Definition handler The output format of
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
# Step four , take logger Add to handler Inside
logger.addHandler(fh)
# journal
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')
# Just insert a handler Output to console :
# Create a handler, For output to console
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING) # Output to console Of log Level switch
ch.setFormatter(formatter)
logger.addHandler(ch)
%(levelno)s: Print log level values
%(levelname)s: Print log level name
%(pathname)s: Print the path of the currently executing program , In fact, that is sys.argv[0]
%(filename)s: Print the name of the currently executing program
%(funcName)s: Print the current function of the log
%(lineno)d: Print the current line number of the log
%(asctime)s: Time to print the log
%(thread)d: Print thread ID
%(threadName)s: Print thread name
%(process)d: Printing process ID
%(message)s: Print log information
import os.path
import time
import logging
# Create a logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Log Grade master switch
# Create a handler, For writing log files
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
log_path = os.path.dirname(os.getcwd()) + '/Logs/'
log_name = log_path + rq + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG) # Output to file Of log Level switch
# Definition handler The output format of
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
# Use logger.XX To record errors , there "error" It can be modified according to the required level
try:
open('/path/to/does/not/exist', 'rb')
except (SystemExit, KeyboardInterrupt):
raise
except Exception, e:
logger.error('Failed to open file', exc_info=True)
If you need to report no errors in the log , Record only , Can be exc_info=False, Echo as follows :
#coding:utf-8
import logging
import time
import re
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler
def backroll():
# Log print format
log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s'
formatter = logging.Formatter(log_fmt)
# establish TimedRotatingFileHandler object
log_file_handler = TimedRotatingFileHandler(filename="ds_update", when="M", interval=2, backupCount=2)
#log_file_handler.suffix = "%Y-%m-%d_%H-%M.log"
#log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")
log_file_handler.setFormatter(formatter)
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
log.addHandler(log_file_handler)
# Circular printing log
log_content = "test log"
count = 0
while count < 30:
log.error(log_content)
time.sleep(20)
count = count + 1
log.removeHandler(log_file_handler)
if __name__ == "__main__":
backroll()
filename: Log file name prefix;
when: Is a string , The basic unit used to describe the rolling period , The values and meanings of a string are as follows :
“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight
interval: Rolling cycle , The unit has when Appoint , such as :when=’D’,interval=1, A log file is generated every day
backupCount: Indicates the number of reserved log files