Skip to content

Commit

Permalink
Added Configs class to handle all pyaedt global settings (#876)
Browse files Browse the repository at this point in the history
* Added Configs class to handle all pyaedt global settings

* Added Configs class to handle all pyaedt global settings

* Added Configs class to handle all pyaedt global settings

* Added Configs class to handle all pyaedt global settings

* fixed style

* Update pyaedt/generic/general_methods.py

Co-authored-by: Maxime Rey <[email protected]>

* log file folder

* log file folder

* log file folder

* log file folder

* log file folder

* removed environment variables for internal checks

Co-authored-by: maxcapodi78 <Shark78>
Co-authored-by: Maxime Rey <[email protected]>
  • Loading branch information
maxcapodi78 and MaxJPRey authored Feb 18, 2022
1 parent 6950eab commit b38a438
Show file tree
Hide file tree
Showing 12 changed files with 280 additions and 96 deletions.
1 change: 1 addition & 0 deletions _setup_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ def recursive_glob(startpath, filepattern):
("dlls", recursive_glob(os.path.join("pyaedt", "dlls"), "*")),
("misc", recursive_glob(os.path.join("pyaedt", "misc"), "*")),
("License", recursive_glob(".", "*.md")),
("xaml", ["pyaedt/generic/wpf_template.xaml"]),
("version", ["pyaedt/version.txt"]),
("setup-distutils", ["setup-distutils.py"]),
]
Expand Down
7 changes: 6 additions & 1 deletion _unittest/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,18 @@
import gc
import sys
from pyaedt.generic.general_methods import is_ironpython, inside_desktop
from pyaedt import settings

log_path = os.path.join(tempfile.gettempdir(), "test.log")
if os.path.exists(os.path.join(tempfile.gettempdir(), "test.log")):
os.remove(log_path)
settings.logger_file_path = log_path
settings.enable_error_handler = False
if is_ironpython:
import _unittest_ironpython.conf_unittest as pytest
else:
import pytest

os.environ["PYAEDT_ERROR_HANDLER"] = "False"

local_path = os.path.dirname(os.path.realpath(__file__))

Expand Down
18 changes: 9 additions & 9 deletions _unittest/test_00_EDB.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

test_project_name = "Galileo_edb"
bom_example = "bom_example.csv"
from _unittest.conftest import config, desktop_version, local_path, scratch_path, is_ironpython
from _unittest.conftest import config, desktop_version, local_path, scratch_path, is_ironpython, settings

try:
import pytest
Expand Down Expand Up @@ -338,12 +338,12 @@ def test_40_create_siwave_ac_analsyis(self):
assert self.edbapp.core_siwave.add_siwave_ac_analysis()

def test_41_create_siwave_dc_analsyis(self):
settings = self.edbapp.core_siwave.get_siwave_dc_setup_template()
settings.accuracy_level = 0
settings.use_dc_custom_settings = True
settings.name = "myDCIR_3"
settings.pos_term_to_ground = "I1"
assert self.edbapp.core_siwave.add_siwave_dc_analysis(settings)
settings_dc = self.edbapp.core_siwave.get_siwave_dc_setup_template()
settings_dc.accuracy_level = 0
settings_dc.use_dc_custom_settings = True
settings_dc.name = "myDCIR_3"
settings_dc.pos_term_to_ground = "I1"
assert self.edbapp.core_siwave.add_siwave_dc_analysis(settings_dc)

def test_42_get_nets_from_pin_list(self):
cmp_pinlist = self.edbapp.core_padstack.get_pinlist_from_component_and_net("U2A5", "GND")
Expand Down Expand Up @@ -504,7 +504,7 @@ def test_57_stackup_limits(self):
assert self.edbapp.core_stackup.stackup_limits()

