0

I'm trying to add logs to my code instead of printing everything. I read a bunch of other posts and articles, such as the ones listed here, but the logs in my code do not print.

Here's an example:

# driver.py
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

def main():
    logging.debug('This is a simple log')
    # other code here


if __name__ == "__main__":
     main()

But my log does not print to stdout. What am I doing wrong?

Also, if I want to add logging to multiple files, can I configure the log on a separate file, import that file on my driver.py and helper_funtions.py for example, so I don't have to repeat the same thing over and over?

Xue Xu
  • 55
  • 1
  • 9
  • 2
    Add [`logging.basicConfig()`](https://docs.python.org/3/library/logging.html#logging.basicConfig) before any other logger config! – Klaus D. Jul 09 '19 at 14:52

1 Answers1

1

You need a StreamHandler

ch = logging.StreamHandler()
logger.add_handler(ch)

The logging cookbook provides plenty of examples on setting up streamhandlers as well as logging to a file. You can even configure the format of the logs to StdOut look different that that of the the file.

https://docs.python.org/3/howto/logging-cookbook.html#logging-cookbook

drewa
  • 11
  • 2