Reputation: 39608
I have the following code for a webserver. I have a problem that nothing is printed in httpd.log
- and I'm clueless why. The file gets created and if I add a print()
statement to log_message()
it is printed out, but nothing ever is written to the file.
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
import logging
from logging.handlers import RotatingFileHandler
class MyHandler(SimpleHTTPRequestHandler):
def __init__(self, *args):
self.logger = logging.getLogger("httpd")
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh = RotatingFileHandler("httpd.log", mode='wa',
maxBytes=1 << 20, backupCount=2)
fh.setFormatter(formatter)
fh.setLevel(logging.INFO)
self.logger.addHandler(fh)
self.logger.info("Creating HTTP Request Handler")
super(SimpleHTTPRequestHandler, self).__init__(*args)
def log_message(self, format, *args):
self.logger.info("%s - - [%s] %s\n" %
(self.address_string(),
self.log_date_time_string(),
format%args))
def main():
server = HTTPServer(('', 80), MyHandler)
server.serve_forever()
if __name__ == '__main__':
main()
This is on Python 3.1.3
Upvotes: 1
Views: 1895
Reputation: 181
open(LOGFILE, "w+").write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), format%args))
This is something you may be interested.
Upvotes: -1
Reputation: 5343
A logger can have more than one handler. Different handlers may have different log levels. The logger has its own log level which is unaffected by handlers and passes messages with appropriate log levels to the handlers to do with as they see fit.
So while your handler was interested in INFO level messages your logger was ignoring them.
The default log level of WARNING is inherited from the root logger.
Upvotes: 4
Reputation: 39608
I needed to call self.logger.setLevel(logging.INFO)
in addition to calling fh.setLevel()
If someone explains why, I'll accept that answer :)
Upvotes: 1