首页 > 解决方案 > 调用日志配置函数后“'NoneType'对象没有属性'info'”

问题描述

我想将记录器函数 logger_main(name) 从文件 Logger.py 导入到同一目录 /GeneralScripts 中的另一个文件。该目录在 PyCharm 中被标记为 Source,并且在 /GeneralScripts 中也添加了一个文件init .py。

所以我从 GeneralScripts.Logger import logger_main 导入它

记录器如下所示:

def logger_main(name):
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)
    logger = logging.basicConfig(filename='{}.log'.format(name),
                                 level=logging.INFO,
                                 format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
                                 datefmt='%Y-%m-%d:%H:%M:%S')
    return logger

我导入它的文件如下所示:

# import modules
import os
import pyodbc
from sqlalchemy import create_engine
import urllib
import json
from GeneralScripts.Logger import logger_main
import logging

# credentials
with open('cred_db', 'r') as file:
    cred_db = json.load(file)


# set the logger
logging = logger_main('DB')

def connect_to_db():
    """Connects to the database Controlling_Marketing.
    :return: engine instance
    """
    try:
        params = urllib.parse.quote_plus('DRIVER={driver};SERVER={server};DATABASE={database};UID={uid};PWD={pwd};Port={port};'.format(**cred_db))
        engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(params))
        logging.info('Connected to the DB Controlling_Marketing')
        return engine
    except Exception as e:
        logging.error("Exception occurred, check def connect_to_db", exc_info=True)

# run it
engine = connect_to_db()

当我运行它时,会发生异常

logging.info('Connected to the DB Controlling_Marketing')
AttributeError: 'NoneType' object has no attribute 'info'

logging.error("Exception occurred, check def connect_to_db", exc_info=True)
AttributeError: 'NoneType' object has no attribute 'error'

我检查了导入其他功能,它工作正常,问题仅出在记录器上。我不知道为什么

标签: pythonloggingimport

解决方案


logging.basicConfig不返回任何东西(从技术上讲,它返回None)。因此,返回值解释了你得到的错误logger_mainNone

你有:

import logging
…
logging = logger_main('DB')  # now logging is None
…
logging.info('...')          # --> 'NoneType' has no attribute 'info'

不要将结果分配给logger_main('DB')to logging,以便logging在调用时仍然引用日志记录模块logging.info

import logging
…
logger_main('DB')    # do not assign
…
logging.info('...')  # now logging is the logging module

推荐阅读