NameError:全局名称“记录器"未定义 [英] NameError: global name 'logger' is not defined

查看:169
本文介绍了NameError:全局名称“记录器"未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个logging.json文件,从那里设置了日志配置,之后我创建了一个类,其中所有方法都可以在其中使用,但是当我在类内使用logger进行记录时,会抛出错误NameError: global name 'logger' is not defined

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",
            "formatter": "simple",
            "filename": "logs/gp.log",
            "maxBytes": 10485760,
            "backupCount": 20,
            "encoding": "utf8"
        },

        "error_file_handler": {
            "class": "logging.handlers.RotatingFileHandler",
            "level": "ERROR",
            "formatter": "simple",
            "filename": "logs/errors.log",
            "maxBytes": 10485760,
            "backupCount": 20,
            "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__) #<<<<<<<<<<<<<<<<<<<<

您错过了logger定义.

您可以将self.logger = logging.getLogger(__name__)放入Generic.__init__()函数中,也可以像在示例中那样在导入后立即定义全局logger.

I wrote a logging.json file from where the logging configuration is setup after which i created a class in which all my methods will be there but for logging when i use logger inside the class it is throwing error NameError: global name 'logger' is not defined

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",
            "formatter": "simple",
            "filename": "logs/gp.log",
            "maxBytes": 10485760,
            "backupCount": 20,
            "encoding": "utf8"
        },

        "error_file_handler": {
            "class": "logging.handlers.RotatingFileHandler",
            "level": "ERROR",
            "formatter": "simple",
            "filename": "logs/errors.log",
            "maxBytes": 10485760,
            "backupCount": 20,
            "encoding": "utf8"
        }
    },

    "loggers": {
        "my_module": {
            "level": "ERROR",
            "handlers": ["console"],
            "propagate": "no"
        }
    },

    "root": {
        "level": "INFO",
        "handlers": ["console", "info_file_handler", "error_file_handler"]
    }
}

Problem :

When i run the program error

$ 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

Iam using the logging example following in this link [ https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/ ]

Any suggestions on how to solve this as logger is not global, any way to make it global.?

解决方案

The example you link to has:

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

you missed the logger definition.

You can either put a self.logger = logging.getLogger(__name__) in your Generic.__init__() function, or define a global logger right after the import as in the example.

这篇关于NameError:全局名称“记录器"未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