Program runs using 2.6.9 without any dependencies:
#!/user/bin/env python
"""
An example python 2.6 script which takes arguments and logs to console/file.
"""
import logging
import logging.config
import optparse
def main():
logging.config.fileConfig('logging.conf')
log = logging.getLogger('kittest')
log.info('kittest starting...')
try:
usage = "usage: %prog [options]"
parser = optparse.OptionParser(usage)
parser.add_option('--source_db', dest="source_db", help='source database')
parser.add_option('--source_table', dest="source_table", help='source table')
(options, args) = parser.parse_args()
log.info('Source is %s.%s', options.source_db, options.source_table)
except:
log.exception('Error in main')
raise
log.info('kittest complete!')
if __name__ == '__main__':
main()
Log configuration file logging.conf:
[loggers]
keys=root
[handlers]
keys=consoleHandler,rotatingFileHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler,rotatingFileHandler
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[handler_rotatingFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=('app.log', 'a', 1000, 3)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
Dependency on PyYAML.
#!/user/bin/env python
"""
An example python script which takes arguments and logs to console/file. Requires PyYAML to parse config.
"""
import logging
import logging.config
import argparse
import yaml
def main():
with open('logging.yaml', 'r') as logconfig:
cfg = yaml.safe_load(logconfig)
#logging.config.fileConfig('logging.conf')
logging.config.dictConfig(cfg)
log = logging.getLogger('kittest')
log.info('kittest starting...')
parser = argparse.ArgumentParser(description='Kit\'s test python script')
parser.add_argument('source_db', help='source database')
parser.add_argument('source_table', help='source table')
args = parser.parse_args()
log.info('Source is %s.%s', args.source_db, args.source_table)
for
log.info('kittest complete!')
if __name__ == '__main__':
main()
Logging configuration file logging.yaml:
version: 1
formatters:
simple:
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
console:
class : logging.StreamHandler
formatter: simple
stream : ext://sys.stdout
file:
class : logging.handlers.RotatingFileHandler
formatter: simple
filename: kittest.log
maxBytes: 1024
backupCount: 3
root:
level: DEBUG
handlers: [console,file]