Several learning connections:
Official Python Link:
Https://docs.python.org/3.4/library/logging.html?highlight=logging
Translation (2.3 version only)
http://crazier9527.iteye.com/blog/290018
Another person's summary:
http://blog.csdn.net/fxjtoday/article/details/6307285
Best to understand, write the best:
Http://bbs.chinaunix.net/thread-3590256-1-1.html
My study summary is based on http://bbs.chinaunix.net/thread-3590256-1-1.html
Take a simple log system as an example to illustrate:
Goal: Create a log system that can not only output information to the console, but also output it to a file.
?
1234567891011121314151617181920212223242526272829 |
#import logging包
import logging
#创建一个logger,getLogger的参数是logger的名字
logger
=
logging.getLogger(
‘lylogger‘
)
#设置logger的等级,大于等于这个等级的信息会被输出,其他会被忽略
logger.setLevel(logging.DEBUG)
#Handler是英文翻译为处理者,用于输出到不同的地方:Stream为控制台,File为文件
#以下创建的是输出到文件的handler,并把等级设为DEBUG
fh
=
logging.FileHandler(
‘test.log‘
)
fh.setLevel(logging.DEBUG)
#以下创建的是输出到控制台的handler,并把等级设为DEBUG
sh
=
logging.StreamHandler()
sh.setLevel(logging.DEBUG)
#下面指定了handler的信息输出格式,其中asctime,name,levelname,message都是logging的关键字
formatter
=
logging.Formatter(
‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘
)
fh.setFormatter(formatter)
sh.setFormatter(formatter)
#把Handler加入到logger中,可理解为给处理者在logger中安排了职位
logger.addHandler(fh)
logger.addHandler(sh)
#记录一条为”Hello,Arsenal!”的info日志信息
logger.info(
‘Hello,Arsenal!‘
)
print
(
"process end!"
)
|
Attention:
Logger.setlevel (LVL)
The level of the logger is set to the following levels:
NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL
If the Looger level is set to info, then logs less than the info level are not output, and logs that are greater than or equal to the info level are output
Study Questions
Run the following log system to find errors and correct them.
?
1234567891011121314151617181920 |
import
logging
logger
=
logging.getLogger(
‘lylogger‘
)
logger.setLevel(logging.DEBUG)
fh
=
logging.FileHandler(
‘test.log‘
)
fh.setLevel(logging.DEBUG)
sh
=
logging.StreamHandler()
sh.setLevel(logging.DEBUG)
formatter
=
logging.Formatter(
‘%(asctime)s - %(name)s - %(levlename)s - %(message)s‘
)
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(sh)
logger.info(
‘Hello,Arsenal!‘
)
print
(
"process end!"
)
|
Answer:
By looking at the error message, locate the Key:levlename, and learn that the keyword LevelName is incorrectly written.
How to use Python's logging module