Introducerade loggning för att ersätta vanliga utskrifter
This commit is contained in:
@@ -6,29 +6,66 @@ import json
|
|||||||
from backend import run_flask
|
from backend import run_flask
|
||||||
import socket
|
import socket
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
|
import logging
|
||||||
|
|
||||||
|
global log_level
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
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():
|
def configure():
|
||||||
|
|
||||||
|
##################
|
||||||
|
# Read YAML config
|
||||||
|
##################
|
||||||
# Load configuration file that defines parameters for services
|
# Load configuration file that defines parameters for services
|
||||||
with open('./smartassist/config/smartassist.yaml') as f:
|
with open('./smartassist/config/smartassist.yaml') as f:
|
||||||
config = yaml.safe_load(f)
|
config = yaml.safe_load(f)
|
||||||
|
|
||||||
# 1. Find the API Key environment variable name
|
def resolve_env_var(value):
|
||||||
api_key_env = None
|
|
||||||
for key, value in config['ollama'].items():
|
|
||||||
if isinstance(value, str) and value.startswith("${") and value.endswith("}"):
|
if isinstance(value, str) and value.startswith("${") and value.endswith("}"):
|
||||||
api_key_env = value[2:-1] # Extract name between ${}
|
env_var_name = value[2:-1] # Extract name between ${}
|
||||||
|
return os.getenv(env_var_name, None)
|
||||||
|
return value
|
||||||
|
|
||||||
# 2. Obtain API Key if an environment variable was found
|
def update_dict_with_env_vars(d):
|
||||||
api_key = None
|
for key in d:
|
||||||
if api_key_env:
|
if isinstance(d[key], dict):
|
||||||
api_key = os.getenv(api_key_env)
|
update_dict_with_env_vars(d[key]) # Recursively check nested dictionaries
|
||||||
else:
|
elif isinstance(d[key], str):
|
||||||
print("Warning: Environment variable reference not found in YAML configuration.")
|
d[key] = resolve_env_var(d[key])
|
||||||
|
return d
|
||||||
|
|
||||||
# Update the config dictionary with the actual API key (or None if not found)
|
# Update the config dictionary with resolved environment variables
|
||||||
config['ollama']['api_key'] = api_key
|
updated_config = update_dict_with_env_vars(config)
|
||||||
return config
|
|
||||||
|
##################
|
||||||
|
# Extract global logging level
|
||||||
|
##################
|
||||||
|
# The log_level variable will be used by the logger module to set the log level
|
||||||
|
global log_level
|
||||||
|
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
|
||||||
|
|
||||||
|
return updated_config
|
||||||
|
|
||||||
|
|
||||||
def start_frontend(config):
|
def start_frontend(config):
|
||||||
@@ -41,32 +78,34 @@ def start_frontend(config):
|
|||||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||||
try:
|
try:
|
||||||
s.bind((hostname, port))
|
s.bind((hostname, port))
|
||||||
print(f"No server is running on {parsed_url.netloc} —- starting up one.")
|
logger.info("No server is running on %s -— starting one.", parsed_url.netloc)
|
||||||
# Start frontend (web server) as a separate process
|
# Start frontend (web server) as a separate process
|
||||||
subprocess.Popen(["python", "-m", "http.server", str(port)])
|
subprocess.Popen(["python", "-m", "http.server", str(port)])
|
||||||
except socket.error as e:
|
except socket.error as e:
|
||||||
if e.errno == 48:
|
if e.errno == 48:
|
||||||
print(f"A server is already running on {parsed_url.netloc} -— will use this.")
|
logger.error("A server is already running on %s -— will use this.", parsed_url.netloc)
|
||||||
else:
|
else:
|
||||||
raise # Unexpected error, re-raise it so we can see the traceback
|
raise # Unexpected error, re-raise it so we can see the traceback
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Failed to start frontend: {e}")
|
logger.error("Failed to start frontend: %s", str(e)) # Corresponds to print(f"Failed to start frontend: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def start_backend(config):
|
def start_backend(config):
|
||||||
parsed_url = urllib.parse.urlparse(config['backend']['url'])
|
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
|
# 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
|
port = parsed_url.port # This is the server port
|
||||||
# print(f"{port}")
|
logger.debug('Backend parsed url set to {}'.format(parsed_url))
|
||||||
|
logger.debug('Backend port set to {}'.format(port))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
run_flask(fport = port)
|
run_flask(fport = port)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Failed to start backend: {e}")
|
logger.error("Failed to start backend: %s", str(e)) # Corresponds to print(f"Failed to start backend: {e}")
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
conf = configure() # Read config from file and set up config dict
|
conf = configure() # Read config from file and set up config dict
|
||||||
print(json.dumps(conf, indent=4))
|
logger.debug('conf dictionary set to {}'.format(json.dumps(conf, indent=4)))
|
||||||
start_frontend(config=conf)
|
start_frontend(config=conf)
|
||||||
start_backend(config=conf)
|
start_backend(config=conf)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user