2

I know how to log message/errors I create myself:

logging.basicConfig(filename='error.log', filemode='a', level=logging.DEBUG)

logging.error(f"could not insert error: {error.args[0]}")

But this message is created when catching an exception, what if there was some uncaught error to the stderr, how can I redirect that message in the same log?

I know about redirecting error output through

python test.py 2>> error.log

But I am not sure this is the right way. I want both the messages I log myself and the stderr logged into one homogeneous log.

To be clear you cannot do this two things at the same time to same file, the permission is denied for the logging.

Borut Flis
  • 15,715
  • 30
  • 92
  • 119
  • One approach I have used previously is to make a log event in `sys.excepthook`, for an example of that see https://stackoverflow.com/q/46310034/674039. In hindsight, it's simpler and clearer just to wrap your app's `main` in a try/except, or handle this situation outside of Python entirely (i.e. configure logging to stdout or stderr within Python, and then let syslog or systemd or whatever write the streams to file). See https://12factor.net/logs for inspiration. – wim Nov 02 '21 at 00:48

0 Answers0