#!/usr/bin/env python # -*- coding: utf-8 -*- """ An example of using JSON for log configuration """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import import json import logging import logging.config def main(): # each time we need to log something we can create a logger object # The operation of creating a logger should be quite cheap. # getLogger() without arguments returns the "root" logger. logger = logging.getLogger() logger.info("This is an INFO message on the root logger.") # If we need to separate things, we can always create child loggers: child = logging.getLogger().getChild("child") child.warning("This is a WARNING message on the child logger.") # let's create an error. This will send an email child.error("This is an ERROR message.") if __name__ == "__main__": # create an initial logger. It will only log to console and it will disabled # when we read the logging configuration from the config file. # This logger can be useful when we need early logging. E.g. we may want to log # the location of the JSON file (e.g. if we get it from a CLI argument). logging.basicConfig(level="INFO") logger = logging.getLogger() logger.info("This is the logger configured by `logging.basicConfig()`.") # set up proper logging. This one disables the previously configured loggers. with open("logging.json", "r", encoding="utf-8") as fd: logging.config.dictConfig(json.load(fd)) main()