Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python logging module is not writing anything to file

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.

like image 587
thePurpleMonkey Avatar asked Apr 09 '13 03:04

thePurpleMonkey


People also ask

How do I enable logging in Python?

You can configure logging as shown above using the module and class functions or by creating a config file or a dictionary and loading it using fileConfig() or dictConfig() respectively. These are useful in case you want to change your logging configuration in a running application.

Where does logger info write to Python?

We can also use the logging. FileHandler() function to write logs to a file in Python. This function takes the file path where we want to write our logs. We can then use the addHandler() function to add this handler to our logger object.

How does logging module work Python?

Logging in Python is simple and well-standardized, thanks to a powerful logging framework right in the standard library. Modules should simply log everything to a logger instance for their module name. This makes it easy for the application to route log messages of different modules to different places, if necessary.


2 Answers

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') 
like image 151
Leopd Avatar answered Sep 23 '22 08:09

Leopd


Try to put the import and the basicConfig at the very beggining of the script. Something like this:

import logging logging.basicConfig(filename='log.log', level=logging.INFO) . . import ... import ... 
like image 21
Fernando Benito Avatar answered Sep 24 '22 08:09

Fernando Benito