首页 > 解决方案 > 在 python 中记录可用性

问题描述

我在 python 中实现一个简单的记录器。在下面找到我的代码,有时它运行良好,有时我得到ValueError at self.log('INFO','Append operation successful.')

我在哪里做错了?我是 python 新手,也参考过文档。无法理解不一致之处,我也在使用 python 3.9,也尝试使用 force 参数。它也不会记录级别,例如严重、信息或错误。

import logging as logger
class data:
    def __init__(self, filename,filetype,filesize,date):
        self.filename=filename
        self.filetype=filetype
        self.filesize=filesize
        self.date=date
        
    def log(self,logtype,msg):
        logger.basicConfig(filename="datalog.log",level=logger.INFO,force=True,format='%(asctime)s %(message)s')
        if logtype == "INFO":
            logger.info(msg)
        elif logtype == "ERROR":
            logger.ERROR(msg)
        elif logtype == "CRITICAL":
            logger.CRITICAL(msg)
        else:
            logger.info(msg)
        
    def openFile(self):
        try:
            filename=self.filename+self.filetype
            f=open(filename,'w+')
            f.write("Hello, Lets learn OOPs in Python")
            f.close()
            self.log('INFO','Write operation successful.')
        except Exception as e:
            self.log('ERROR','Writing operation failed.')
        
    def appendFile(self):
        try:
            f=open(self.filename+self.filetype,'a')
            f.write("Appending some extra content")
            f.close()
            self.log('INFO','Append operation successful.')
        except Exception as e:
            self.log('ERROR','Append operation failed.')

sample = data('sample','.txt','1Mb','2021-08-20')
sample.appendFile()
sample.openFile()

错误:

ValueError: Unrecognised argument(s): force

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-1-e095529812fd> in log(self, logtype, msg)
     12             logger.info(msg)
     13         elif logtype == "ERROR":
---> 14             logger.ERROR(msg)
     15         elif logtype == "CRITICAL":
     16             logger.CRITICAL(msg)

TypeError: 'int' object is not callable

标签: python-3.xloggingvalueerror

解决方案


force选项basicConfig仅在 Python 3.8+ 中可用。检查您的 Python 版本。

此外,在每个日志事件上强制重新配置日志系统可能不是一个好主意。只需在应用程序的主入口点配置一次。


推荐阅读