python logging module is not writing anything to file

file, logging, python, python-logging

Solution

Try calling

logger.error('This should go to both console and file')

instead of

logging.error('this will go to the default logger which you have not changed the config of')

Problem

I'm trying to write a server that logs exceptions both to the console and to a file. I pulled some code off the cookbook. Here it is: ``` logger = logging.getLogger('server_logger') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler('server.log') fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.ERROR) # create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') ch.setFormatter(formatter) fh.setFormatter(formatter) # add the handlers to logger logger.addHandler(ch) logger.addHandler(fh) ``` This code logs perfectly fine to the console, but nothing is logged to the file. The file is created, but nothing is ever written to it. I've tried closing the handler, but that doesn't do anything. Neither does flushing it. I searched the Internet, but apparently I'm the only one with this problem. Does anybody have any idea what the problem is? Thanks for your answers.

Original source

Related problems