Skip to content

Instantly share code, notes, and snippets.

@omsobliga
Last active August 29, 2015 14:12
Show Gist options
  • Save omsobliga/f7bdee58f67e0ada8906 to your computer and use it in GitHub Desktop.
Save omsobliga/f7bdee58f67e0ada8906 to your computer and use it in GitHub Desktop.
Get a logger that can print to file and stream in one time.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
def get_logger():
# Get a logger, default is the root logger.
logger = logging.getLogger('mylogger')
logger.setLevel(logging.INFO)
# Create a handler which can print to file.
fh = logging.FileHandler('test.log')
# Create a handler which can print to stream.
sh = logging.StreamHandler()
# Set print formatter for handler.
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
# Add handler to logger.
logger.addHandler(fh)
logger.addHandler(sh)
return logger
# Record one log.
logger = get_logger()
logger.info('Hello world!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment