Skip to content

Commit 7a90f08

Browse files
authored
Merge pull request #237 from Radio-Spectrum/hotfix/logging_facility
fix(simulation): Fixed simulator log facility setup
2 parents c174348 + 1055911 commit 7a90f08

File tree

3 files changed

+50
-72
lines changed

3 files changed

+50
-72
lines changed

sharc/main_cli.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77

88
import os
99
import sys
10-
import getopt
10+
import argparse
1111

12-
from sharc.support.sharc_logger import Logging, SimulationLogger
12+
from sharc.support.sharc_logger import setup_logging, SimulationLogger
1313
from sharc.controller import Controller
1414
from sharc.gui.view_cli import ViewCli
1515
from sharc.model import Model
@@ -34,28 +34,25 @@ def main(argv):
3434

3535
param_file = ""
3636

37-
try:
38-
opts, _ = getopt.getopt(argv, "hp:")
39-
except getopt.GetoptError:
40-
print("usage: main_cli.py -p <param_file>")
41-
sys.exit(2)
42-
43-
if not opts:
44-
param_file = os.path.join(os.getcwd(), "input", "parameters.yaml")
45-
else:
46-
for opt, arg in opts:
47-
if opt == "-h":
48-
print("usage: main_cli.py -p <param_file>")
49-
sys.exit()
50-
elif opt == "-p":
51-
param_file = os.path.join(os.getcwd(), arg)
37+
parser = argparse.ArgumentParser(description="SHARC - Radio Sharing and Compatiblity Monte Carlo Simulator")
38+
parser.add_argument("-p", "--param-file", default=os.path.join(os.getcwd(), "input", "parameters.yaml"),
39+
help="Path to parameter file (default: input/parameters.yaml)")
40+
parser.add_argument("-l", "--log-file", default=None,
41+
help="Path to output log file (optional)")
42+
43+
args = parser.parse_args(argv)
44+
param_file = os.path.join(os.getcwd(), args.param_file) if not os.path.isabs(args.param_file) else args.param_file
45+
46+
log_file = None
47+
if args.log_file is not None:
48+
log_file = os.path.join(os.getcwd(), args.log_file) if not os.path.isabs(args.log_file) else args.log_file
49+
50+
setup_logging(log_file=log_file)
5251

5352
# Logger setup start
5453
sim_logger = SimulationLogger(param_file)
5554
sim_logger.start()
5655

57-
Logging.setup_logging()
58-
5956
model = Model()
6057
view_cli = ViewCli()
6158
controller = Controller()

sharc/support/logging.yaml

Lines changed: 0 additions & 27 deletions
This file was deleted.

sharc/support/sharc_logger.py

Lines changed: 34 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,41 @@
22
import os
33
import sys
44
import yaml
5-
import logging
5+
import logging.config
66
import subprocess
77
from pathlib import Path
88
from datetime import datetime
9-
from typing import Optional
10-
11-
12-
class Logging:
13-
"""Logging utility class for configuring application logging."""
14-
15-
@staticmethod
16-
def setup_logging(
17-
default_path="support/logging.yaml",
18-
default_level=logging.INFO,
19-
env_key="LOG_CFG",
20-
):
21-
"""Set up logging configuration for the application."""
22-
path = default_path
23-
value = os.getenv(env_key, None)
24-
if value:
25-
path = value
26-
if os.path.exists(path):
27-
with open(path, "rt") as f:
28-
config = yaml.safe_load(f.read())
29-
logging.config.dictConfig(config)
30-
else:
31-
logging.basicConfig(level=default_level)
9+
from typing import Optional, List
10+
11+
level_mapping = logging.getLevelNamesMapping()
12+
13+
14+
def setup_logging(log_file=None, default_level="INFO"):
15+
"""Setup logging configuration for the root logger.
16+
17+
Run this function in the beginning of the simulation to setup the root logger.
18+
"""
19+
20+
try:
21+
level = level_mapping[default_level]
22+
except KeyError:
23+
raise ValueError("Invalid log level option {}".format(default_level))
24+
25+
root_logger = logging.getLogger()
26+
root_logger.setLevel(level)
27+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
28+
root_logger.handlers = []
29+
30+
# Stream to stdout
31+
handler = logging.StreamHandler(sys.stdout)
32+
handler.setFormatter(formatter)
33+
root_logger.addHandler(handler)
34+
35+
# Stream to file if specified
36+
if log_file is not None:
37+
file_handler = logging.FileHandler(log_file)
38+
file_handler.setFormatter(formatter)
39+
root_logger.addHandler(file_handler)
3240

3341

3442
class SimulationLogger:
@@ -102,7 +110,7 @@ def _find_root_dir(self, folder_name: str) -> Optional[Path]:
102110
return parent
103111
return None
104112

105-
def _run_git_cmd(self, args: list[str]) -> Optional[str]:
113+
def _run_git_cmd(self, args: List[str]) -> Optional[str]:
106114
try:
107115
return (
108116
subprocess.check_output(["git"] + args, stderr=subprocess.DEVNULL)
@@ -132,7 +140,7 @@ def _get_invocation_command(self) -> str:
132140
def _get_python_version(self) -> str:
133141
return sys.version.replace("\n", " ")
134142

135-
def _get_installed_packages(self) -> list[str]:
143+
def _get_installed_packages(self) -> List[str]:
136144
try:
137145
output = subprocess.check_output(
138146
[sys.executable, "-m", "pip", "freeze"], stderr=subprocess.DEVNULL

0 commit comments

Comments
 (0)