1

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

1 Answer 1

0

Just found a solution:

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s (%(lineno)s) - %(levelname)s: %(message)s",
    datefmt='%Y.%m.%d %H:%M:%S', 
    filename=LOGFILE
    )

rootLogger = logging.getLogger("")
logFormatter = logging.Formatter("%(asctime)s - %(name)s (%(lineno)s) - %(levelname)s: %(message)s")
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
consoleHandler.setLevel("DEBUG")
rootLogger.addHandler(consoleHandler)

found here: https://stackoverflow.com/a/23681578/1907997

Sign up to request clarification or add additional context in comments.

Comments

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.