2019-02-19 13:09:32 -05:00
|
|
|
#!/usr/bin/python3
|
|
|
|
#
|
|
|
|
# SPDX-License-Identifier: Apache-2.0
|
|
|
|
#
|
|
|
|
|
2023-05-04 17:21:54 -03:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
2019-02-19 13:09:32 -05:00
|
|
|
|
|
|
|
import os
|
|
|
|
import datetime
|
|
|
|
import logging
|
|
|
|
from consts.env import LOGPATH
|
|
|
|
|
2023-05-04 17:21:54 -03:00
|
|
|
LOG_DIR = ""
|
2019-02-19 13:09:32 -05:00
|
|
|
LOG = logging.getLogger()
|
|
|
|
|
2023-05-04 17:21:54 -03:00
|
|
|
|
2019-02-19 13:09:32 -05:00
|
|
|
def init_logging(lab_name, log_path=None):
|
2023-05-04 17:21:54 -03:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
|
|
|
|
2023-06-06 12:22:06 -03:00
|
|
|
global LOG, LOG_DIR # pylint: disable=global-statement, global-variable-not-assigned
|
2019-02-19 13:09:32 -05:00
|
|
|
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()
|
2023-06-06 12:22:06 -03:00
|
|
|
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}"
|
2023-05-04 17:21:54 -03:00
|
|
|
if not os.path.exists(LOG_DIR):
|
|
|
|
os.makedirs(LOG_DIR)
|
2019-02-19 13:09:32 -05:00
|
|
|
|
|
|
|
LOG.setLevel(logging.INFO)
|
|
|
|
formatter = logging.Formatter("%(asctime)s: %(message)s")
|
2023-05-04 17:21:54 -03:00
|
|
|
log_file = f"{LOG_DIR}/install.log"
|
2019-02-19 13:09:32 -05:00
|
|
|
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")
|
2023-07-25 13:56:56 -03:00
|
|
|
except FileNotFoundError:
|
2019-02-19 13:09:32 -05:00
|
|
|
pass
|
2023-07-25 13:56:56 -03:00
|
|
|
|
2023-05-04 17:21:54 -03:00
|
|
|
os.symlink(LOG_DIR, lab_log_path + "/latest")
|
|
|
|
|
2019-02-19 13:09:32 -05:00
|
|
|
|
|
|
|
def get_log_dir():
|
2023-07-25 13:56:56 -03:00
|
|
|
"""This method returns the log directory"""
|
2023-05-04 17:21:54 -03:00
|
|
|
|
|
|
|
return LOG_DIR
|