I am trying to override the global method print
with my own version. I tried to override the method using the python's global dictionary. But it throws an error.
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()
The error that I get is:
--- 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: ()
How can I override the default print method so that I can use it across the application in sync with the python's logging module?