#!/usr/bin/python3 # # SPDX-License-Identifier: Apache-2.0 # """ This module provides functionality to initialize logging for a lab, create a sub-directory for the current run, set the logging level, and create a symbolic link to the latest logs for the lab. """ import os import datetime import logging from consts.env import LOGPATH LOG_DIR = "" LOG = logging.getLogger() def init_logging(lab_name, log_path=None): """ This method initializes the logging for a lab. It creates a sub-directory for the current run and sets the logging level to INFO. It also creates a symbolic link to the latest logs for the lab. The method takes in the lab name and an optional log path parameter. If no log path is specified, it uses the default path provided by the LOGPATH constant in the env module. """ global LOG, LOG_DIR # pylint: disable=global-statement, global-variable-not-assigned if not log_path: log_path = LOGPATH lab_log_path = log_path + "/" + lab_name # Setup log sub-directory for current run current_time = datetime.datetime.now() LOG_DIR = f"{lab_log_path}/{current_time.year}_{current_time.month}_" \ f"{current_time.day}_{current_time.hour}_{current_time.minute}_{current_time.second}" if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) LOG.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s: %(message)s") log_file = f"{LOG_DIR}/install.log" handler = logging.FileHandler(log_file) handler.setFormatter(formatter) handler.setLevel(logging.INFO) LOG.addHandler(handler) handler = logging.StreamHandler() handler.setFormatter(formatter) LOG.addHandler(handler) # Create symbolic link to latest logs of this lab try: os.unlink(lab_log_path + "/latest") except FileNotFoundError: pass os.symlink(LOG_DIR, lab_log_path + "/latest") def get_log_dir(): """This method returns the log directory""" return LOG_DIR