码迷,mamicode.com
首页 > 编程说话 > 详细

(转)python logging模块

时间:2019-10-10 00:30:01      浏览:28      评论:0      收藏:0      [点我收藏+]

标签:win   default   select   特定   root   body   word   learn   设备文件   

原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html

1 logging模块简介

logging模块是Python内置的标准模块,重要用于输入运转日记,可以设置输入日记的等级、日记保存途径、日记文件回滚等;比拟print,具有以下长处:

  1. 可以经过过程设置不合的日记等级,在release版本中只输入重要信息,而不用显示大年夜量的调试信息;
  2. print将一切信息都输入到标准输入中,严重影响开辟者从标准输入中检查其它数据;logging则可以由开辟者决定将信息输入到甚么处所,和怎样输入;

2 logging模块应用

2.1 根本应用

设备logging根本的设置,然后在控制台输入日记,

技巧图片
技巧图片
import logging
logging.basicConfig(level = logging.INFO,format = ‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
logger = logging.getLogger(__name__)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
技巧图片
技巧图片

运转时,控制台输入,

2016-10-09 19:11:19,434 - __main__ - INFO - Start print log
2016-10-09 19:11:19,434 - __main__ - WARNING - Something maybe fail.
2016-10-09 19:11:19,434 - __main__ - INFO - Finish

logging中可以选择很多消息级别,如debug、info、warning、error和critical。经过过程付与logger或许handler不合的级别,开辟者便可以只输掉足误信息到特定的记录文件,或许在调试时只记录调试信息。

例如,我们将logger的级别改成DEBUG,再不雅察一下输入成果,

logging.basicConfig(level = logging.DEBUG,format = ‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)

控制台输入,可以发明,输入了debug的信息。

2016-10-09 19:12:08,289 - __main__ - INFO - Start print log
2016-10-09 19:12:08,289 - __main__ - DEBUG - Do something
2016-10-09 19:12:08,289 - __main__ - WARNING - Something maybe fail.
2016-10-09 19:12:08,289 - __main__ - INFO - Finish

logging.basicConfig函数各参数:

filename:指定日记文件名;

filemode:和file函数意义雷同,指定日记文件的翻开形式,‘w‘或许‘a‘;

format:指定输入的格局和内容,format可以输入很多有效的信息,

参数:感化
%(levelno)s:打印日记级其他数值
%(levelname)s:打印日记级其他称号
%(pathname)s:打印以后履行法式榜样的途径,其实就是sys.argv[0]
%(filename)s:打印以后履行法式榜样名
%(funcName)s:打印日记的以后函数
%(lineno)d:打印日记的以后行号
%(asctime)s:打印日记的时间
%(thread)d:打印线程ID
%(threadName)s:打印线程称号
%(process)d:打印过程ID
%(message)s:打印日记信息

datefmt:指准时间格局,同time.strftime();

level:设置日记级别,默许为logging.WARNNING;

stream:指定将日记的输入流,可以指定输入到sys.stderr,sys.stdout或许文件,默许输入到sys.stderr,当stream和filename同时指准时,stream被忽视;

2.2 将日记写入到文件

2.2.1 将日记写入到文件

设置logging,创建一个FileHandler,并对输入消息的格局停止设置,将其添加到logger,然后将日记写入到指定的文件中,

技巧图片
技巧图片
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
技巧图片
技巧图片

log.txt中日记数据为,

2016-10-09 19:01:13,263 - __main__ - INFO - Start print log
2016-10-09 19:01:13,263 - __main__ - WARNING - Something maybe fail.
2016-10-09 19:01:13,263 - __main__ - INFO - Finish

2.2.2 将日记同时输入到屏幕和日记文件

logger中添加StreamHandler,可以将日记输入到屏幕上,

技巧图片
技巧图片
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)

logger.addHandler(handler)
logger.addHandler(console)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
技巧图片
技巧图片

可以在log.txt文件和控制台中看到,

2016-10-09 19:20:46,553 - __main__ - INFO - Start print log
2016-10-09 19:20:46,553 - __main__ - WARNING - Something maybe fail.
2016-10-09 19:20:46,553 - __main__ - INFO - Finish

可以发明,logging有一个日记处理的主对象,其他处理方法都是经过过程addHandler添加出来,logging中包含的handler重要有以下几种,

handler称号:地位;感化

StreamHandler:logging.StreamHandler;日记输入到流,可所以sys.stderr,sys.stdout或许文件
FileHandler:logging.FileHandler;日记输入到文件
BaseRotatingHandler:logging.handlers.BaseRotatingHandler;根本的日记回滚方法
RotatingHandler:logging.handlers.RotatingHandler;日记回滚方法,支撑日记文件最大年夜数量和日记文件回滚
TimeRotatingHandler:logging.handlers.TimeRotatingHandler;日记回滚方法,在一准时间区域内回滚日记文件
SocketHandler:logging.handlers.SocketHandler;长途输入日记到TCP/IP sockets
DatagramHandler:logging.handlers.DatagramHandler;长途输入日记到UDP sockets
SMTPHandler:logging.handlers.SMTPHandler;长途输入日记到邮件地址
SysLogHandler:logging.handlers.SysLogHandler;日记输入到syslog
NTEventLogHandler:logging.handlers.NTEventLogHandler;长途输入日记到Windows NT/2000/XP的事宜日记
MemoryHandler:logging.handlers.MemoryHandler;日记输入到内存中的指定buffer
HTTPHandler:logging.handlers.HTTPHandler;经过过程"GET"或许"POST"长途输入到HTTP办事器

