Last active
August 29, 2015 14:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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