def test_58_create_polygon(self):
os.environ["PYAEDT_ERROR_HANDLER"] = "True"
settings.enable_error_handler = True
points = [[-0.025, -0.02], [0.025, -0.02], [0.025, 0.02], [-0.025, 0.02], [-0.025, -0.02]]
plane = self.edbapp.core_primitives.Shape("polygon", points=points)
points = [
Expand All @@ -530,7 +530,7 @@ def test_58_create_polygon(self):
points = [[0.001, -0.001, "ccn", 0.0, -0.0012]]
plane = self.edbapp.core_primitives.Shape("polygon", points=points)
assert not self.edbapp.core_primitives.create_polygon(plane, "TOP")
os.environ["PYAEDT_ERROR_HANDLER"] = "False"
settings.enable_error_handler = False

def test_59_create_path(self):
points = [
Expand Down
4 changes: 3 additions & 1 deletion _unittest/test_14_AedtLogger.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

# Import required modules
from pyaedt.aedt_logger import AedtLogger
from pyaedt import Hfss
from pyaedt import Hfss, settings


class TestClass:
Expand Down Expand Up @@ -166,6 +166,7 @@ def test_02_output_file_with_app_filter(self):
@pytest.mark.skipif(is_ironpython, reason="stdout redirection does not work in IronPython.")
def test_03_stdout_with_app_filter(self):
capture = CaptureStdOut()
settings.logger_file_path = ""
with capture:
logger = AedtLogger(to_stdout=True)
logger.info("Info for Global")
Expand Down Expand Up @@ -244,6 +245,7 @@ def test_04_disable_output_file_handler(self):
design_logger.removeHandler(handler)

os.remove(path)
settings.logger_file_path = ""

@pytest.mark.skipif(is_ironpython, reason="stdout redirection does not work in IronPython.")
def test_05_disable_stdout(self):
Expand Down
6 changes: 3 additions & 3 deletions _unittest/test_20_HFSS.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
except ImportError:
import _unittest_ironpython.conf_unittest as pytest
# Setup paths for module imports
from _unittest.conftest import scratch_path, local_path
from _unittest.conftest import scratch_path, local_path, settings
import gc

# Import required modules
Expand Down Expand Up @@ -247,11 +247,11 @@ def test_06d_create_single_point_sweep(self):
assert self.aedtapp.create_single_point_sweep(
setupname="MySetup", unit="GHz", freq=[1.1e1, 1.2e1, 1.3e1], save_single_field=[True, False, True]
)
os.environ["PYAEDT_ERROR_HANDLER"] = "True"
settings.enable_error_handler = True
assert not self.aedtapp.create_single_point_sweep(
setupname="MySetup", unit="GHz", freq=[1, 2e2, 3.4], save_single_field=[True, False]
)
os.environ["PYAEDT_ERROR_HANDLER"] = "False"
settings.enable_error_handler = False

def test_06e_delete_setup(self):
setup_name = "SetupToDelete"
Expand Down
7 changes: 7 additions & 0 deletions _unittest_ironpython/run_unittests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@
import os
import sys
import unittest
import tempfile
from datetime import datetime
from pyaedt import settings

log_path = os.path.join(tempfile.gettempdir(), "test.log")
if os.path.exists(os.path.join(tempfile.gettempdir(), "test.log")):
os.remove(log_path)
settings.logger_file_path = log_path

from pyaedt.generic.general_methods import is_ironpython

Expand Down
9 changes: 4 additions & 5 deletions pyaedt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@

os.environ["ANSYSEM_FEATURE_SF6694_NON_GRAPHICAL_COMMAND_EXECUTION_ENABLE"] = "1"
os.environ["ANSYSEM_FEATURE_SF159726_SCRIPTOBJECT_ENABLE"] = "1"


try:
__version__ = ""
if os.path.exists(os.path.join(os.path.dirname(__file__), "version.txt")):
with open(os.path.join(os.path.dirname(__file__), "version.txt"), "r") as f:
__version__ = f.read().strip()
except:
__version__ = ""

from pyaedt.generic.general_methods import settings
from pyaedt.generic import constants
from pyaedt.generic.general_methods import aedt_exception_handler, generate_unique_name, _retry_ntimes
from pyaedt.generic.general_methods import is_ironpython, _pythonver, inside_desktop, convert_remote_object
from pyaedt.aedt_logger import AedtLogger


try:
from pyaedt.generic.design_types import Hfss3dLayout
except:
Expand Down
28 changes: 12 additions & 16 deletions pyaedt/aedt_logger.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
import logging
import sys

from pyaedt import log_handler
from pyaedt import log_handler, settings
from pyaedt.application.MessageManager import AEDTMessageManager

ENABLE_LOGGER = True
# if LOGGER_FILE is defined, it will be taken as output log file
LOGGER_FILE = None

FORMATTER = logging.Formatter(
"%(asctime)s:%(destination)s:%(extra)s%(levelname)-8s:%(message)s", datefmt="%Y/%m/%d %H.%M.%S"
)


class AppFilter(logging.Filter):
"""This filter will be used to specify the destination of the log
Expand Down Expand Up @@ -69,13 +61,16 @@ def __init__(self, level=logging.DEBUG, filename=None, to_stdout=False):
main = sys.modules["__main__"]

self.level = level
self.filename = filename
self.filename = filename or settings.logger_file_path
settings.logger_file_path = self.filename

self._messenger = AEDTMessageManager()
self._global = logging.getLogger("Global")
self._file_handler = None
self._std_out_handler = None
self.formatter = logging.Formatter(settings.logger_formatter, datefmt=settings.logger_datefmt)

if not ENABLE_LOGGER:
if not settings.enable_logger:
self._global.addHandler(logging.NullHandler())
return

Expand All @@ -90,16 +85,17 @@ def __init__(self, level=logging.DEBUG, filename=None, to_stdout=False):
self._global.setLevel(level)
self._global.addFilter(AppFilter())

if LOGGER_FILE or filename:
self._file_handler = logging.FileHandler(LOGGER_FILE or filename)
if self.filename:
self._file_handler = logging.FileHandler(self.filename)
self._file_handler.setLevel(level)
self._file_handler.setFormatter(FORMATTER)
self._file_handler.setFormatter(self.formatter)
self._global.addHandler(self._file_handler)

if to_stdout:
self._std_out_handler = logging.StreamHandler()
self._std_out_handler.setLevel(level)
self._std_out_handler.setFormatter(FORMATTER)

self._std_out_handler.setFormatter(self.formatter)
self._global.addHandler(self._std_out_handler)

@property
Expand Down Expand Up @@ -172,7 +168,7 @@ def enable_log_on_file(self):
self._messenger._log_on_file = True
self._file_handler = logging.FileHandler(self.filename)
self._file_handler.setLevel(self.level)
self._file_handler.setFormatter(FORMATTER)
self._file_handler.setFormatter(self.formatter)
self._global.addHandler(self._file_handler)

def get_messages(self):
Expand Down
63 changes: 41 additions & 22 deletions pyaedt/application/MessageManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@
"""

import logging
import os
import sys

from pyaedt.generic.general_methods import settings

message_levels = {"Global": 0, "Project": 1, "Design": 2}

Expand Down Expand Up @@ -105,30 +104,50 @@ class AEDTMessageManager(object):

def __init__(self, app=None):
self._app = app
if not app:
if "oDesktop" in dir(sys.modules["__main__"]):
self.MainModule = sys.modules["__main__"]
self._desktop = self.MainModule.oDesktop
self._log_on_desktop = os.getenv("PYAEDT_DESKTOP_LOGS", "True").lower() in (
"true",
"1",
"t",
"yes",
"y",
)
else:
self._log_on_desktop = False
self._desktop = None

@property
def _desktop(self):
if self._app:
return self._app._desktop # pragma: no cover
if "oDesktop" in dir(sys.modules["__main__"]):
MainModule = sys.modules["__main__"]
return MainModule.oDesktop
return None # pragma: no cover

@property
def _log_on_desktop(self):
if self._desktop and settings.enable_desktop_logs:
return True
else:
self._desktop = self._app._desktop
self._log_on_desktop = os.getenv("PYAEDT_DESKTOP_LOGS", "True").lower() in ("true", "1", "t")
self._log_on_file = os.getenv("PYAEDT_FILE_LOGS", "True").lower() in ("true", "1", "t")
self._log_on_screen = os.getenv("PYAEDT_SCREEN_LOGS", "True").lower() in ("true", "1", "t")
return False

@_log_on_desktop.setter
def _log_on_desktop(self, val):
settings.enable_desktop_logs = val

@property
def _log_on_file(self):
return settings.enable_file_logs

@_log_on_file.setter
def _log_on_file(self, val):
settings.enable_file_logs = val

@property
def _log_on_screen(self):
return settings.enable_screen_logs

@_log_on_screen.setter
def _log_on_screen(self, val):
settings.enable_screen_logs = val

@property
def logger(self):
"""Aedt Logger object."""
if self._log_on_file:
self.logger = logging.getLogger(__name__)
return logging.getLogger(__name__)
else:
self.logger = None
return None # pragma: no cover

@property
def messages(self):
Expand Down
15 changes: 9 additions & 6 deletions pyaedt/desktop.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import subprocess

from pyaedt.misc import list_installed_ansysem
from pyaedt import aedt_exception_handler
from pyaedt import aedt_exception_handler, settings
from pyaedt.generic.general_methods import is_ironpython, _pythonver, inside_desktop

from pyaedt import aedt_logger, __version__
Expand Down Expand Up @@ -435,7 +435,7 @@ def _init_ironpython(self, non_graphical, new_aedt_session, version):
else:
oAnsoftApp = StandalonePyScriptWrapper.CreateObject(version)
if non_graphical:
os.environ["PYAEDT_DESKTOP_LOGS"] = "False"
settings.enable_desktop_logs = False
self._main.oDesktop = oAnsoftApp.GetAppDesktop()
self._main.isoutsideDesktop = True
sys.path.append(os.path.join(base_path, "common", "commonfiles", "IronPython", "DLLs"))
Expand Down Expand Up @@ -498,7 +498,7 @@ def _init_cpython(self, non_graphical, new_aedt_session, version, student_versio
else:
StandalonePyScriptWrapper.CreateObject(version)
if non_graphical:
os.environ["PYAEDT_DESKTOP_LOGS"] = "False"
settings.enable_desktop_logs = False
processID2 = []
if IsWindows:
processID2 = self._get_tasks_list_windows(student_version)
Expand Down Expand Up @@ -534,9 +534,12 @@ def _set_logger_file(self):
project_dir = self._main.oDesktop.GetProjectDirectory()
else:
project_dir = tempfile.gettempdir()
self.logfile = os.path.join(
project_dir, "pyaedt{}.log".format(datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
)
if settings.logger_file_path:
self.logfile = settings.logger_file_path
else:
self.logfile = os.path.join(
project_dir, "pyaedt{}.log".format(datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
)

return True

Expand Down
12 changes: 7 additions & 5 deletions pyaedt/edb.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
except ImportError:
if os.name != "posix":
warnings.warn("Pythonnet is needed to run pyaedt")

from pyaedt import settings
from pyaedt.edb_core import Components, EdbNets, EdbPadstacks, EdbLayout, EdbHfss, EdbSiwave, EdbStackup
from pyaedt.edb_core.EDB_Data import EdbBuilder
from pyaedt.generic.general_methods import (
Expand Down Expand Up @@ -120,10 +120,12 @@ def __init__(
project_dir = tempfile.gettempdir()
else:
project_dir = os.path.dirname(edbpath)

logfile = os.path.join(
project_dir, "pyaedt{}.log".format(datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
)
if settings.logger_file_path:
logfile = settings.logger_file_path
else:
logfile = os.path.join(
project_dir, "pyaedt{}.log".format(datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
)
self._logger = AedtLogger(filename=logfile, level=logging.DEBUG)
self._logger.info("Logger Started on %s", logfile)
self._main.aedt_logger = self._logger
Expand Down
Loading

0 comments on commit b38a438

Please sign in to comment.