我正在尝试使用自己的版本覆盖全局方法print
。我试图使用python的全局字典覆盖该方法。但这会引发错误。
import logging
format = '%(asctime)s %(message)s %(name)s - %(levelname)s | %(service)s - %(m)s'
formatter = logging.Formatter(format)
logging.basicConfig(format=format)
file_handler = logging.FileHandler("app.log")
logger = logging.getLogger('root-logger')
logger.addHandler(file_handler)
file_handler.setFormatter(formatter)
def p():
logger.warning("hello")
globals()['print'] = p
print()
我得到的错误是:
--- Logging error ---
Traceback (most recent call last):
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 1025, in emit
msg = self.format(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 869, in format
return fmt.format(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 611, in format
s = self.formatMessage(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 580, in formatMessage
return self._style.format(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 422, in format
return self._fmt % record.__dict__
KeyError: 'service'
Call stack:
File "test.py", line 24, in <module>
print()
File "test.py", line 18, in p
logger.warning("hello")
Message: 'hello'
Arguments: ()
--- Logging error ---
Traceback (most recent call last):
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 1025, in emit
msg = self.format(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 869, in format
return fmt.format(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 611, in format
s = self.formatMessage(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 580, in formatMessage
return self._style.format(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 422, in format
return self._fmt % record.__dict__
KeyError: 'service'
Call stack:
File "test.py", line 24, in <module>
print()
File "test.py", line 18, in p
logger.warning("hello")
Message: 'hello'
Arguments: ()
如何覆盖默认的打印方法,以便可以在应用程序中与python的日志记录模块同步使用它?