about python logging

logging basics

logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('this is a debug msg')
logging.info('this is an info msg')
logging.warning('this is a warning msg')

recommend reading official tutorial

more thinking: how to log from different module in the same log file?

it gave me a headache at first. and I tried importing logging module in each module and log in the same file. it works somehow but with issues.

an obivious one of them is you are doing a lot of work with the same logic, and it is avoidable.

but how?

appoligize first I couldn’t find the post, but the idea is like this:

create a module called log_module or something like that

import logging

def get_logger(name):
  # name defines name of log file
  logging.basicConfig(filename=name, level = logging.INFO)
  logger = logging.getLogger()
  # maybe adding handler below

  return logger

so you can pass around logger, and it will always get the same logger and log to the same file.

specifically, for moduleA.py you want to use logger, just do

...
from log_module import get_logger

...