首页 > 代码库 > python之logging模块使用

python之logging模块使用

#!/usr/bin/env python
# encoding: utf-8
import logging
#定义handler的输出格式
formatter=logging.Formatter(‘%(asctime)s--%(name)s--%(filename)s--%(message)s‘)
#创建一个handler,用于写入日志文件,只输出debug级别以上的日志
fh=logging.FileHandler(‘test.log‘)
fh.setFormatter(formatter)
#再创建一个handler,用于输出到控制台
ch=logging.StreamHandler()
ch.setFormatter(formatter)
#创建一个logging命名为mylogger,%(name)s可调用这个名字
logger=logging.getLogger(‘mylogger‘)
logger.setLevel(logging.DEBUG)
#给logger添加handler
logger.addHandler(fh)
logger.addHandler(ch)
#记录两条日志
logger.info(‘foorbar‘)
logger.debug(‘just a test‘)
 
[aolens@aolens-2 ~/Documents/python/reboot]$ python loggers.py
2017-03-01 15:21:22,434--mylogger--loggers.py--foorbar
2017-03-01 15:21:22,435--mylogger--loggers.py--just a test

Logging Formatter的参数:

  • %(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)

  • %(lineno)d Source line number where the logging call was issued (if available)

  • %(funcName)s Function name

  • %(created)f Time when the LogRecord was created (time.time() return value)

  • %(asctime)s Textual time when the LogRecord was created

  • %(msecs)d Millisecond portion of the creation time

  • %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded (typically at application startup time)

  • %(thread)d Thread ID (if available)

  • %(threadName)s Thread name (if available)

  • %(process)d Process ID (if available)

  • %(message)s The result of record.getMessage(), computed just as the record is emitted


function 封装logging日志调用
    loggers.py中封装log日志 调用。内容如下:

import loggingdef InitLogger(filename,level,name):    
    #create a logging object    
    logger = logging.getLogger()    
    logger.setLevel(level)    
    #format log file    
    formatter = logging.Formatter(‘%(asctime)s %(name)s-%(levelname)s-%(filename)s-[line:%(lineno)s]: %(message)s‘)    
    #create the logging file handler and format the log file    
    fh = logging.FileHandler(filename,mode=‘a+‘)    
    fh.setFormatter(formatter)    
    #create logging print Stream    
    ch = logging.StreamHandler()    
    ch.setFormatter(formatter)    
    #logger object load the hander    
    logger.addHandler(fh)    
    logger.addHandler(ch)    
    return logger

调用日志:

import loggers,logging
logger=loggers.InitLogger(‘./testfile.log‘,logging.INFO,‘test‘)
logger.info("print info level log one line")

查看testfile.log日志文件

[aolens@aolens-2 ~/Documents/python/reboot]$ cat testfile.log
2017-03-01 15:45:15,974 root-INFO-sys.py-[line:6]: print info level log one line

方法二:Basic Demo

#filename:Loggers.py
def LoggingDemo():
    InitLogging(‘./test.log‘)
    logging.debug("this is debug message")
    logging.info("this is info message")
    logging.warning("this is warning message")
    logging.error("this is error message")
def InitLogging(logfilename):
    logging.basicConfig(level=logging.DEBUG,
        format=‘%(asctime)s %(name)s-%(levelname)s-%(filename)s-[line:%(lineno)s]: %(message)s‘,
        datefmt=logfilename,
        filemode=‘w‘,
        filename=logfilename
        );
if __name__==‘__main__‘:
    LoggingDemo()
basicConfig参数:
  • 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.

调用:
#!/usr/bin/env python
# encoding: utf-8
import loggers,logging
loggers.LoggingDemo()

 推荐使用方式:

import logging,logging.handlers
    ‘‘‘
    思路
    1,通过函数,实例化一个LOGGER对象
    2,函数实例化logger对象后,并对对象座位返回值,即return logger
    3,其他模块直接调用模块中的函数即可,简单方便
    ‘‘‘
    #定义写日志的函数,返回一个实例化的logger对象,直接配置logger参数的形式
