python http server logging setup

356 views Asked by At

I have a simple python http server as below. This will host an index.html page which is in the current directory. The server will be running in the background as a thread.

import os
import time
import threading
import logging

from http.server import HTTPServer, CGIHTTPRequestHandler

def html_server(port):
    """This function will host a html file containing the bot"""
    os.chdir('.')
    httpd = HTTPServer(('', port), CGIHTTPRequestHandler)
    httpd.serve_forever()
    
def start_html_server(port):
    httpserv = threading.Thread(target=html_server, args=(port,), name='daemon_server', daemon=True)
    try:
        httpserv.start() 
    except:
        logging.critical("unable to start HTTP server")
    else:
        logging.info('Strated HTTP server ') 

FORMAT = '%(asctime)s: %(levelname)s: %(message)s'
log_dir = os.getenv('LOG_DIR') # this value will be taken from env variable
logging.basicConfig(filename=f'{log_dir}/monitor.log', level=logging.INFO, format=FORMAT)

start_html_server(8000) 

while True:
    time.sleep(1) 

Right now its logging the requests to the std out of the script. I'm trying to log the output to a file called monitor.log. I want to use the logging.info inside the http.server.

Thanks in advance.

0

There are 0 answers