0

我测试了以下代码以了解导入自定义 python 程序,它工作正常,但是当按照相同的过程导入自定义日志记录模块时,我看到错误。

下面工作正常

#calculation.py
from mult import product
def add(a,b):
    return a + b
if __name__== '__main__':
    a = 10
    b = 5
    print(add(a,b))
    print(product(a,b))

现在第二个程序 mult.py

# mult.py
def product(a,b):
return a * b

下面不起作用,为什么?

#test_logger.py
import loggerforhousing
print("custom logs")
logger.info("this is info")
logger.error("this is error")

第二个节目

#loggerforhousing.py
import logging    

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
file_handler = logging.FileHandler('train_123.log') # store log files in artifacts directory
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

错误信息

Traceback (most recent call last):
  File "test_logger.py", line 3, in <module>
    logger.info("this is info")
NameError: name 'logger' is not defined

请帮我弄清楚我错过了什么。

4

1 回答 1

1

test_logger.py中,将 logger 声明为loggerforhousing.py的一部分:

loggerforhousing.logger.info(“this is info”)

或显式导入记录器(如您在第一个带有产品功能的片段中所做的那样):

from loggerforhousing import logger

它有帮助吗?

于 2019-08-21T19:11:22.110 回答