2.2.3 日记回滚

应用RotatingFileHandler,可以完成日记回滚,

技巧图片
技巧图片
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
#定义一个RotatingFileHandler,最多备份3个日记文件,每个日记文件最大年夜1K
rHandler = RotatingFileHandler("log.txt",maxBytes = 1*1024,backupCount = 3)
rHandler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
rHandler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)

logger.addHandler(rHandler)
logger.addHandler(console)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
技巧图片
技巧图片

可以在工程目次中看到,备份的日记文件,

2016/10/09  19:36               732 log.txt
2016/10/09  19:36               967 log.txt.1
2016/10/09  19:36               985 log.txt.2
2016/10/09  19:36               976 log.txt.3

2.3 设置消息的等级

可以设置不合的日记等级,用于控制日记的输入,

日记等级:应用范围

FATAL:致命缺点
CRITICAL:特别蹩脚的任务,如内存耗尽、磁盘空间为空,普通很少应用
ERROR:产生缺点时,如IO操作掉败或许连接成绩
WARNING:产生很重要的事宜,然则其实不是缺点时,如用户登录暗码缺点
INFO:处理请求或许状况变更等平常事务
DEBUG:调试过程当中应用DEBUG等级,如算法中每个轮回的中心状况

2.4 捕获traceback

Python中的traceback模块被用于跟踪异常前往信息,可以在logging中记录下traceback,

代码,

技巧图片
技巧图片
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)

logger.addHandler(handler)
logger.addHandler(console)

logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
try:
    open("sklearn.txt","rb")
except (SystemExit,KeyboardInterrupt):
    raise
except Exception:
    logger.error("Faild to open sklearn.txt from logger.error",exc_info = True)

logger.info("Finish")
技巧图片
技巧图片

控制台和日记文件log.txt中输入,

Start print log
Something maybe fail.
Faild to open sklearn.txt from logger.error
Traceback (most recent call last):
  File "G:\zhb7627\Code\Eclipse WorkSpace\PythonTest\test.py", line 23, in <module>
    open("sklearn.txt","rb")
IOError: [Errno 2] No such file or directory: ‘sklearn.txt‘
Finish

也能够应用logger.exception(msg,_args),它等价于logger.error(msg,exc_info = True,_args),

logger.error("Faild to open sklearn.txt from logger.error",exc_info = True)

调换为,

logger.exception("Failed to open sklearn.txt from logger.exception")

控制台和日记文件log.txt中输入,

Start print log
Something maybe fail.
Failed to open sklearn.txt from logger.exception
Traceback (most recent call last):
  File "G:\zhb7627\Code\Eclipse WorkSpace\PythonTest\test.py", line 23, in <module>
    open("sklearn.txt","rb")
IOError: [Errno 2] No such file or directory: ‘sklearn.txt‘
Finish

2.5 多模块应用logging

主模块mainModule.py,

技巧图片
技巧图片
import logging
import subModule
logger = logging.getLogger("mainModule")
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)

logger.addHandler(handler)
logger.addHandler(console)


logger.info("creating an instance of subModule.subModuleClass")
a = subModule.SubModuleClass()
logger.info("calling subModule.subModuleClass.doSomething")
a.doSomething()
logger.info("done with  subModule.subModuleClass.doSomething")
logger.info("calling subModule.some_function")
subModule.som_function()
logger.info("done with subModule.some_function")
技巧图片
技巧图片

子模块subModule.py,

技巧图片
技巧图片
import logging

module_logger = logging.getLogger("mainModule.sub")
class SubModuleClass(object):
    def __init__(self):
        self.logger = logging.getLogger("mainModule.sub.module")
        self.logger.info("creating an instance in SubModuleClass")
    def doSomething(self):
        self.logger.info("do something in SubModule")
        a = []
        a.append(1)
        self.logger.debug("list a = " + str(a))
        self.logger.info("finish something in SubModuleClass")

def som_function():
    module_logger.info("call function some_function")
技巧图片
技巧图片

履行以后,在控制和日记文件log.txt中输入,

2016-10-09 20:25:42,276 - mainModule - INFO - creating an instance of subModule.subModuleClass
2016-10-09 20:25:42,279 - mainModule.sub.module - INFO - creating an instance in SubModuleClass
2016-10-09 20:25:42,279 - mainModule - INFO - calling subModule.subModuleClass.doSomething
2016-10-09 20:25:42,279 - mainModule.sub.module - INFO - do something in SubModule
2016-10-09 20:25:42,279 - mainModule.sub.module - INFO - finish something in SubModuleClass
2016-10-09 20:25:42,279 - mainModule - INFO - done with  subModule.subModuleClass.doSomething
2016-10-09 20:25:42,279 - mainModule - INFO - calling subModule.some_function
2016-10-09 20:25:42,279 - mainModule.sub - INFO - call function some_function
2016-10-09 20:25:42,279 - mainModule - INFO - done with subModule.some_function

