3

If a module whose source code I can't change says something like:

# foo.py
import logging

logging.info('Hello world')

How can I see the logs while running

$ python foo.py

from my POSIX-compliant terminal?

All the answers I can find about this involve changing the source code.

The docs are pretty clear about logging WARN-level and above:

The INFO message doesn’t appear because the default level is WARNING.

But I can't easily see how to change that default.

LondonRob
  • 73,083
  • 37
  • 144
  • 201
  • Is this supposed to be a script, or an importable module? If it's a module, just configure logging in your own code. If it's a script, it's the script's job to provide options to configure logging. – user2357112 Jun 26 '20 at 09:46
  • (And if it's a script with no options to configure logging, then it's likely that those logs were never meant to be shown to users at all - maybe they're a debug thing that got left in, or unnecessary code that got copy-pasted from a program that did have configurable logging.) – user2357112 Jun 26 '20 at 09:49
  • Also, do you really mean stdout? When logging to a standard stream, the usual choice is stderr. – user2357112 Jun 26 '20 at 09:51
  • Yeah, I should've said "the screen". I don't care between stdout and stderr. – LondonRob Jun 26 '20 at 10:31

1 Answers1

3

Run the script with an incantation that preconfigures logging for you (now 100% more Python3 compatible).

$ cat foo.py
import logging
logging.info('Hello world')

$ python3 -c 'import logging,sys,runpy;logging.basicConfig(level=logging.INFO,stream=sys.stdout);runpy.run_path("foo.py")'
INFO:root:Hello world
~/Desktop

Not memorable enough?

To make it more memorable, you can wrap things in a please_log.py. Some sys.argv finagling is required.

please_log.py

import logging, sys, runpy
script = sys.argv.pop(1)
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
runpy.run_path(script)

foo.py

import logging
import sys

logging.info('Hello world: %s', sys.argv)

output

$ python3 please_log.py foo.py
INFO:root:Hello world: ['foo.py']
AKX
  • 152,115
  • 15
  • 115
  • 172