Skip to content

Commit 9ad22ea

Browse files
committed
fix(logger): restore files and content
1 parent 4077b7e commit 9ad22ea

File tree

3 files changed

+89
-42
lines changed

3 files changed

+89
-42
lines changed

src/ansys/tools/common/logger.py

Lines changed: 3 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
import logging
2828
from pathlib import Path
2929

30+
from ansys.tools.common.logger_formatter import DEFAULT_FORMATTER
31+
3032

3133
class SingletonType(type):
3234
"""Provides the singleton helper class for the logger."""
@@ -40,37 +42,6 @@ def __call__(cls, *args, **kwargs):
4042
return cls._instances[cls]
4143

4244

43-
class CustomFormatter(logging.Formatter):
44-
"""Custom formatter to truncate long columns."""
45-
46-
def set_column_width(self, width: int):
47-
"""Set the maximum column width for module and function names."""
48-
# at least 8
49-
if width < 8:
50-
raise ValueError("Column width must be at least 8 characters.")
51-
self._max_column_width = width
52-
53-
@property
54-
def max_column_width(self):
55-
"""Get the maximum column length."""
56-
if not hasattr(self, "_max_column_width"):
57-
self._max_column_width = 15
58-
return self._max_column_width
59-
60-
def format(self, record):
61-
"""Format the log record, truncating the module and function names if necessary."""
62-
if len(record.module) > self.max_column_width:
63-
record.module = record.module[: self.max_column_width - 3] + "..."
64-
if len(record.funcName) > self.max_column_width:
65-
record.funcName = record.funcName[: self.max_column_width - 3] + "..."
66-
67-
# Fill the module and function names with spaces to align them
68-
record.module = record.module.ljust(self.max_column_width)
69-
record.funcName = record.funcName.ljust(self.max_column_width)
70-
71-
return super().format(record)
72-
73-
7445
class Logger(object, metaclass=SingletonType):
7546
"""Provides the singleton logger.
7647
@@ -91,9 +62,7 @@ def __init__(self, level: int = logging.ERROR, logger_name: str = "Logger", colu
9162
"""Initialize the logger."""
9263
self._logger = logging.getLogger(logger_name)
9364
self._logger.setLevel(level)
94-
self._formatter = CustomFormatter(
95-
"%(asctime)s [%(levelname)-8s | %(module)s | %(funcName)s:%(lineno)-4d] > %(message)s"
96-
)
65+
self._formatter = DEFAULT_FORMATTER
9766
self._formatter.set_column_width(column_width)
9867

9968
def get_logger(self):
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Copyright (C) 2025 ANSYS, Inc. and/or its affiliates.
2+
# SPDX-License-Identifier: MIT
3+
#
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a copy
6+
# of this software and associated documentation files (the "Software"), to deal
7+
# in the Software without restriction, including without limitation the rights
8+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
# copies of the Software, and to permit persons to whom the Software is
10+
# furnished to do so, subject to the following conditions:
11+
#
12+
# The above copyright notice and this permission notice shall be included in all
13+
# copies or substantial portions of the Software.
14+
#
15+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
# SOFTWARE.
22+
23+
"""Default logger formatter module."""
24+
25+
import logging
26+
from typing import Final
27+
28+
29+
class PyAnsysBaseFormatter(logging.Formatter):
30+
"""Provides a custom formatter to truncate long columns."""
31+
32+
def set_column_width(self, width: int = 15):
33+
"""Set the maximum column width for module and function names."""
34+
# at least 8
35+
if width < 8:
36+
raise ValueError("Column width must be at least 8 characters.")
37+
self._max_column_width = width
38+
39+
@property
40+
def max_column_width(self):
41+
"""Get the maximum column length."""
42+
if not hasattr(self, "_max_column_width"):
43+
self._max_column_width = 15
44+
return self._max_column_width
45+
46+
47+
DEFAULT_FORMATTER: Final = PyAnsysBaseFormatter(
48+
"%(asctime)s [%(levelname)-8s | %(module)s | %(funcName)s:%(lineno)-4d] > %(message)s"
49+
)
50+
"""Default formatter for the logger."""
51+
52+
DEFAULT_HEADER = (
53+
"-" * (70 + DEFAULT_FORMATTER.max_column_width)
54+
+ "\n"
55+
+ f"Timestamp [Level | Module{' ' * (DEFAULT_FORMATTER.max_column_width - 6)} | Function{' ' * (DEFAULT_FORMATTER.max_column_width - 8)}:Line] > Message\n" # noqa: E501
56+
+ "-" * (70 + DEFAULT_FORMATTER.max_column_width)
57+
+ "\n"
58+
)
59+
"""Default header for the log file."""

tests/test_logger.py

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@
2525

2626
import pytest
2727

28-
from ansys.tools.common.logger import LOGGER, CustomFormatter, Logger
28+
from ansys.tools.common.logger import LOGGER, Logger
29+
from ansys.tools.common.logger_formatter import DEFAULT_FORMATTER, PyAnsysBaseFormatter
2930

3031

3132
def test_logger_singleton():
@@ -68,9 +69,9 @@ def test_logger_file_handler(tmp_path):
6869

6970

7071
def test_custom_formatter_truncation():
71-
"""Test truncation of module and function names in CustomFormatter."""
72-
formatter = CustomFormatter("%(module)s | %(funcName)s")
73-
assert formatter.max_column_width == 15 # Default width
72+
"""Test truncation of module and function names in PyAnsysBaseFormatter."""
73+
formatter = PyAnsysBaseFormatter("%(module).10s | %(funcName).10s")
74+
# assert formatter.max_column_width == 15 # Default width
7475
formatter.set_column_width(10)
7576
record = logging.LogRecord(
7677
name="test",
@@ -84,20 +85,38 @@ def test_custom_formatter_truncation():
8485
record.module = "very_long_module_name"
8586
record.funcName = "very_long_function_name"
8687
formatted_message = formatter.format(record)
87-
assert "very_lo..." in formatted_message
88-
assert "very_lo..." in formatted_message
88+
assert "very_long_ | very_long_" in formatted_message
8989

9090

9191
def test_custom_formatter_column_width():
92-
"""Test setting and getting column width in CustomFormatter."""
93-
formatter = CustomFormatter("%(module)s | %(funcName)s")
92+
"""Test setting and getting column width in PyAnsysBaseFormatter."""
93+
formatter = PyAnsysBaseFormatter("%(module)s | %(funcName)s")
9494
formatter.set_column_width(12)
9595
assert formatter.max_column_width == 12
9696

9797
with pytest.raises(ValueError):
9898
formatter.set_column_width(5)
9999

100100

101+
def test_default_formatter():
102+
"""Test the default formatter."""
103+
formatter = DEFAULT_FORMATTER
104+
record = logging.LogRecord(
105+
name="test",
106+
level=logging.INFO,
107+
pathname="test_path",
108+
lineno=1,
109+
msg="Test message",
110+
args=None,
111+
exc_info=None,
112+
)
113+
record.module = "very_long_module_name"
114+
record.funcName = "very_long_function_name"
115+
assert "[INFO | very_long_module_name | very_long_function_name:1 ] > Test message" in formatter.format(
116+
record
117+
)
118+
119+
101120
def test_logger_debug(capsys):
102121
"""Test the debug method."""
103122
LOGGER.enable_output()

0 commit comments

Comments
 (0)