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.

4
  • 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. Commented Jun 26, 2020 at 9: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.) Commented Jun 26, 2020 at 9:49
  • Also, do you really mean stdout? When logging to a standard stream, the usual choice is stderr. Commented Jun 26, 2020 at 9:51
  • Yeah, I should've said "the screen". I don't care between stdout and stderr. Commented Jun 26, 2020 at 10:31

1 Answer 1

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']
Sign up to request clarification or add additional context in comments.

5 Comments

I'll be sad if this turns out to be the best we can do here. Not exactly memorable!
Added a wrapper script option.
execfile doesn't exist in Python 3.
@user2357112supportsMonica Oop, good point. Fixed :)
It does indeed seem like maybe logging doesn't have anything which can do better than this. I'd sort of expected there to be a OVERRIDE_LOG_LEVEL=INFO python ... envvar solution. Ah well. I live and learn.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.