Skip to content Skip to sidebar Skip to footer

Redirecting Sys.stdout To Python Logging

So right now we have a lot of python scripts and we are trying to consolidate them and fix and redundancies. One of the things we are trying to do, is to ensure that all sys.stdout

Solution 1:

The problem is that the logging module is looking a single layer up the call stack to find who called it, but now your function is an intermediate layer at that point (Though I'd have expected it to report cleanMsg, not __init__, as that's where you're calling into log()). Instead, you need it to go up two levels, or else pass who your caller is into the logged message. You can do this by inspecting up the stack frame yourself and grabbing the calling function, inserting it into the message.

To find your calling frame, you can use the inspect module:

importinspectf= inspect.currentframe(N)

will look up N frames, and return you the frame pointer. ie your immediate caller is currentframe(1), but you may have to go another frame up if this is the stdout.write method. Once you have the calling frame, you can get the executing code object, and look at the file and function name associated with it. eg:

code = f.f_code
caller = '%s:%s' % (code.co_filename, code.co_name)

You may also need to put some code to handle non-python code calling into you (ie. C functions or builtins), as these may lack f_code objects.

Alternatively, following up mikej's answer, you could use the same approach in a custom Logger class inheriting from logging.Logger that overrides findCaller to navigate several frames up, rather than one.

Solution 2:

I think the problem is that your actual log messages are now being created by the logy.error and logy.info calls in cleanMsg, hence that method is the source of the log messages and you are seeing this as __init__.py

If you look in the source of Python's lib/logging/__init__.py you will see a method defined called findCaller which is what the logging module uses to derive the caller of a logging request. Perhaps you can override this on your logging object to customise the behaviour?

Post a Comment for "Redirecting Sys.stdout To Python Logging"