python notes -- logging of built-in modules

logging module                                                                                                                           

As the name implies, it is used for program log output. You can set the log level, format, output method, etc. The basic usage is as follows:


1、logging.basicConfig方式

    Simple configuration, you can only choose to output to the screen or output to a file, but not at the same time. E.g:

#-*- coding:utf-8 -*-
#Can only choose to output to screen or file
import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a,%d %b %Y %H:%M:%S',
                    filename='test.log',
                    filemode='a')
'''
parameter:
level: specifies the log level of the output
format: Specifies the log format, including:
    asctime: time
    filename: The name of the file to which the log belongs
    lineno: the line number of the log corresponding code in the attribution file
    levelname: day to the lowest level, if not specified, the default is warning
    message: the specific log content,
datefmt: Specify a specific time format, if not specified, asctime will use the default format, such as: 2018-05-05 22:07:30,578 
filename: specifies the name of the log file, which can carry a specific path. If this parameter is not specified, the log is output to the screen
filemode: specifies the log writing mode, the default is 'a' for appending, and it can be specified as 'w' for overwriting
'''
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

The above example outputs the log to the test.log file, the content:

Sat,05 May 2018 22:25:14 2.py[line:22] DEBUG debug message
Sat,05 May 2018 22:25:14 2.py[line:23] INFO info message
Sat,05 May 2018 22:25:14 2.py[line:24] WARNING warning message
Sat,05 May 2018 22:25:14 2.py[line:25] ERROR error message
Sat,05 May 2018 22:25:14 2.py[line:26] CRITICAL critical message

If you only need to output the log to the screen, you only need to comment out the lines filename='test.log' and filemode='a'.


2. logging.getLogger method

    Complete configuration, you can output to screen or file individually or simultaneously. E.g:

#-*- coding:utf-8 -*-
#Log output is more flexible and can be output to the screen and file separately or at the same time
import logging

#Create a logger object
logger=logging.getLogger()

#Create a file output stream handler for writing to the log file
fm=logging.FileHandler('test1.log')

#Create another standard output stream handler for output to the screen
pm=logging.StreamHandler()

#Create a log format object
formatter=logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')

#Add log format for two handlers
fm.setFormatter(formatter)
pm.setFormatter(formatter)

#Add handler for logger object
logger.addHandler(fm)
logger.addHandler(pm)

#Set the output log level, by default only output above warning
logger.setLevel(logging.DEBUG)

logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')

In the above example, the log is output to the screen and the test1.log file at the same time, the content:

2018-05-05 22:32:52,800 3.py[line:28] DEBUG debug message
2018-05-05 22:32:52,800 3.py[line:29] INFO info message
2018-05-05 22:32:52,800 3.py[line:30] WARNING warning message
2018-05-05 22:32:52,800 3.py[line:31] ERROR error message
2018-05-05 22:32:52,800 3.py[line:32] CRITICAL critical message

logger.addHandler() determines the direction of log output. If it is only output to one side, you can comment out another line.


3. Specific application

#!/usr/local/python-3.4/bin/python3.4
#-*- coding:utf-8 -*-
import urllib.request
import time
import logging
#Here is used to request a url and return the status code
my_url='http://172.16.1.20:8080/bizmon/BIZServlet?BizCode=DX0001&BatchId=%s' %(int(time.time()))
def url_request():
    url_response=urllib.request.urlopen(my_url)
    url_code=url_response.code
    return url_code
#define your own log function
def get_log():
    logger=logging.getLogger()
    fh=logging.FileHandler('test.log')
    ph=logging.StreamHandler()
    formatter=logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    # logger.addHandler(ph)
    logger.setLevel(logging.INFO)
    return logger

if __name__ == "__main__":
    my_log=get_log()
    try:
        code=url_request()
    except Exception:
        my_log.error("%s request failed!"%(my_url),exc_info=True) #Capture the exception and output it to the log
    else:
        my_log.info("%s request successful! code is %s"%(my_url,code))    #正常日志

Log content:

2018-05-07 19:41:41,575 16.py[line:28] ERROR http://172.16.1.20:8080/bizmon/BIZServlet?BizCode=DX0001&BatchId=1525693301 request failed!
Traceback (most recent call last):
  File "C:/Users/Administrator/PycharmProjects/first/16.py", line 26, in <module>
    code=url_request()
  File "C:/Users/Administrator/PycharmProjects/first/16.py", line 8, in url_request
    url_response=urllib.request.urlopen(my_url)
  File "C:\Python3.6\lib\urllib\request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python3.6\lib\urllib\request.py", line 532, in open
    response = meth(req, response)
  File "C:\Python3.6\lib\urllib\request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python3.6\lib\urllib\request.py", line 570, in error
    return self._call_chain(*args)
  File "C:\Python3.6\lib\urllib\request.py", line 504, in _call_chain
    result = func(*args)
  File "C:\Python3.6\lib\urllib\request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 500: Internal Server Error

When catching an exception,

my_log.error("%s request failed!"%(my_url),exc_info=True)也可写成:my_log.exception("%s request failed!"%(my_url))


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325377032&siteId=291194637