gpt4 book ai didi

python - 本地函数无法识别记录器

转载 作者:行者123 更新时间:2023-11-30 23:05:18 27 4
gpt4 key购买 nike

我有一个 python 代码(如下),它在下面进一步发出错误,我不明白问题出在哪里。据我了解python HOWTO记录器应该可供定义记录器的 main() 调用的例程使用。我正在使用 python 2.7.10。

#!/usr/bin/python

import logging
import sys

def setup():
logger.debug('some text')
return 0

def main():
logger = logging.getLogger('some_logger_name')
logger.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
consoleHandler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
logger.addHandler(consoleHandler)

ret = setup()

if __name__=='__main__':
sys.exit(main()) # Exit python upon execution of main().

这是我运行 $python test.py 时收到的错误消息:

Traceback (most recent call last):
File "test.py", line 20, in <module>
sys.exit(main()) # Exit python upon execution of main().
File "test.py", line 17, in main
ret = setup()
File "test.py", line 7, in setup
logger.debug('some text')
NameError: global name 'logger' is not defined

有人看到我的错误吗?

编辑:感谢到目前为止的回复!您能否解释一下我的版本和我上面提到的 python HOWTO 上的版本之间的区别(我在下面附加了相关摘录)。

If your program consists of multiple modules, here’s an example of how you could organize logging in it:

# myapp.py
import logging
import mylib

def main():
__logging.basicConfig(filename='myapp.log', level=logging.INFO)
__logging.info('Started')
__mylib.do_something()
__logging.info('Finished')

if __name__ == '__main__':
__main()

这是模块mylib.py:

# mylib.py
import logging

def do_something():
__logging.info('Doing something')

If you run myapp.py, you should see this in myapp.log:

INFO:root:Started
INFO:root:Doing something
INFO:root:Finished

which is hopefully what you were expecting to see. You can generalise this to multiple modules, using the pattern in mylib.py.

Arg,对于奇怪的编辑感到抱歉。我不明白我应该如何格式化引用的代码。

最佳答案

记录器是在 main() 中设置的局部变量您需要在全局空间中声明它。

logger=None
def setup():
logger.debug('some text')
return 0

def main():
global logger
logger = logging.getLogger('some_logger_name')
logger.setLevel(logging.DEBUG)

ret = setup()

关于python - 本地函数无法识别记录器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33212184/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com