Additional to phd's answer, calling logging.basicConfig()
is a convenient function which will get you a default StreamHandler
and a Formatter
. That is enough if you want to quickly have a logging functionality. You can customize it's behaviour by passing basicConfig
some arguments:
Add Useful parameters: output timestamp alongside the message
logger = logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
This should be fine for most of the one off needs. If you need more control about your config, you can add more sophisticated behaviours by defining the logger's attributes your self.
Sophisticated Example: without using the basicConfig
function
import logging
logger = logging.getLogger("mylogger")
streamHandler = logging.StreamHandler()
streamHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
logger.info("Files copied")
logger.warning("disk quota exceeded")
>> 2017-12-06 11:11:12, 090 - mylogger - INFO Files copied
>> 2017-12-06 11:11:12, 091 - mylogger - WARNING disk quota exceeded
The next step in a bigger environment, would be deriving a new logger from the previously created one, to first keep the formatting and as well to maintain a "log hierarchy"
logger2 = logging.getLogger("mylogger.new")
logger2.info("New Logger info")
>> 2017-12-06 11:11:12, 091 - mylogger.new - New logger info
A good reference is the logging cookbook:
https://docs.python.org/2/howto/logging-cookbook.html