Thursday, February 25, 2016

python logging on both file and console

http://stackoverflow.com/questions/13733552/logger-configuration-to-log-to-file-and-print-to-stdout

http://victorlin.me/posts/2012/08/26/good-logging-practice-in-python

#!/usr/bin/env python

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# create a file handler

handler = logging.FileHandler('hello.log')
handler.setLevel(logging.INFO)

# create a logging format

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handlers to the logger

logger.addHandler(handler)


logger.info('Hello baby')

# handler2

logger2 = logging.getLogger(__name__ + '2')
logger2.setLevel(logging.INFO)

handler2 = logging.StreamHandler()
handler2.setLevel(logging.INFO)

# create a logging format

formatter2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler2.setFormatter(formatter2)

# add the handlers to the logger

logger2.addHandler(handler2)

logger2.info('Hi Baba!')

No comments:

Post a Comment