def daemonLog(moduleDiscription = "test123", logPath='/root/Desktop/dns/test.log', logLevel=4):
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename=logPath,
filemode='a+')
thisLog = logging.getLogger(moduleDiscription)
logLevelDict = {
'debug': thisLog.debug('a'),
'info': thisLog.info('b'),
'warning': thisLog.warning('c'),
'error': thisLog.error('d')
}
print logLevelDict.get('info')
今天实现日志相关功能的实现的时候发现了一些比较奇葩的问题
毫无疑问用dic,和list可以实现switch的作用,而且简洁易读,但今天想用dic实现一个logging模块的不同级别的日志类型,但是发现无论是用dic还是list都会导致dic和list的所有级别的日志类型都会输出到日志文件中去
1、
# logLevelList = [thisLog.debug('a'),thisLog.info('b'),thisLog.warning('c'),thisLog.error('d')]
# print logLevelList[ 0 ]
2、
logLevelDict = {
'debug': thisLog.debug('a'),
'info': thisLog.info('b'),
'warning': thisLog.warning('c'),
'error': thisLog.error('d')
}
print logLevelDict.get('info')
1,2效果一样,已醉,目前猜测可能是在遍历的时候,list和dic中的表达式都被执行了一遍,而且由于该方式不返回值,所以取出的值为None,目测如此,所以可以采用用lambda函数的方式,这样就可以保证在遍历的时候只是取出对应的函数而不是直接执行了对应的函数,实现如下,可以达到预期效果
# coding=utf-8
import logging
def daemonLog(moduleDiscription = "test123", logPath='/root/Desktop/dns/test.log', logLevel=4):
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename=logPath,
filemode='a+')
thisLog = logging.getLogger(moduleDiscription)
logLevelDict = {
'debug': lambda: thisLog.debug('a'),
'info': lambda: thisLog.info('b'),
'warning': lambda: thisLog.warning('c'),
'error': lambda: thisLog.error('d')
}
logLevelDict.get('info')()
# thisLog.debug('z')
# thisLog.info('bb')
# thisLog.warning('c')
# thisLog.error('dddd')
daemonLog()
有种简约不简单的感觉,注意logLevelDict.get('info')()这里如果没有最后的括号你只是取出了一个函数而已,加上括号(如果你有设参数,这里需要填入参数)才表示执行了该函数