简体   繁体   中英

Nothing is written to file when I override `log_message()` in `SimpleHTTPRequestHandler`

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

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.

I needed to call self.logger.setLevel(logging.INFO) in addition to calling fh.setLevel()

If someone explains why , I'll accept that answer :)

 open(LOGFILE, "w+").write("%s - - [%s] %s\n" % (self.address_string(), self.log_date_time_string(), format%args)) 

您可能对此感兴趣。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM