Monthly Archives: September 2017

Python Logging Config Sample with Multiple Sinks

Multiple sinks for default logger’s levels

[loggers]
keys=root

[handlers]
keys=consoleHandler, fileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler, fileHandler

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[handler_fileHandler]
class=FileHandler
level=INFO
formatter=simpleFormatter
args=("%(log_path)s/%(log_filename)s", "a", "utf-8", False)

[formatter_simpleFormatter]
format=[%(levelname)-8s] - %(asctime)s (%(threadName)-10s) %(message)s

Test like this:

import logging
import logging.config
from logging import debug, log
from os import path


def main():
    debug("Hello %s", 1)


if __name__ == "__main__":
    logging.config.fileConfig(
        r"C:\Workspace\Python\VS Code\Logging\default.conf",
        {
            'log_path': path.dirname(path.realpath(__file__)),
            'log_filename': "%s.log" % path.basename(__file__)[:-3]
        }
    )

    log(logging.INFO, "Started")
    main()
    log(logging.INFO, "Finished")