• Python Logging模块


    1.about logging

    a.Logging is performed by calling methods on instances of the Logger class (hereafter called loggers).

    logging通过调用Logger类的对象的方法实现。

    Loggers指logger类的实例(对象),是实现Logging的核心元素。

    b.Logger names can be anything you want, and indicate the area of an application in which a logged message originates.

    Loggers对象的名称可以任意取,目的是标识Log信息源自于应用的哪个区域

    c.The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging.

    logging API由标准库提供,这样的好处在于所有的Python模块都能进行logging。

    2.logging的基本元素

    a.日志记录对象logger

    如何使用logger? 

    1 logger=logging.getLogger('name')#获取Logger对象
    2 logger.setLevel(logging.DEBUG)#设置logger对象等级
    3 logger.debug("first msg")#log a message

     Logger.setLevel(lvl)

    Sets the threshold for this logger to lvl. Logging messages which are less severe than lvl will be ignored.

    b.声明句柄类对象

    句柄类对象有多种类型,包括StreamHandler,FileHandler,RotatingFileHandler,SysLogHandler,SocketHandler等等。

    句柄控制logger的输出,使其更多样化的输出。

    class logging.StreamHandler([strm])

    Returns a new instance of the StreamHandler class. If strm is specified, the instance will use it for logging output; otherwise, sys.stderr will be used.

     class logging.FileHandler(filename[, mode[, encoding[, delay]]])

    Returns a new instance of the FileHandler class. The specified file is opened and used as the stream for logging. If mode is not specified, 'a' is used. If encoding is not None, it is used to open the file with that encoding. If delay is true, then file opening is deferred until the first call to emit(). By default, the file grows indefinitely.

    class logging.handlers.RotatingFileHandler(filename[, mode[, maxBytes[, backupCount[, encoding[, delay]]]]])

    Returns a new instance of the RotatingFileHandler class. The specified file is opened and used as the stream for logging. If mode is not specified, 'a' is used. If encoding is not None, it is used to open the file with that encoding. If delay is true, then file opening is deferred until the first call to emit(). By default, the file grows indefinitely.

     如何使用handler?

    1 console = logging.StreamHandler()#声明handler对象
    2 console.setLevel(logging.INFO)#设置handler等级
    3 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    4 console.setFormatter(formatter)#设置handler格式
    5 logging.getLogger('').addHandler(console)#绑定Logger

    c.Format

    如何设置?

    1 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    2 handle.setFormatter(formatter)

    有哪些格式?

    FormatDescription
    %(name)s Name of the logger (logging channel).
    %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
    %(levelname)s Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
    %(pathname)s Full pathname of the source file where the logging call was issued (if available).
    %(filename)s Filename portion of pathname.
    %(module)s Module (name portion of filename).
    %(funcName)s Name of function containing the logging call.
    %(lineno)d Source line number where the logging call was issued (if available).
    %(created)f Time when the LogRecord was created (as returned by time.time()).
    %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
    %(asctime)s Human-readable time when the LogRecord was created. By default this is of the form “2003-07-08 16:49:45,896” (the numbers after the comma are millisecond portion of the time).
    %(msecs)d Millisecond portion of the time when the LogRecord was created.
    %(thread)d Thread ID (if available).
    %(threadName)s Thread name (if available).
    %(process)d Process ID (if available).
    %(message)s The logged message, computed as msg % args.

     d.Level

    LevelNumeric value
    CRITICAL 50
    ERROR 40
    WARNING 30
    INFO 20
    DEBUG 10
    NOTSET 0

    3.logging 例子

    a.简单的例子

     1 import logging
     2 
     3 logging.basicConfig(level=logging.DEBUG,
     4                     format='%(asctime)s %(levelname)-8s %(message)s',
     5                     datefmt='%a, %d %b %Y %H:%M:%S',
     6                     filename='/temp/myapp.log',
     7                     filemode='w')
     8 logging.debug('A debug message')
     9 logging.info('Some information')
    10 logging.warning('A shot across the bows')

    其中basicConfig方法设置默认的输出形式,包括输出到哪个文件,消息输出的格式和级别

     1 import logging
     2 
     3 # set up logging to file - see previous section for more details
     4 logging.basicConfig(level=logging.DEBUG,
     5                     format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
     6                     datefmt='%m-%d %H:%M',
     7                     filename='/temp/myapp.log',
     8                     filemode='w')
     9 # define a Handler which writes INFO messages or higher to the sys.stderr
    10 console = logging.StreamHandler()
    11 console.setLevel(logging.INFO)
    12 # set a format which is simpler for console use
    13 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    14 # tell the handler to use this format
    15 console.setFormatter(formatter)
    16 # add the handler to the root logger
    17 logging.getLogger('').addHandler(console)
    18 
    19 # Now, we can log to the root logger, or any other logger. First the root...
    20 logging.info('Jackdaws love my big sphinx of quartz.')
    21 
    22 # Now, define a couple of other loggers which might represent areas in your
    23 # application:
    24 
    25 logger1 = logging.getLogger('myapp.area1')
    26 logger2 = logging.getLogger('myapp.area2')
    27 
    28 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
    29 logger1.info('How quickly daft jumping zebras vex.')
    30 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
    31 logger2.error('The five boxing wizards jump quickly.')
  • 相关阅读:
    Django ORM操作及进阶
    Django ORM字段和字段参数
    Django视图系统
    Django路由系统
    Django模板语言
    Django项目创建及相关配置,在pycharm终端打印SQL语句,在Python脚本中调用Django环境
    SQLALchemy之ORM操作
    SQLALchemy之介绍,基本使用
    SQLAlchemy创建表和删除表
    线程的通信与协作:sleep、wait、notify、yield、join关系与区别
  • 原文地址:https://www.cnblogs.com/helo-blog/p/3890931.html
Copyright © 2020-2023  润新知