python logging 模块

logging用于便捷的记录日志且线程安全

1.单文件日志

import logging
logging.basicConfig(filename='log.log',
                    format=('%(asctime)s - %(name)s - %(levelname)s - %(module)s:%(message)s'),
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=logging.INFO)
"""
超过level 就会记录
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
"""
logging.critical('aaa')
logging.error('bbb')
logging.warning('ccc')
logging.info('ddd')
logging.debug('eee')
#上述都是通过调用log 来调用的
logging.log(20,'ggg')

日志记录的格式:

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

用户输出的消息

 2.写入多个文件

 基本的自定义格式:

#定义文件
filehandler1 = logging.FileHandler('file1.log','w',encoding='utf-8')
format1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(module)s:%(message)s')
filehandler1.setFormatter(format1)
#定义日志
logger1 = logging.Logger('log1',level=logging.DEBUG)
logger1.addHandler(filehandler1)
#记录日志
logger1.debug('aaa')
logger1.info('bbb')

 同时向两个日志文件写入:

#定义文件
filehandler1 = logging.FileHandler('file1.log','w',encoding='utf-8')
format1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(module)s:%(message)s')
filehandler1.setFormatter(format1)

filehandler2 = logging.FileHandler('file2.log','w',encoding='utf-8')
format2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(module)s:%(message)s')
filehandler2.setFormatter(format2)
#定义日志
logger1 = logging.Logger('log1',level=logging.DEBUG)
logger1.addHandler(filehandler1)
logger1.addHandler(filehandler2)
#记录日志
logger1.debug('aaa')
logger1.info('bbb')

 

posted @ 2017-04-29 09:07  1916  阅读(103)  评论(0)    收藏  举报