0

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?

Amanda
  • 2,013
  • 3
  • 24
  • 57
  • "I am trying to override the global method print with my own version." Let's start with that though. Why? What is the broader problem you're trying to solve? Maybe there is a better way... – Iguananaut Oct 08 '19 at 10:41
  • (To be clear, your problem is coming from the logging module, as `service`, is not one of the standard [`LogRecord` attributes](https://docs.python.org/3/library/logging.html#logrecord-attributes) Nevertheless I dont think you should be trying to override the `print()` function, and the way you're doing it currently is not going to work consistently across modules.) – Iguananaut Oct 08 '19 at 10:43
  • 1
    @Iguananaut I want to do logging across my python application. However I feel using `print` for any logging is more intuitive and natural. So I do not want to disturb this and the use of print statements across the application. I am looking for a way where every `print` is intercepted by the `logging` module so that it logs the way it wants. – Amanda Oct 08 '19 at 10:44
  • It really isn't--overriding `print()` is not very "Pythonic" and just leads to surprising behavior to anyone else who looks at your code. Though if you really want you could do something at module-level like `print = logger.info` and then use that as a replacement for `print()`. No need to mess around with `globals()`. I think a more idiomatic way to do this is to replace `sys.stdout` with a wrapper that also writes to your log, as in [this answer](https://stackoverflow.com/a/36296215/982257). – Iguananaut Oct 08 '19 at 10:48
  • Possible duplicate of [Redirect Python 'print' output to Logger](https://stackoverflow.com/questions/11124093/redirect-python-print-output-to-logger) – Iguananaut Oct 08 '19 at 10:48

0 Answers0