Search code examples
pythonloggingstderr

The right way to output an error message from a Python library


I now have in my Python code:

sys.stderr.write("Iteration stopped to avoid infinite loop.\n")

but this code always writes to stderr no matter what the client of the code wants.

I would use a logger instead, but that would output to stderr a message like:

:INFO:main:Iteration stopped to avoid infinite loop.

instead of

Iteration stopped to avoid infinite loop.

I do not want :INFO:main: for this particular message.

So my questions:

  • Can I configure a logger to not output :INFO:main:?

  • What else except Python logger can I use?

If there is no such class in Python installations, then what should be the interface of my own logger class? Should it be like

class MyLogger(object):
    @abstractmethod
    def log(msg):
        pass

or what may I miss (maybe add some other methods, maybe some additional log() arguments)?


Solution

  • You can modify basicConfig to change the error message

    import logging
    logging.basicConfig(format='%(message)s')
    logging.warning("Iteration stopped to avoid infinite loop.")