python 用list,dic实现switch功能的一个奇葩现象

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')()这里如果没有最后的括号你只是取出了一个函数而已,加上括号(如果你有设参数,这里需要填入参数)才表示执行了该函数


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值