当前位置: 移动技术网 > IT编程>脚本编程>Python > Python之logging模块的使用方法

Python之logging模块的使用方法

2018年02月01日  | 移动技术网IT编程  | 我要评论

笑容 作文,sqqvob,塑料热板焊接机

logging的日志可以分为 debug(), info(), warning(), error() and critical() 5个级别

最简单用法:

import logging

logging.warning("user [snow] attempted wrong password more than 3 times")
logging.critical("server is down")

#输出
WARNING:root:user [snow] attempted wrong password more than 3 times
CRITICAL:root:server is down

日志级别:

DEBUG: Detailed information, typically of interest only when diagnosing problems.
INFO: Confirmation that things are working as expected.
WARNING:  An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. 
ERROR: Due to a more serious problem, the software has not been able to perform some function.
CRITICAL: A serious error, indicating that the program itself may be unable to continue running.

basicConfig()方法:

  Do basic configuration for the logging system.This function does nothing if the root logger already has handlers configured. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package.

  The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger.

optional keyword arguments(可选择的函数变量):

*filename: Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler.

*filemode: Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a').

*format: Use the specified format string for the handler.

*datefmt: Use the specified date/time format.

*level: Set the root logger level to the specified level.

*stream: Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored.

注意:StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed.

日志的format格式:

%(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: 用户输出的消息

logging模块记录日志涉及四个主要类:

logger:提供了应用程序可以直接使用的接口;

handler:将(logger创建的)日志记录发送到合适的目的输出;

filter:提供了细度设备来决定输出哪条日志记录;

formatter:决定日志记录的最终输出格式

1、logger:

每个程序在输出信息之前都要获得一个Logger。Logger通常对应了程序的模块名。

getLogger()方法:

这是最基本的入口,该方法参数可以为空,默认的logger名称是root,如果在同一个程序中一直都使用同名的logger,其实会拿到同一个实例,使用这个技巧就可以跨模块调用同样的logger来记录日志。

另外你也可以通过日志名称来区分同一程序的不同模块,比如这个例子

logger = logging.getLogger("App.UI")
logger = logging.getLogger("App.Service")
Logger的其他方法:

*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():可以设置的日志级别

2、handler:

handler对象负责发送相关的信息到指定目的地。可以使用已有的handler,也可以编写Handler。通过addHandler()方法添加多个handler

Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略

Handler.setFormatter():给这个handler选择一个格式

Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象

每个Logger可以附加多个Handler。

一些常用的Handler:

1) logging.StreamHandler
使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。它的构造函数是:
StreamHandler([strm])
其中strm参数是一个文件对象。默认是sys.stderr

2) logging.FileHandler
和StreamHandler类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:
FileHandler(filename[,mode])
filename是文件名,必须指定一个文件名。
mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。

3) logging.handlers.RotatingFileHandler
这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。它的构造函数是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode两个参数和FileHandler一样。
maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。

4) logging.handlers.TimedRotatingFileHandler
这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
interval是时间间隔。
when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:
S 秒
M 分
H 小时
D 天
W 每星期(interval==0时代表星期一)
midnight 每天凌晨

使用示例:

# -*- coding:utf-8 -*-

import logging

# create logger
logger = logging.getLogger('demo3.py')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create file handler and set level to warning
fh = logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)

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

# add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)

# add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)

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

记录异常信息:

当你使用logging模块记录异常信息时,不需要传入该异常对象,只要你直接调用logger.error() 或者 logger.exception()就可以将当前异常记录下来。

try:
    1 / 0
except:
    # 等同于error级别,但是会额外记录当前抛出的异常堆栈信息
    logger.exception('this is an exception message')

# 2016-10-08 21:59:19,493 ERROR   : this is an exception message
# Traceback (most recent call last):
#   File "D:/Git/py_labs/demo/use_logging.py", line 45, in 
#     1 / 0
# ZeroDivisionError: integer pision or modulo by zero

通过文件配置logging:

配置文件内容:

vim logger_config.ini
[loggers]
keys=root,infoLogger,errorlogger

[logger_root]
level=DEBUG
handlers=infohandler,errorhandler

[logger_infoLogger]
handlers=infohandler
qualname=infoLogger
propagate=0

[logger_errorlogger]
handlers=errorhandler
qualname=errorlogger
propagate=0

###############################################

[handlers]
keys=infohandler,errorhandler

[handler_infohandler]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stdout,)

[handler_errorhandler]
class=FileHandler
level=ERROR
formatter=form01
args=('logs/mylog.log', 'a')

###############################################

[formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s %(filename)s %(levelname)s  %(message)s
datefmt=%Y-%m-%d %H:%M:%S

[formatter_form02]
format=%(asctime)s %(filename)s %(levelname)s  %(message)s
datefmt=%Y-%m-%d %H:%M:%S

字段说明:

[loggers]
# 定义logger模块,root是父类,必需存在的,其它的是自定义。
# logging.getLogger(NAME)便相当于向logging模块注册了一种日志打印
# name 中用 . 表示 log 的继承关系

[handlers]
# 定义handler

[formatters]
# 定义格式化输出

[logger_root]

# 实现上面定义的logger模块,必需是[logger_xxxx]这样的形式

# [logger_xxxx] logger_模块名称
# level     级别,级别有DEBUG、INFO、WARNING、ERROR、CRITICAL
# handlers  处理类,可以有多个,用逗号分开
# qualname  logger名称,应用程序通过 logging.getLogger获取。对于不能获取的名称,则记录到root模块。
# propagate 是否继承父类的log信息,0:否 1:是

[handler_infohandler]
# [handler_xxxx]
# class handler类名
# level 日志级别
# formatter,上面定义的formatter
# args handler初始化函数参数

[formatter_form01]

# 日志格式

使用方式:

from logging.config import fileConfig

fileConfig('loggin_config.ini')
logger=logging.getLogger('infoLogger')
logger.info('test1')
logger_error=logging.getLogger('errorhandler')
logger_error.error('test5')

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网