加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – NameError:未定义全局名称“logger”

发布时间:2020-12-20 12:34:40 所属栏目:Python 来源:网络整理
导读:我写了一个logging.json文件,其中设置了日志配置,之后我创建了一个类,其中我的所有方法都在那里但是当我在类中使用logger时它会抛出错误NameError:全局名称’logger’是没有定义的 app.py #/usr/bin/pythonimport sysimport loggingimport timeimport jsoni
我写了一个logging.json文件,其中设置了日志配置,之后我创建了一个类,其中我的所有方法都在那里但是当我在类中使用logger时它会抛出错误NameError:全局名称’logger’是没有定义的

app.py

#/usr/bin/python

import sys
import logging
import time
import json
import os
import logging.config

def setup_logging(default_path='logging.json',default_level=logging.INFO,env_key='LOG_CFG'):
    """Setup logging configuration"""
    path = default_path
    value = os.getenv(env_key,None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path,'rt') as f:
            config = json.load(f)
        logging.config.dictConfig(config)
    else:
        logging.basicConfig(level=default_level)

class Generic:

        def __init__(self,file_path):
                self.file_path = file_path

        def check_mime(self):
                logger.info('Generic on file {} starts at {}'.format(file_path,time.time()))


print 'File path is {}'.format(sys.argv[1])
file_path = sys.argv[1]

def parser():
        parser = Generic(file_path)
        parser.check_mime()
def main():
        print 'This is intended for module purpose only'
        setup_logging()
        parser()

if __name__ == '__main__':
        main()

logging.json

{
    "version": 1,"disable_existing_loggers": false,"formatters": {
        "simple": {
            "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    },"handlers": {
        "console": {
            "class": "logging.StreamHandler","level": "DEBUG","formatter": "simple","stream": "ext://sys.stdout"
        },"info_file_handler": {
            "class": "logging.handlers.RotatingFileHandler","level": "INFO","filename": "logs/gp.log","maxBytes": 10485760,"backupCount": 20,"encoding": "utf8"
        },"error_file_handler": {
            "class": "logging.handlers.RotatingFileHandler","level": "ERROR","filename": "logs/errors.log","encoding": "utf8"
        }
    },"loggers": {
        "my_module": {
            "level": "ERROR","handlers": ["console"],"propagate": "no"
        }
    },"root": {
        "level": "INFO","handlers": ["console","info_file_handler","error_file_handler"]
    }
}

问题:

当我运行程序错误

$python app.py /home/default/domain.txt
File path is /home/default/domain.txt
This is intended for module purpose only
Traceback (most recent call last):
  File "app.py",line 44,in <module>
    main()
  File "app.py",line 41,in main
    parser()
  File "app.py",line 37,in parser
    parser.check_mime()
  File "app.py",line 29,in check_mime
    logger.info('GenericParser
NameError: global name 'logger' is not defined

我在此链接中使用以下日志记录示例[https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/]

关于如何解决这个问题作为记录器的任何建议都不是全局性的,任何使其成为全局的方法.

解决方法

您链接的示例包含:

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) #<<<<<<<<<<<<<<<<<<<<

你错过了记录器的定义.

您可以在您的Generic .__ init __()函数中放置self.logger = logging.getLogger(__ name__),也可以在导入后立即定义全局记录器,如示例所示.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读