Skip to content

Instantly share code, notes, and snippets.

@yanxurui
Last active April 15, 2017 03:31
Show Gist options
  • Save yanxurui/084adaf6e079901c47d1f3b9ce8a7ff8 to your computer and use it in GitHub Desktop.
Save yanxurui/084adaf6e079901c47d1f3b9ce8a7ff8 to your computer and use it in GitHub Desktop.
Logging module's FileHandler doesn't write into the file
import logging
logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG) # default will not show log messages whose level is under warning
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fh)
logger.debug('what the fuck'); # use logger object to log, log handlers won't work if logging is used
logger.info('here is some infomation');
logger.error('something must be wrong');
import logging
# level>=DEBUG: output to file 'app.log'
format_str = '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s'
logging.basicConfig(
format=format_str,
filename='app.log',
filemode='w',
level=logging.DEBUG)
# level>=WARNING: print on terminal
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
formatter = logging.Formatter(format_str)
ch.setFormatter(formatter)
logging.getLogger('').addHandler(ch) # set hander for root log
#---------------------------------------
# we can see the last log in the console
# but log file spam.log is empty
#---------------------------------------
import logging
logger = logging.getLogger(__name__)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
logger.addHandler(ch)
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
logging.debug('what the fuck');
logging.info('here is some infomation');
logging.error('something must be wrong');
@yanxurui
Copy link
Author

I set logger's handler but I don't use logger instead I use root logger
debug and info logging message won't be logged because the root logger's level is WARNING by default
in addition
root logger use a destination of the console (sys.stderr) and a format "severity:logger name:message" by default

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment