GVKun编程网logo

Python 模块学习 - logging(python的logging模块)

20

此处将为大家介绍关于Python模块学习-logging的详细内容,并且为您解答有关python的logging模块的相关问题,此外,我们还将为您介绍关于(转)pythonlogging模块、0x02

此处将为大家介绍关于Python 模块学习 - logging的详细内容,并且为您解答有关python的logging模块的相关问题,此外,我们还将为您介绍关于(转)python logging模块、0x02 Python logging模块利用配置加载logger、Logging 模块学习笔记、python logging 模块的有用信息。

本文目录一览:

Python 模块学习 - logging(python的logging模块)

Python 模块学习 - logging(python的logging模块)

Purpose

根据 Python Guide - logging 部分总结,使用日志是为了达到一下两个目的:

  • Diagnostic logging records events related to the application’s operation. If a user calls in to report an error, for example, the logs can be searched for context.
  • Audit logging records events for business analysis. A user’s transactions can be extracted and combined with other user details for reports or to optimize a business goal.

Logging Flow

下面这张图来自 Python 官方文档,描述了日志处理流程。


Logging Objects

在记录日志的过程中会涉及到以下这些对象:

  • logger
    • logger 是在需要记录日志的地方进行调用,然后产生日志的一个对象。这个对象有对应五种不同日志级别的相应方法 (如,logger.debug)。
  • handler
    • 从名字就可以看出来,这个是日志的处理器,它处理 logger 产生的日志,将这些日志送往各自的目的地 (destination)。
  • filter
    • Filters provide a finer grained facility for determining which log records to output.
  • formatter
    • 日志格式化器,用来决定每条日志记录中记录哪些信息。

Logging Levels

通常来说,日志共有五种级别,而且级别越高,日志中记录的内容越少 (如果日志级别为 CRITICAL,则 DEBUG、INFO、WARNING 和 ERROR 级别的日志不会记录)。以下日志级别由低到高:

  • 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.

Useful Handlers

在 Python2.7 版本中除了基本的 Handler 类,还提供了一下一些继承自 Handler 的子类:

  • StreamHandler
    • instances send messages to streams (file-like objects).
  • FileHandler
    • instances send messages to disk files.
  • BaseRotatingHandler
    • base class for handlers that rotate log files at a certain point. It is not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler.
  • RotatingFileHandler
    • instances send messages to disk files, with support for maximum log file sizes and log file rotation.
  • TimedRotatingFileHandler
    • instances send messages to disk files, rotating the log file at certain timed intervals.
  • SocketHandler
    • instances send messages to TCP/IP sockets.
  • DatagramHandler
    • instances send messages to UDP sockets.
  • SMTPHandler
    • instances send messages to a designated email address.
  • SysLogHandler
    • instances send messages to a Unix syslog daemon, possibly on a remote machine.
  • NTEventLogHandler
    • instances send messages to a Windows NT/2000/XP event log.
  • MemoryHandler
    • instances send messages to a buffer in memory, which is flushed whenever specific criteria are met.
  • HTTPHandler
    • instances send messages to an HTTP server using either GET or POST semantics.
  • WatchedFileHandler
    • instances watch the file they are logging to. If the file changes, it is closed and reopened using the file name. This handler is only useful on Unix-like systems; Windows does not support the underlying mechanism used.
  • NullHandler
    • instances do nothing with error messages. They are used by library developers who want to use logging, but want to avoid the ‘No handlers could be found for logger XXX’ message which can be displayed if the library user has not configured logging. See Configuring Logging for a Library for more information.

LogRecord attributes

每个日志记录都是一个 LogRecord 实例,具有以下这些属性,而这些属性一般都可以在设置 formatter 的时候进行设置。


Approaches

至少有三种方法可以用来生成一个日志记录器 (logger).

  • 使用 INI 格式的文件进行配置,然后使用 logging.config.fileConfig(fname) 来加载配置项。
  • 使用一个字典或者一个 json 格式文件 (通过 json.dump (dict_obj, fname))
  • 纯代码实现:

config.ini

[loggers]
keys=root

[handlers]
keys=stream_handler

[formatters]
keys=formatter

[logger_root]
level=DEBUG
handlers=stream_handler

[handler_stream_handler]
class=StreamHandler
level=DEBUG
formatter=formatter
args=(sys.stderr,)

