Simple example
import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG, encoding='utf-8')
logging.debug('this message can go to the file.')
logging.info('this a info')
logging.warning('this a warning message')
logging.error('this a error message')
# If you want to set the logging level from a command-line option such as:
--log=INFO
# If you want each run to start afresh, not remembering the messages from earlier runs, you can specify the filemode argument, by changing the call in the above example to:
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
# Changing the format of displayed message
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG)
Config by logging.conf file
# config by logging.conf file
import logging
import logging.config
logging.config.fileConfig('logging.conf')
# create logger
logger = logging.getLogger('simpleExample')
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
Here is the logging.conf file:
[loggers]
keys=root,simpleExample
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=