def WriteLog(log_name):
    log_filename=‘./test.log‘
    log_level=logging.DEBUG
    format = logging.Formatter(‘%(asctime)s %(name)s-%(levelname)s-%(filename)s-[line:%(lineno)s]: %(message)s‘)
    handler = logging.handlers.RotatingFileHandler(log_filename,mode=‘a‘,maxBytes=10*1024*1024,backupCount=5)
    handler.setFormatter(format)
    logger = logging.getLogger(log_name)
    logger.addHandler(handler)
    logger.setLevel(log_level)
    return logger
if __name__==‘__main__‘:
    WriteLog(‘api‘).info(‘this is test‘)

调用:

#!/usr/bin/env python
# encoding: utf-8
import loggers,logging
loggers.WriteLog(‘api-2‘).info(‘sys file test log‘)

以配置文件方式配置logger:

logger.conf:

#定义logger模块,root是父类,必须存在,其他的是自定义
#logging.getLogger(NAME)就相当于向logging模块注册了实例化了
#name中用,表示 log的继承关系
[loggers]
keys=root,exp01,exp02
#[logger_xxx] logger_模块名称
#level 级别,级别有DEBUG,INFO,WARNING,ERROR,CRITICAL
#handlers 处理类,可以有多个,用逗号分割
#qualname logger名称,应用程序通过logging.getLogger获取.对于不能获取的名称,则记录到root模块
#propagate 是否继承父类的LOG信息,0:否,1:是
[logger_root]
level=DEBUG
handlers=hand01,hand02
 
[logger_exp01]
handlers=hand01,hand02
qualname=exp01
propagate=0
 
[logger_exp02]
handlers=hand01,hand02
qualname=exp02
#[handler_xxx]
#class handler 类名
#level 日志级别
#formatter 上边定义的formatter
#args handler初始化函数参数
[handlers]
keys=hand01,hand02
 
[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)
 
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=(‘test.log‘,‘a‘)
#和上边的格式一样formatter_XXX 用来格式化日志
[formatters]
keys=form01,form02
 
[formatter_form01]
format=%(asctime)s %(name)s-%(levelname)s-%(filename)s-[line:%(lineno)s]: %(message)s
datefmt=%a,%d %b %Y %H:%M:%S
 
[formatter_form02]
format=%(asctime)s %(name)s-%(levelname)s-%(filename)s-[line:%(lineno)s]: %(message)s
datefmt=%a,%d %b %Y %H:%M:%S
配置文件读取:
#!/usr/bin/env python
# encoding: utf-8
import logging,logging.config
logging.config.fileConfig("logger.conf") #配置文件名称
logger = logging.getLogger("exp01") #调用日志模版,默认一定是root
logger.debug(‘this is debug‘)
logger.info(‘this is info‘)
logger.warning(‘this is warning‘)

执行输出:

[aolens@aolens-2 ~/Documents/python/reboot]$ python sys.py
Thu,02 Mar 2017 14:29:04 exp01-INFO-sys.py-[line:7]: this is info
Thu,02 Mar 2017 14:29:04 exp01-WARNING-sys.py-[line:8]: this is warning

文件输出:

[aolens@aolens-2 ~/Documents/python/reboot]$ cat test.log
Thu,02 Mar 2017 14:03:41 exp01-DEBUG-sys.py-[line:6]: this is debug
Thu,02 Mar 2017 14:03:41 exp01-INFO-sys.py-[line:7]: this is info
Thu,02 Mar 2017 14:03:41 exp01-WARNING-sys.py-[line:8]: this is warning


原文地址:https://www.aolens.cn/?p=1251


本文出自 “aolens·程超” 博客,请务必保留此出处http://aolens.blog.51cto.com/7021142/1902668

python之logging模块使用