How can I set up the basic logging to write to a logfile and also print output to terminal?
I use basicConfig to set up logging for modules and sub modules.
Problem: If I use logging.basicConfig(filename=LOGFILE, …) there is no more terminal output from logging module. If I add another FileHandler for the logfile, this is only used by main module and not by sub modules, example:
if __name__ == "__main__":
logging.basicConfig(
level=logging.DEBUG,
format="%(name)s (%(lineno)s): %(message)s",
filename=LOGFILE
)
# add logfile
formatter = logging.Formatter("%(name)s (%(lineno)s): %(message)s")
logfile = logging.FileHandler(LOGFILE)
logfile.setLevel("DEBUG")
logfile.setFormatter(formatter)
Using Python 2.7
Update
Just found https://stackoverflow.com/a/13733863/1907997 but example is not working, no output on terminal or file:
if __name__ == "__main__":
logFormatter = "%(name)s (%(lineno)s): %(message)s"
rootLogger = logging.getLogger()
fileHandler = logging.FileHandler(LOGFILE)
fileHandler.setFormatter(logFormatter)
fileHandler.setLevel("DEBUG")
rootLogger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
consoleHandler.setLevel("DEBUG")
rootLogger.addHandler(consoleHandler)
Info for newer Python Version:
. Since Python 3.3 logging.basicConfig() can take a keyword argument handlers https://stackoverflow.com/a/46098711/1907997