欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python logging模块学习笔记

程序员文章站 2022-06-12 21:45:18
模块级函数 logging.getlogger([name]):返回一个logger对象,如果没有指定名字将返回root loggerlogging.debug()、lo...

模块级函数

logging.getlogger([name]):返回一个logger对象,如果没有指定名字将返回root logger
logging.debug()、logging.info()、logging.warning()、logging.error()、logging.critical():设定root logger的日志级别
logging.basicconfig():用默认formatter为日志系统建立一个streamhandler,设置基础配置并加到root logger中

示例:logging_level_example.py

复制代码 代码如下:

import logging
import sys

levels = {'debug': logging.debug,
          'info': logging.info,
          'warning': logging.warning,
          'error': logging.error,
          'critical': logging.critical}

if len(sys.argv) > 1:
    level_name = sys.argv[1]
    level = levels.get(level_name, logging.notset)
    logging.basicconfig(level=level)

logging.debug('this is a debug message')
logging.info('this is an info message')
logging.warning('this is a warning message')
logging.error('this is an error message')
logging.critical('this is a critical error message')

输出:
复制代码 代码如下:

$ python logging_level_example.py debug
debug:root:this is a debug message
info:root:this is an info message
warning:root:this is a warning message
error:root:this is an error message
critical:root:this is a critical error message

$ python logging_level_example.py info
info:root:this is an info message
warning:root:this is a warning message
error:root:this is an error message
critical:root:this is a critical error message

loggers

logger.setlevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高
logger.addfilter(filt)、logger.removefilter(filt):添加或删除指定的filter
logger.addhandler(hdlr)、logger.removehandler(hdlr):增加或删除指定的handler
logger.debug()、logger.info()、logger.warning()、logger.error()、logger.critical():可以设置的日志级别

示例:simple_logging_module.py

复制代码 代码如下:

import logging

# create logger
logger = logging.getlogger("simple_example")
logger.setlevel(logging.debug)

# create console handler and set level to debug
ch = logging.streamhandler()
ch.setlevel(logging.debug)

# create formatter
formatter = logging.formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")

# add formatter to ch
ch.setformatter(formatter)

# add ch to logger
logger.addhandler(ch)

# "application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")

输出:
复制代码 代码如下:

$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - debug - debug message
2005-03-19 15:10:26,620 - simple_example - info - info message
2005-03-19 15:10:26,695 - simple_example - warning - warn message
2005-03-19 15:10:26,697 - simple_example - error - error message
2005-03-19 15:10:26,773 - simple_example - critical - critical message

handlers

handler对象负责发送相关的信息到指定目的地。可以通过addhandler()方法添加多个多handler
handler.setlevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
handler.setformatter():给这个handler选择一个格式
handler.addfilter(filt)、handler.removefilter(filt):新增或删除一个filter对象

formatters

formatter对象设置日志信息最后的规则、结构和内容,默认的时间格式为%y-%m-%d %h:%m:%s,下面是formatter常用的一些信息

%(name)s

logger的名字

%(levelno)s

数字形式的日志级别

%(levelname)s

文本形式的日志级别

%(pathname)s

调用日志输出函数的模块的完整路径名,可能没有

%(filename)s

调用日志输出函数的模块的文件名

%(module)s

调用日志输出函数的模块名

%(funcname)s

调用日志输出函数的函数名

%(lineno)d

调用日志输出函数的语句所在的代码行

%(created)f

当前时间,用unix标准的表示时间的浮 点数表示

%(relativecreated)d

输出日志信息时的,自logger创建以 来的毫秒数

%(asctime)s

字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒

%(thread)d

线程id。可能没有

%(threadname)s

线程名。可能没有

%(process)d

进程id。可能没有

%(message)s

用户输出的消息


最后来个完整例子:

复制代码 代码如下:

import logging

# set up logging to file - see previous section for more details
logging.basicconfig(level=logging.debug,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %h:%m',
                    filename='/temp/myapp.log',
                    filemode='w')
# define a handler which writes info messages or higher to the sys.stderr
console = logging.streamhandler()
console.setlevel(logging.info)
# set a format which is simpler for console use
formatter = logging.formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setformatter(formatter)
# add the handler to the root logger
logging.getlogger('').addhandler(console)

# now, we can log to the root logger, or any other logger. first the root...
logging.info('jackdaws love my big sphinx of quartz.')

# now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getlogger('myapp.area1')
logger2 = logging.getlogger('myapp.area2')

logger1.debug('quick zephyrs blow, vexing daft jim.')
logger1.info('how quickly daft jumping zebras vex.')
logger2.warning('jail zesty vixen who grabbed pay from quack.')
logger2.error('the five boxing wizards jump quickly.')

运行后,在终端看到的结果

复制代码 代码如下:

root        : info     jackdaws love my big sphinx of quartz.
myapp.area1 : info     how quickly daft jumping zebras vex.
myapp.area2 : warning  jail zesty vixen who grabbed pay from quack.
myapp.area2 : error    the five boxing wizards jump quickly.

在日志文件中的结果

复制代码 代码如下:

10-22 22:19 root         info     jackdaws love my big sphinx of quartz.
10-22 22:19 myapp.area1  debug    quick zephyrs blow, vexing daft jim.
10-22 22:19 myapp.area1  info     how quickly daft jumping zebras vex.
10-22 22:19 myapp.area2  warning  jail zesty vixen who grabbed pay from quack.
10-22 22:19 myapp.area2  error    the five boxing wizards jump quickly.

发现debug信息只有在文件中出现,这是因为streamhandler中setlevel是info,可以看出logger.setlevel()和handler.setlevel()的区别

详细信息请参阅 http://docs.python.org/library/logging.html