Python3日志记录模块:为config中的日志记录级别设置变量

时间:2017-03-14 14:14:43

标签: python-3.x logging

我在Python 3.5中使用日志记录模块,我觉得我之前已经这样做了,但我想用我的配置文件提供的常量更改日志记录级别。

目前我正在使用:

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
logger.setLevel(logging.INFO)

我想在配置文件中声明INFO,DEBUG等,并使用文字替换。

my_script_config:

LOG_LEVEL = 'DEBUG' #this value to be modified by user.

脚本:

import my_script_conf as msc
SET_LEVEL = 'logging.' + msc.LOG_LEVEL
BASIC_LEVEL = 'level=' + SET_LEVEL

logger = logging.getLogger(__name__)
logging.basicConfig(BASIC_LEVEL)
logger.setLevel(SET_LEVEL)

Python对此感到不安,对我糟糕编码的任何帮助都会非常感激。任何实现相同结果的路由,我基本上都希望它具有可读性和易用性,在外部配置文件中设置日志模块级别似乎是最明智的选择。你的pythonista可能有其他的想法!

谢谢,弗兰克

1 个答案:

答案 0 :(得分:-1)

我在另一个变量中连接了字符串,然后在变量上运行了一个exec。

my_script_config:

LOG_LEVEL = 'DEBUG' #this value to be modified by user.

脚本:

import my_script_conf as msc
SET_LEVEL = 'logger.setLevel(' + msc.LOG_LEVEL + ')
BASIC_LEVEL = 'logging.basicConfig(level=' + msc.LOG_LEVEL + ')'

logger = logging.getLogger(__name__)
exec(SET_LEVEL)
exec(BASIC_LEVEL)