我是第一次使用日志记录模块。我能够按照我的要求编写程序。 try和except内部编写的逻辑也几乎可以成功运行,并且在日志文件中生成了日志。但是由于某种原因,我在IDE控制台上看到所有“ logging.info”和“ logging.exception”的“ AttributeError”。因此,为了进行交叉验证,我注释掉了所有这些位置,这一次我的代码运行无任何错误,但日志文件中未记录任何内容。这很明显。下面是整个程序
import logging
from logging.handlers import TimedRotatingFileHandler
logger = logging.handlers.TimedRotatingFileHandler('amitesh.log', when='midnight', interval=1)
logger.suffix = '%y_%m_%d.log'
# create a logging format
LOGGING_MSG_FORMAT = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger.setFormatter(LOGGING_MSG_FORMAT)
LOGGING_DATE_FORMAT = '%d-%b-%y %H:%M:%S'
# create basic configuration
logging.basicConfig(level=logging.INFO, format=LOGGING_MSG_FORMAT, datefmt=LOGGING_DATE_FORMAT)
root_logger = logging.getLogger('')
# add the handlers to the logger
root_logger.addHandler(logger)
while True:
print(" ")
print("This is a Logging demo")
print(" ")
logging.info("new request came")
print(" ")
try:
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
print(x / y)
except ZeroDivisionError as msg:
print("cannot divide with zero")
logging.exception(msg)
print(" ")
except ValueError as msg:
print("enter only integer value")
logging.exception(msg)
print(" ")
logging.info("executed successfully")
print(" ")
以下是我的IDE控制台中的错误消息:
return self._fmt.find(self.asctime_search) >= 0
AttributeError: 'Formatter' object has no attribute 'find'
Call stack:
File "/Users/amitesh/PycharmProjects/Automation/Databases/DB_Conn.py", line 68, in <module>
logging.info("new request came")
Message: 'new request came'
Arguments: ()
过去2天,我没有任何运气就上网了。 请帮助我找出我的错误。
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 388, in usesTime
return self._fmt.find(self.asctime_search) >= 0
AttributeError: 'Formatter' object has no attribute 'find'
Call stack:
File "/Users/amitesh/PycharmProjects/Automation/Databases/DB_Conn.py", line 68, in <module>
logging.info("new request came")
Message: 'new request came'
Arguments: ()
谢谢。
答案 0 :(得分:0)
删除了format = LOGGING_MSG_FORMAT,LOGGING_MSG_FORMAT,并直接使用“ format”参数定义了basicConfig内部的值,因为参数“ format”采用字符串而不是Formatter类型。