Simple Log File Handler in Python

For the next time I need to use this…

import logging
import sys

def setup_custom_logger(name):
    formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                                  datefmt='%Y-%m-%d %H:%M:%S')
    handler = logging.FileHandler('log.txt', mode='w')
    screen_handler = logging.StreamHandler(stream=sys.stdout)
    logger = logging.getLogger(name)
    return logger

>>> logger = setup_custom_logger('myapp')
>>>'This is a message!')
2015-02-04 15:07:12 INFO     This is a message!
>>> logger.error('Here is another')
2015-02-04 15:07:30 ERROR    Here is another

Credit to paidhima on the below Stack Overflow answer:

One thought on “Simple Log File Handler in Python

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s