Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/changelog.d/37.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Provide logger formatter separately
37 changes: 3 additions & 34 deletions src/ansys/tools/common/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import logging
from pathlib import Path

from ansys.tools.common.logger_formatter import DEFAULT_FORMATTER


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


class CustomFormatter(logging.Formatter):
"""Custom formatter to truncate long columns."""

def set_column_width(self, width: int):
"""Set the maximum column width for module and function names."""
# at least 8
if width < 8:
raise ValueError("Column width must be at least 8 characters.")
self._max_column_width = width

@property
def max_column_width(self):
"""Get the maximum column length."""
if not hasattr(self, "_max_column_width"):
self._max_column_width = 15
return self._max_column_width

def format(self, record):
"""Format the log record, truncating the module and function names if necessary."""
if len(record.module) > self.max_column_width:
record.module = record.module[: self.max_column_width - 3] + "..."
if len(record.funcName) > self.max_column_width:
record.funcName = record.funcName[: self.max_column_width - 3] + "..."

# Fill the module and function names with spaces to align them
record.module = record.module.ljust(self.max_column_width)
record.funcName = record.funcName.ljust(self.max_column_width)

return super().format(record)


class Logger(object, metaclass=SingletonType):
"""Provides the singleton logger.

Expand All @@ -91,9 +62,7 @@ def __init__(self, level: int = logging.ERROR, logger_name: str = "Logger", colu
"""Initialize the logger."""
self._logger = logging.getLogger(logger_name)
self._logger.setLevel(level)
self._formatter = CustomFormatter(
"%(asctime)s [%(levelname)-8s | %(module)s | %(funcName)s:%(lineno)-4d] > %(message)s"
)
self._formatter = DEFAULT_FORMATTER
self._formatter.set_column_width(column_width)

def get_logger(self):
Expand Down
72 changes: 72 additions & 0 deletions src/ansys/tools/common/logger_formatter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Copyright (C) 2025 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""Default logger formatter module."""

import logging


class PyAnsysBaseFormatter(logging.Formatter):
"""Custom formatter to truncate long columns."""

def set_column_width(self, width: int):
"""Set the maximum column width for module and function names."""
# at least 8
if width < 8:
raise ValueError("Column width must be at least 8 characters.")
self._max_column_width = width

@property
def max_column_width(self):
"""Get the maximum column length."""
if not hasattr(self, "_max_column_width"):
self._max_column_width = 15
return self._max_column_width

def format(self, record):
"""Format the log record, truncating the module and function names if necessary."""
if len(record.module) > self.max_column_width:
record.module = record.module[: self.max_column_width - 3] + "..."
if len(record.funcName) > self.max_column_width:
record.funcName = record.funcName[: self.max_column_width - 3] + "..."

# Fill the module and function names with spaces to align them
record.module = record.module.ljust(self.max_column_width)
record.funcName = record.funcName.ljust(self.max_column_width)

return super().format(record)


DEFAULT_FORMATTER = PyAnsysBaseFormatter(
"%(asctime)s [%(levelname)-8s | %(module)s | %(funcName)s:%(lineno)-4d] > %(message)s"
)
DEFAULT_FORMATTER.set_column_width(15)
"""Default formatter for the logger."""

DEFAULT_HEADER = (
"-" * (70 + DEFAULT_FORMATTER.max_column_width)
+ "\n"
+ f"Timestamp [Level | Module{' ' * (DEFAULT_FORMATTER.max_column_width - 6)} | Function{' ' * (DEFAULT_FORMATTER.max_column_width - 8)}:Line] > Message\n" # noqa: E501
+ "-" * (70 + DEFAULT_FORMATTER.max_column_width)
+ "\n"
)
"""Default header for the log file."""
11 changes: 6 additions & 5 deletions tests/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@

import pytest

from ansys.tools.common.logger import LOGGER, CustomFormatter, Logger
from ansys.tools.common.logger import LOGGER, Logger
from ansys.tools.common.logger_formatter import PyAnsysBaseFormatter


def test_logger_singleton():
Expand Down Expand Up @@ -68,8 +69,8 @@ def test_logger_file_handler(tmp_path):


def test_custom_formatter_truncation():
"""Test truncation of module and function names in CustomFormatter."""
formatter = CustomFormatter("%(module)s | %(funcName)s")
"""Test truncation of module and function names in PyAnsysBaseFormatter."""
formatter = PyAnsysBaseFormatter("%(module)s | %(funcName)s")
assert formatter.max_column_width == 15 # Default width
formatter.set_column_width(10)
record = logging.LogRecord(
Expand All @@ -89,8 +90,8 @@ def test_custom_formatter_truncation():


def test_custom_formatter_column_width():
"""Test setting and getting column width in CustomFormatter."""
formatter = CustomFormatter("%(module)s | %(funcName)s")
"""Test setting and getting column width in PyAnsysBaseFormatter."""
formatter = PyAnsysBaseFormatter("%(module)s | %(funcName)s")
formatter.set_column_width(12)
assert formatter.max_column_width == 12

Expand Down
Loading