官术网_书友最值得收藏!

How it works…

Let's now learn to log results. After our imports, we create our logger object by initializing an instance using the script's name represented by the __file__ attribute. With our logging object initiated, we will set the level and specify various formatters and handlers for this script. The formatters provide the flexibility to define what fields will be displayed for each message, including timestamps, function name, and the message level. The format strings follow the standards of Python string formatting, meaning we can specify padding for the following strings:

from __future__ import print_function
import logging
import sys

logger = logging.getLogger(__file__)
logger.setLevel(logging.DEBUG)

msg_fmt = logging.Formatter("%(asctime)-15s %(funcName)-20s"
"%(levelname)-8s %(message)s")

The handlers allow us to specify where the log message should be recorded, including a log file, standard output (console), or standard error. In the following example, we use the standard output for our stream handler and the script's name with the .log extension for the file handler. Lastly, we register these handlers with our logger object:

strhndl = logging.StreamHandler(sys.stdout)
strhndl.setFormatter(fmt=msg_fmt)

fhndl = logging.FileHandler(__file__ + ".log", mode='a')
fhndl.setFormatter(fmt=msg_fmt)

logger.addHandler(strhndl)
logger.addHandler(fhndl)

The logging library by default uses the following levels in increasing order of severity: NOTSET, DEBUG, INFORMATION, WARNING, ERROR, and CRITICAL. To showcase some of the features of the format string, we will log a few types of messages from functions:

logger.info("information message")
logger.debug("debug message")


def function_one():
logger.warning("warning message")


def function_two():
logger.error("error message")


function_one()
function_two()

When we execute this code, we can see the following message information from the invocation of the script. Inspection of the generated log file matches what was recorded in the console:

主站蜘蛛池模板: 银川市| 昔阳县| 开原市| 平昌县| 新津县| 高台县| 北川| 苍南县| 凭祥市| 景泰县| 阿尔山市| 瑞昌市| 咸宁市| 沐川县| 华坪县| 买车| 肃南| 大渡口区| 平远县| 和硕县| 镇坪县| 肇庆市| 固阳县| 昭苏县| 潮安县| 左权县| 永顺县| 承德县| 谢通门县| 漳州市| 华阴市| 客服| 启东市| 黎平县| 襄城县| 横山县| 义乌市| 莱阳市| 舟曲县| 兴化市| 嘉鱼县|