1
0
Fork 0
forked from github/pelican
pelican-theme/pelican/server.py
Deniz Turgut ed3209888a Refactor logging handling
Old system was using manual string formatting for log messages.
This caused issues with common operations like exception logging
because often they need to be handled differently for Py2/Py3
compatibility. In order to unify the effort:

 - All logging is changed to `logging.level(msg, arg1, arg2)` style.
 - A `SafeLogger` is implemented to auto-decode exceptions properly
in the args (ref #1403).
 - Custom formatters were overriding useful logging functionality
like traceback outputing (ref #1402). They are refactored to be
more transparent. Traceback information is provided in `--debug`
mode for `read_file` errors in generators.
 - Formatters will now auto-format multiline log messages in order
to make them look related. Similarly, traceback will be formatted in
the same fashion.
 - `pelican.log.LimitFilter` was (ab)using logging message which
would result in awkward syntax for argumented logging style. This
functionality is moved to `extra` keyword argument.
 - Levels for errors that would result skipping a file (`read_file`)
changed from `warning` to `error` in order to make them stand out
among other logs.
 - Small consistency changes to log messages (i.e. changing all
to start with an uppercase letter) and quality-of-life improvements
(some log messages were dumping raw object information).
2014-07-22 12:39:39 -04:00

52 lines
1.6 KiB
Python

from __future__ import print_function
import os
import sys
import logging
try:
import SimpleHTTPServer as srvmod
except ImportError:
import http.server as srvmod # NOQA
try:
import SocketServer as socketserver
except ImportError:
import socketserver # NOQA
PORT = len(sys.argv) == 2 and int(sys.argv[1]) or 8000
SUFFIXES = ['', '.html', '/index.html']
class ComplexHTTPRequestHandler(srvmod.SimpleHTTPRequestHandler):
def do_GET(self):
# we are trying to detect the file by having a fallback mechanism
found = False
for suffix in SUFFIXES:
if not hasattr(self,'original_path'):
self.original_path = self.path
self.path = self.original_path + suffix
path = self.translate_path(self.path)
if os.path.exists(path):
srvmod.SimpleHTTPRequestHandler.do_GET(self)
logging.info("Found: %s" % self.path)
found = True
break
logging.info("Tried to find file %s, but it doesn't exist. ", self.path)
if not found:
logging.warning("Unable to find file %s or variations.", self.path)
Handler = ComplexHTTPRequestHandler
socketserver.TCPServer.allow_reuse_address = True
try:
httpd = socketserver.TCPServer(("", PORT), Handler)
except OSError as e:
logging.error("Could not listen on port %s", PORT)
sys.exit(getattr(e, 'exitcode', 1))
logging.info("Serving at port %s", PORT)
try:
httpd.serve_forever()
except KeyboardInterrupt as e:
logging.info("Shutting down server")
httpd.socket.close()