起首在主模块定义了logger‘mainModule‘,并对它停止了设备,便可以在说冥器过程外面的其他处所经过过程getLogger(‘mainModule‘)取得的对象都是一样的,不须要重新设备,可以直接应用。定义的该logger的子logger,都可以共享父logger的定义和设备,所谓的父子logger是经过过程定名来辨认,随便任性以‘mainModule‘开首的logger都是它的子logger,例如‘mainModule.sub‘。

实际开辟一个application,起首可以经过过程logging设备文件编写好这个application所对应的设备,可以生成一个根logger,如‘PythonAPP‘,然后在主函数中经过过程fileConfig加载logging设备,接着在application的其他处所、不合的模块中,可以应用根logger的子logger,如‘PythonAPP.Core‘,‘PythonAPP.Web‘来停止log,而不须要反复的定义和设备各个模块的logger。

3 经过过程JSON或许YAML文件设备logging模块

虽然可以在Python代码中设备logging,然则如许其实不敷灵活,最好的办法是应用一个设备文件来设备。在Python 2.7及今后的版本中,可以从字典中加载logging设备,也就意味着可以经过过程JSON或许YAML文件加载日记的设备。

3.1 经过过程JSON文件设备

JSON设备文件,

{
    "version":1,
    "disable_existing_loggers":false,
    "formatters":{
        "simple":{
            "format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    },
    "handlers":{
        "console":{
            "class":"logging.StreamHandler",
            "level":"DEBUG",
            "formatter":"simple",
            "stream":"ext://sys.stdout"
        },
        "info_file_handler":{
            "class":"logging.handlers.RotatingFileHandler",
            "level":"INFO",
            "formatter":"simple",
            "filename":"info.log",
            "maxBytes":"10485760",
            "backupCount":20,
            "encoding":"utf8"
        },
        "error_file_handler":{
            "class":"logging.handlers.RotatingFileHandler",
            "level":"ERROR",
            "formatter":"simple",
            "filename":"errors.log",
            "maxBytes":10485760,
            "backupCount":20,
            "encoding":"utf8"
        }
    },
    "loggers":{
        "my_module":{
            "level":"ERROR",
            "handlers":["info_file_handler"],
            "propagate":"no"
        }
    },
    "root":{
        "level":"INFO",
        "handlers":["console","info_file_handler","error_file_handler"]
    }
}

经过过程JSON加载设备文件,然后经过过程logging.dictConfig设备logging,

技巧图片
技巧图片
import json
import logging.config
import os

def setup_logging(default_path = "logging.json",default_level = logging.INFO,env_key = "LOG_CFG"):
    path = default_path
    value = os.getenv(env_key,None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path,"r") as f:
            config = json.load(f)
            logging.config.dictConfig(config)
    else:
        logging.basicConfig(level = default_level)

def func():
    logging.info("start func")

    logging.info("exec func")

    logging.info("end func")

if __name__ == "__main__":
    setup_logging(default_path = "logging.json")
    func()
技巧图片
技巧图片

3.2 经过过程YAML文件设备

经过过程YAML文件停止设备,比JSON看起来加倍简介清楚明了,

version: 1
disable_existing_loggers: False
formatters:
        simple:
            format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
    console:
            class: logging.StreamHandler
            level: DEBUG
            formatter: simple
            stream: ext://sys.stdout
    info_file_handler:
            class: logging.handlers.RotatingFileHandler
            level: INFO
            formatter: simple
            filename: info.log
            maxBytes: 10485760
            backupCount: 20
            encoding: utf8
    error_file_handler:
            class: logging.handlers.RotatingFileHandler
            level: ERROR
            formatter: simple
            filename: errors.log
            maxBytes: 10485760
            backupCount: 20
            encoding: utf8
loggers:
    my_module:
            level: ERROR
            handlers: [info_file_handler]
            propagate: no
root:
    level: INFO
    handlers: [console,info_file_handler,error_file_handler]

经过过程YAML加载设备文件,然后经过过程logging.dictConfig设备logging,

技巧图片
技巧图片
import yaml
import logging.config
import os

def setup_logging(default_path = "logging.yaml",default_level = logging.INFO,env_key = "LOG_CFG"):
    path = default_path
    value = os.getenv(env_key,None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path,"r") as f:
            config = yaml.load(f)
            logging.config.dictConfig(config)
    else:
        logging.basicConfig(level = default_level)

def func():
    logging.info("start func")

    logging.info("exec func")

    logging.info("end func")

if __name__ == "__main__":
    setup_logging(default_path = "logging.yaml")
    func()
    
技巧图片
技巧图片

 

 

 

(转)python logging模块

标签:win   default   select   特定   root   body   word   learn   设备文件   

原文地址:https://www.cnblogs.com/quinc1201/p/11645099.html

(0)
(0)
   
告发
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权一切 京ICP备13008772号-2
迷上了代码!