Mer struktur och först försök med centralt definierad loggning.
This commit is contained in:
@@ -3,31 +3,36 @@ import subprocess
|
||||
import os
|
||||
import yaml
|
||||
import json
|
||||
from backend import run_flask
|
||||
# from backend import run_flask
|
||||
import socket
|
||||
import urllib.parse
|
||||
import logging
|
||||
import utils
|
||||
from utils import set_local_logger, run_flask
|
||||
|
||||
global log_level
|
||||
# global log_level
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
# logger = logging.getLogger(__name__)
|
||||
|
||||
def set_local_logger(log_instance):
|
||||
"""
|
||||
Configure logging based on the global variable log_level
|
||||
Logging is controlled by integer values, where DEBUG < INFO < WARNING < ERROR < CRITICAL.
|
||||
To turn off logging completely, set numeric_log_level to at least CRITICAL + 1.
|
||||
"""
|
||||
global log_level
|
||||
numeric_log_level = getattr(logging, log_level, None)
|
||||
if not isinstance(numeric_log_level, int):
|
||||
raise ValueError('Invalid log level: %s' % log_level)
|
||||
# def set_local_logger(log_instance):
|
||||
# """
|
||||
# Configure logging based on the global variable log_level
|
||||
# Logging is controlled by integer values, where DEBUG < INFO < WARNING < ERROR < CRITICAL.
|
||||
# To turn off logging completely, set numeric_log_level to at least CRITICAL + 1.
|
||||
# """
|
||||
# global log_level
|
||||
# numeric_log_level = getattr(logging, log_level, None)
|
||||
# if not isinstance(numeric_log_level, int):
|
||||
# raise ValueError('Invalid log level: %s' % log_level)
|
||||
|
||||
logging.basicConfig(level=numeric_log_level) # Set the root logger level to the configured level
|
||||
log_instance.info('Log level set to {}'.format(log_level)) # Example usage of the logger
|
||||
# logging.basicConfig(level=numeric_log_level) # Set the root logger level to the configured level
|
||||
# log_instance.info('Log level set to {}'.format(log_level)) # Example usage of the logger
|
||||
|
||||
def configure():
|
||||
|
||||
"""
|
||||
Reads YAML configruation file into dictionary, parse it and fill all referenceed
|
||||
environment variables with their values.
|
||||
"""
|
||||
##################
|
||||
# Read YAML config
|
||||
##################
|
||||
@@ -56,14 +61,14 @@ def configure():
|
||||
# Extract global logging level
|
||||
##################
|
||||
# The log_level variable will be used by the logger module to set the log level
|
||||
global log_level
|
||||
global log_level # REALLY NECESSARY TO DEFINE THIS GLOBAL AGAIN???
|
||||
log_level = 'INFO' # Default value if not specified in the config file
|
||||
if isinstance(updated_config.get('logging'), dict): # Look for 'logging' key in config file
|
||||
logging_config = updated_config['logging']
|
||||
if isinstance(logging_config.get('level'), str): # Set to value of the yaml file if specified
|
||||
log_level = logging_config['level']
|
||||
|
||||
set_local_logger(logger) # Set log level for logger based on log_level
|
||||
set_local_logger(utils.logger) # Set log level for logger based on log_level
|
||||
|
||||
return updated_config
|
||||
|
||||
@@ -78,16 +83,16 @@ def start_frontend(config):
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
try:
|
||||
s.bind((hostname, port))
|
||||
logger.info("No server is running on %s -— starting one.", parsed_url.netloc)
|
||||
utils.logger.info("No server is running on %s -— starting one.", parsed_url.netloc)
|
||||
# Start frontend (web server) as a separate process
|
||||
subprocess.Popen(["python", "-m", "http.server", str(port)])
|
||||
except socket.error as e:
|
||||
if e.errno == 48:
|
||||
logger.error("A server is already running on %s -— will use this.", parsed_url.netloc)
|
||||
utils.logger.error("A server is already running on %s -— will use this.", parsed_url.netloc)
|
||||
else:
|
||||
raise # Unexpected error, re-raise it so we can see the traceback
|
||||
except Exception as e:
|
||||
logger.error("Failed to start frontend: %s", str(e)) # Corresponds to print(f"Failed to start frontend: {e}")
|
||||
utils.logger.error("Failed to start frontend: %s", str(e)) # Corresponds to print(f"Failed to start frontend: {e}")
|
||||
|
||||
|
||||
|
||||
@@ -95,17 +100,17 @@ def start_backend(config):
|
||||
parsed_url = urllib.parse.urlparse(config['backend']['url'])
|
||||
# hostname = parsed_url.netloc.split(':')[0] # Split by ':' and take the first part, i.e., 'localhost', IP, or domain name
|
||||
port = parsed_url.port # This is the server port
|
||||
logger.debug('Backend parsed url set to {}'.format(parsed_url))
|
||||
logger.debug('Backend port set to {}'.format(port))
|
||||
utils.logger.debug('Backend parsed url set to {}'.format(parsed_url))
|
||||
utils.logger.debug('Backend port set to {}'.format(port))
|
||||
|
||||
try:
|
||||
run_flask(fport = port)
|
||||
except Exception as e:
|
||||
logger.error("Failed to start backend: %s", str(e)) # Corresponds to print(f"Failed to start backend: {e}")
|
||||
utils.logger.error("Failed to start backend: %s", str(e)) # Corresponds to print(f"Failed to start backend: {e}")
|
||||
|
||||
if __name__ == '__main__':
|
||||
conf = configure() # Read config from file and set up config dict
|
||||
logger.debug('conf dictionary set to {}'.format(json.dumps(conf, indent=4)))
|
||||
utils.logger.debug('conf dictionary set to {}'.format(json.dumps(conf, indent=4)))
|
||||
start_frontend(config=conf)
|
||||
start_backend(config=conf)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user