You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.9实现自定义logger偶发ValueError、TypeError且不输出日志级别求助

问题原因及修复方案

1. ValueError: Unrecognised argument(s): force 错误原因

logging.basicConfig的force参数是Python 3.8版本才新增的参数,你声称使用Python3.9但运行时出现该报错,说明实际运行代码的Python环境版本低于3.8,环境不一致才会出现有时运行正常有时报错的不稳定情况。
另外不建议每次调用log方法时都执行basicConfig,该配置全局只需要执行一次即可,重复配置属于冗余操作。

2. TypeError: 'int' object is not callable 错误原因

你混淆了日志级别常量和日志输出方法:

  • logger.ERROR、logger.CRITICAL是表示日志级别的整数常量,不是可调用的方法
  • 对应的日志输出方法是小写的logger.error()、logger.critical()

3. 日志不输出级别信息的原因

你在basicConfig的format参数中没有配置级别的占位符,需要新增%(levelname)s字段才能输出日志级别。


修复后的代码
import logging as logger

# 日志配置全局只执行一次
logger.basicConfig(
    filename="datalog.log",
    level=logger.INFO,
    # 如果你确定运行环境都是3.8及以上可以保留force参数,否则删除
    # force=True,
    format='%(asctime)s %(levelname)s %(message)s'
)

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):
        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()

内容的提问来源于stack exchange,提问作者binayak choudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:57:03