Xue Xu
Xue Xu

Reputation: 55

Correct way to work with the `logging` module in Python

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?

Upvotes: 0

Views: 198

Answers (1)

drewa
drewa

Reputation: 11

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

Upvotes: 1

Related Questions