#coding: UTF-8
'''
Created on 2014年1月6日
@author: mingliu
'''
import logging#导入
mylog = logging.getLogger('mylogger')#申请一个名字
otherlog = logging.getLogger('mylogger')#同一个工程下面全部logger全可以统一根据名字获得,享用相同配置
mylog.setLevel(logging.ERROR)#设置输出级别
fh = logging.FileHandler('test.log')#设置输出信息物理位置(文件)
fh.setLevel(logging.DEBUG)#设置handler输出级别
ch = logging.StreamHandler()#设置输出控制台
ch.setLevel(logging.INFO)
formatter = logging.Formatter("%(pathname)s-%(module)s - \
%(lineno)d -%(asctime)s - %(name)s - %(levelname)s-%(levelno)s-%(thread)d\n%(message)s")#输出信息格式
fh.setFormatter(formatter) #向handler添加输出格式
ch.setFormatter(formatter)
mylog.addHandler(fh)#向logger添加handler
mylog.addHandler(ch)
if __name__ == '__main__':
pass
mylog.debug('testDebug')
mylog.info('testInfo')
mylog.warn('testWarn')
mylog.error('testError')
otherlog.debug('testDebug')
otherlog.info('testInfo')
otherlog.warn('testWarn')
otherlog.error('testError')
使用配置文件
程序:
logging.config.fileConfig("logging.conf")
mylog = logging.getLogger('mylogger')#申请一个名字
配置文件:
[loggers]
keys=root,mylogger
[handlers]
keys=consoleHandler,fileHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_mylogger]
level=DEBUG
handlers=consoleHandler,fileHandler
qualname=simpleExample
propagate=0
[handler_fileHandler]
class=FileHandler
level=ERROR
formatter=simpleFormatter
args=('test.log',)
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s