python - 调用日志配置函数后“'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'
我检查了导入其他功能,它工作正常,问题仅出在记录器上。我不知道为什么
解决方案
logging.basicConfig
不返回任何东西(从技术上讲,它返回None
)。因此,返回值解释了你得到的错误logger_main
。None
你有:
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
推荐阅读
- linker - 网站注册号以电话号码链接的形式出现,有没有办法逃脱?
- python - Selenium 的 XPath 问题
- python - 除了在 OpenCV (Python) 中作为坐标提供的多边形之外的遮光图像
- sql - 访问 - 选择从一对多表中返回“一”的查询
- reactjs - 从 react-redux、Parent vs Child 组件中使用 connect() 的首选方式是什么?
- swift - SpriteKit - 如何修复节点动画中的失真?
- xml - 如何使用带有约束的 DOM 针对 XSD 验证 XML?
- spring-data-mongodb - mongodb 的 querydsl 是否支持 $text (full text) 搜索?(使用带有spring数据mongodb的querydsl)
- r - R中自动一张一张选择图像文件的功能
- javascript - 这里的 setState 回调语法有什么区别?