[formatter_formatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s

loggers.py

import logging


# ini file
from logging.config import fileConfig

fileConfig(''config.ini'')
logger = logging.getLogger()
logger.debug(''often makes a very good meal of %s'', ''visiting tourists'')


# dict
from logging.config import dictConfig

logging_config = dict(
    version = 1,
    formatters = {
        ''f'': {''format'':
              ''%(asctime)s %(name)-12s %(levelname)-8s %(message)s''}
        },
    handlers = {
        ''h'': {''class'': ''logging.StreamHandler'',
              ''formatter'': ''f'',
              ''level'': logging.DEBUG}
        },
    loggers = {
        ''root'': {''handlers'': [''h''],
                 ''level'': logging.DEBUG}
        }
)

dictConfig(logging_config)

logger = logging.getLogger()
logger.debug(''often makes a very good meal of %s'', ''visiting tourists'')


# code
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
        ''%(asctime)s %(name)-12s %(levelname)-8s %(message)s'')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

logger.debug(''often makes a very good meal of %s'', ''visiting tourists'')

(转)python logging模块

(转)python logging模块

原文: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()
复制代码
复制代码

4 Reference

每个 Python 程序员都要知道的日志实践

Python标准模块logging

python 的日志logging模块学习

0x02 Python logging模块利用配置加载logger

0x02 Python logging模块利用配置加载logger

目录

  • logging模块利用配置加载logger
    • 方式一模板:logging.config.dictConfig(config_dict)

logging模块利用配置加载logger

logging.config模块提供了从配置加载创建logger等相关对象,并放入manager对象中进行缓存待用。所以记录下一般几种方式配置的范本模式,方便项目中copy直接修改使用。

dict config references 官档关于logging配置字典说明

方式一模板:logging.config.dictConfig(config_dict)

config_dict 字典模板

