0

I'm trying to migrate from elaborate, if(debug): flagged, print statements for debugging to using the builtin logging module. I really like that I can log output both to a log file, and to stdout (for example, see this question). I'm interested in doing the reverse; can I include stdout information into the logger?

Edit: I dont want to "Redirect" stdout to the log, I want to include it in the log... in addition to going to stdout.


For example,

print "Loading data"
sources = getSources(params)
logging.debug("> From %d sources" % (len(sources)))
data = loadData(sources)

def getSources(params):
    logging.info(">> Using parameters : %s" % (params))
    ...
    return sources

Let's say that logging is sending to both stdout and to a log file. It's great that "Loading Data" is always printed, and I can choose how much of the next two statements are:

Loading Data
> From ___ sources
>> Using parameters : ___

But how can I also get "Loading Data" logged to the log file?


The two options I've considered are:

1) Writing two statements which is annoying and clumsy:

print "Loading Data"
logging.info("Loading Data")

or, 2) using critical to log for all levels, but this seems abusive...

logging.critical("Loading Data")
Community
  • 1
  • 1
DilithiumMatrix
  • 17,795
  • 22
  • 77
  • 119
  • @MartijnPieters edited to explain – DilithiumMatrix Jul 25 '15 at 18:02
  • So the other solution cannot be adapted? Just write to the original `sys.stdout` *as well*. – Martijn Pieters Jul 25 '15 at 18:04
  • @MartijnPieters Then I'm in the same position as the (1) attempt I described: duplicating the output statement. i.e. `print "Loading Data"; sys.stdout.write("Loading Data")` – DilithiumMatrix Jul 25 '15 at 18:07
  • No, have the `LogWriter` class log both to the logger *and* write to `sys.stdout` (or rather, to a saved reference to that object, since you'll be replacing `sys.stdout` with the `LogWriter` instance). – Martijn Pieters Jul 25 '15 at 18:10
  • @MartijnPieters, I think that's effectively the solution I linked to in [this answer](http://stackoverflow.com/questions/14058453/making-python-loggers-output-all-messages-to-stdout-in-addition-to-log)... which ties into my attempt (2) ---- which, in deed, might be the only/best solution. – DilithiumMatrix Jul 25 '15 at 18:22

0 Answers0