cfg = {
        'version': 1,'formatters': {
            'detailed': {
                'class': 'logging.Formatter','format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            }
        },'handlers': {
            'console': {
                'class': 'logging.StreamHandler','level': 'INFO',},'file': {
                'class': 'logging.FileHandler','filename': 'mplog.log','mode': 'w','formatter': 'detailed','foofile': {
                'class': 'logging.FileHandler','filename': 'mplog-foo.log','errors': {
                'class': 'logging.FileHandler','filename': 'mplog-errors.log','level': 'ERROR','loggers': {
            'foo': {
                'handlers': ['foofile']
            }
        },'root': {
            'level': 'DEBUG','handlers': ['console','file','errors']
        },}

Logging 模块学习笔记

Logging 模块学习笔记

<h4> 快速开始 </h4> <p > 日志级别 <br /> 权值 </p> <p>CRITICAL <br />50</p> <p>ERROR <br />40</p> <p>WARNING <br />30</p> <p>INFO <br />20</p> <p>DEBUG <br />10</p> <p>NOTSET <br />0</p> <p > 除 < code>NOTSET</code > 外,<code>logging</code > 模块提供了与级别名称对应的小写函数以便快速调用。 <br /> 样例代码:</p> <pre><code>import logging

def main(): logging.critical("critical") logging.error("error") logging.warning("warning") logging.info("info") logging.debug("debug")

if name == ''main'': main()</code></pre>

<p> 输出:</p>

<blockquote> <p>CRITICAL:root:critical <br />ERROR:root:error

<br />WARNING:root:warning</p>

</blockquote>

<p> 从输出可以注意到 < code>WARNING</code > 以下级别的信息并没有打印出来。

<br /> 原因在于 < code>logging</code > 默认的级别是 < code>WARNING</code>,可以通过 < code>logging.basicConfig</code > 函数或修改默认 < code>Logger</code > 对象来改变级别。

<br /> 默认输出格式为:</p>

<blockquote> <p > 级别:Logger 对象名:日志 </p> </blockquote>

<h4>basicConfig 函数 </h4>

<p>basicConfig 函数可以快速定制默认 < code>Logger</code > 对象。</p>

<h5> 参数名 </h5>

<h6>filename</h6>

<p> 指定日志文件的名称。</p>

<h6>filemode</h6>

<p> 指定日志文件的打开方式,有 < code>w</code > 和 < code>a</code > 两个选项,默认为 < code>a</code>。</p>

<h6>format</h6>

<p> 指定输出的格式和内容,格式为:</p>

<blockquote> <p>%(名称) 格式控制字符串 </p> </blockquote>

<p> 格式列表与其对应的类型 </p>

<ul> <li><strong>levelno</strong> <code>s</code>: 打印日志级别的数值 </li>

<li><strong>levelname</strong> <code>s</code>: 打印日志级别名称 </li>

<li><strong>pathname</strong> <code>s</code>: 打印当前执行程序的路径,其实就是 < code>sys.argv [0]</code></li>

<li><strong>filename</strong> <code>s</code>: 打印当前执行程序名 </li>

<li><strong>funcName</strong> <code>s</code>: 打印日志的当前函数 </li>

<li><strong>lineno</strong> <code>d</code>: 打印日志的当前行号 </li>

<li><strong>asctime</strong> <code>s</code>: 打印日志的时间 </li>

<li><strong>thread</strong> <code>d</code>: 打印线程 ID </li>

<li><strong>threadName</strong> <code>s</code>: 打印线程名称 </li>

<li><strong>process</strong> <code>d</code>: 打印进程 ID </li>

<li><strong>message</strong> <code>s</code>: 打印日志信息 </li> </ul>

<h6>datefmt</h6>

<p> 指定时间格式,格式同 < code>time.strftime</code>,影响 < code>format</code > 中 < code>asctime</code > 的格式。</p>

<h6>level</h6>

<p> 设置日志级别,默认为 < code>logging.WARNING</code>。</p>

<h6>stream</h6>

<p> 指定将日志的输出流,可以指定输出到 < code>sys.stderr</code>,<code>sys.stdout</code > 或者文件,默认输出到 < code>sys.stderr</code>,当 < code>stream</code > 和 < code>filename</code > 同时指定时,<code>stream</code > 被忽略。</p>

<h4>Logger 对象 </h4>

<p><code>logging.getLogger</code > 函数返回一个 < code>Logger</code > 对象,函数接收一个字符串用以描述希望返回的 < code>Logger</code > 对象的名称,相同的名称全局唯一对应一个 < code>Logger</code > 对象。缺省参数为 < code>root</code>,返回默认 < code>Logger</code > 对象。</p>

<h5>Logger 对象的方法 </h5>

<h6>setLevel</h6>

<p> 设置该 < code>Logger</code > 对象的记录级别。

<br /> 参数:</p>

<ol> <li><strong>level</strong>:级别枚举 </li> </ol>

<h6>log</h6>

<p> 打印指定级别的日志,须先设置 handler。 <br /> 参数:</p>

<ol> <li><strong>level</strong>:级别枚举。 </li>

<li><strong>msg</strong>:希望打印的对象,会自动转为字符串。如果参数已是字符串,可以是格式字符串。 </li>

<li><strong>*args</strong>:与 msg 结合成待打印内容 < code>(msg % args)</code>。</li> </ol>

<h6>critical / error / warning / info / debug</h6>

<p> 指定对应级别的调用 < code>log</code>。

<br /> 参数:</p>

<ol> <li><strong>msg</strong>:希望打印的对象,会自动转为字符串。如果参数已是字符串,可以是格式字符串。 </li>

<li><strong>*args</strong>:与 msg 结合成待打印内容 (msg % args)。</li> </ol>

<h6>addHandler</h6>

<p> 给 < code>Logger</code > 对象添加处理器,可添加多个。

<br /> 参数:</p>

<ol> <li><strong>hdlr</strong>:处理器对象。</li> </ol>

<h6>removeHandler</h6>

<p> 移除 < code>Logger</code > 对象的指定处理器。

<br /> 参数:</p>

<ol> <li><strong>hdlr</strong>:处理器对象。</li> </ol>

<h4> 日志处理器 </h4>

<p> 处理器用来扩展 < code>Logger</code > 对象,通过 < code>logger.addHandler (hdlr)</code > 方法加载到 < code>Logger</code > 对象。</p>

<h5> 模块集成处理器对象 </h5>

<ul> <li><strong>logging.StreamHandler</strong>:日志输出到流,可以是 < code>sys.stderr</code>、<code>sys.stdout</code > 或者文件。 </li>

<li><strong>logging.FileHandler</strong>:日志输出到文件。 </li>

<li><strong>logging.handlers.SocketHandler</strong>:远程输出日志到 TCP/IP sockets。 </li>

<li><strong>logging.handlers.DatagramHandler</strong>: 远程输出日志到 UDP sockets。 </li>

<li><strong>logging.handlers.SMTPHandler</strong>: 远程输出日志到邮件地址。 </li>

<li><strong>logging.handlers.SysLogHandler</strong>:日志输出到 syslog。 </li>

<li><strong>logging.handlers.NTEventLogHandler</strong>:远程输出日志到 Windows NT/2000/XP 的事件日志。 </li>

<li><strong>logging.handlers.MemoryHandler</strong>:日志输出到内存中的制定 buffer。 </li>

<li><strong>logging.handlers.HTTPHandler</strong>:通过 < code>GET</code > 或 < code>POST</code > 远程输出到 HTTP 服务器。 </li>

<li><strong>logging.handlers.BaseRotatingHandler</strong>:日志回滚。 </li>

<li><strong>logging.handlers.RotatingFileHandler</strong>:日志回滚,实际用。 </li>

<li><strong>logging.handlers.TimedRotatingFileHandler</strong>:日志回滚,实际用。</li> </ul>

<h5> 处理器使用简示 </h5>

<h6>logging.StreamHandler</h6>

<p><code>logging.StreamHandler</code > 对象构造参数缺省为 < code>sys.stdout</code>,参数可以接收一个流对象(<code>sys.stderr</code>、<code>sys.stdout</code > 或者文件)。</p>

<pre><code>sh1 = logging.StreamHandler () sh2 = logging.StreamHandler (sys.stdout) sh3 = logging.StreamHandler (open (file_path,&quot;w&quot;)) # w 和 a 皆可 </code></pre>

<p><code>logging.StreamHandler</code> 对象能够设置记录的日志级别,但实际输出受 < code>Logger</code > 对象的级别限制。<code>Logger</code > 对象的级别制约着消息的派发,<code>Handler</code > 对象的级别制约着记录。</p>

<pre><code>sh2 = logging.setLevel(logging.WARING) sh3 = logging.setLevel(logging.INFO)</code></pre>

<p><code>logging.StreamHandler</code> 对象能够自定义输出格式。</p>

<pre><code>fmt = logging.Formatter(&quot;%(name)s:%(levelname)s:%(message)s&quot;) sh1.setFormatter(fmt)</code></pre>

<h4> 更多资料 </h4>

<ul> <li><a href="http://docs.python.org/2/library/logging.html"> 官方文档 </a></li>

<li><a href="http://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html">python 的日志 logging 模块学习 </a></li>

<li><a href="http://blog.csdn.net/fxjtoday/article/details/6307285">Python 标准模块 logging</a></li> </ul>

<hr />

<blockquote> <p>@<a href="http://mrlyc.blogspot.com/">LYC</a>

<br />转载请注明<a href="http://mrlyc.blogspot.com/">出处</a></p></blockquote>

python logging 模块

python logging 模块

在自动化测试中,软件运行会出现错误,这时候日志就很重要了。python的logging.basicConfig函数在这里就显得很重要了

logging提供了一组便利的函数,用来做简单的日志。它们是 debug()、 info()、 warning()、 error() 和 critical()。

 

logging函数根据它们用来跟踪的事件的级别或严重程度来命名。标准级别及其适用性描述如下(以严重程度递增排序):

级别 何时使用
DEBUG 详细信息,一般只在调试问题时使用。
INFO 证明事情按预期工作。
WARNING 某些没有预料到的事件的提示,或者在将来可能会出现的问题提示。例如:磁盘空间不足。但是软件还是会照常运行。
ERROR 由于更严重的问题,软件已不能执行一些功能了。
CRITICAL 严重错误,表明软件已不能继续运行了。

 

默认等级是WARNING,这意味着仅仅这个等级及以上的才会反馈信息,除非logging模块被用来做其它事情。

被跟踪的事件能以不同的方式被处理。最简单的处理方法就是把它们在控制台上打印出来。另一种

本文同步分享在 博客“SoWhat1412”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

我们今天的关于Python 模块学习 - loggingpython的logging模块的分享已经告一段落,感谢您的关注,如果您想了解更多关于(转)python logging模块、0x02 Python logging模块利用配置加载logger、Logging 模块学习笔记、python logging 模块的相关信息,请在本站查询。

本文标签: