Skip to content

Commit 99fea55

Browse files
authored
explicitly set supported file formats (#1406)
1 parent 451ce48 commit 99fea55

File tree

3 files changed

+32
-17
lines changed

3 files changed

+32
-17
lines changed

can/io/logger.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,13 @@
77
from abc import ABC, abstractmethod
88
from datetime import datetime
99
import gzip
10-
from typing import Any, Optional, Callable, Type, Tuple, cast, Dict
10+
from typing import Any, Optional, Callable, Type, Tuple, cast, Dict, Set
1111

1212
from types import TracebackType
1313

1414
from typing_extensions import Literal
1515
from pkg_resources import iter_entry_points
1616

17-
import can.io
1817
from ..message import Message
1918
from ..listener import Listener
2019
from .generic import BaseIOHandler, FileIOMessageWriter, MessageWriter
@@ -131,9 +130,10 @@ class BaseRotatingLogger(Listener, BaseIOHandler, ABC):
131130
:class:`~logging.handlers.BaseRotatingHandler`.
132131
133132
Subclasses must set the `_writer` attribute upon initialization.
134-
135133
"""
136134

135+
_supported_formats: Set[str] = set()
136+
137137
#: If this attribute is set to a callable, the :meth:`~BaseRotatingLogger.rotation_filename`
138138
#: method delegates to this callable. The parameters passed to the callable are
139139
#: those passed to :meth:`~BaseRotatingLogger.rotation_filename`.
@@ -224,17 +224,21 @@ def _get_new_writer(self, filename: StringPathLike) -> FileIOMessageWriter:
224224
:return:
225225
An instance of a writer class.
226226
"""
227-
228-
logger = Logger(filename, *self.writer_args, **self.writer_kwargs)
229-
if isinstance(logger, FileIOMessageWriter):
230-
return logger
231-
elif isinstance(logger, Printer) and logger.file is not None:
232-
return cast(FileIOMessageWriter, logger)
233-
else:
234-
raise Exception(
235-
f"The log format \"{''.join(pathlib.Path(filename).suffixes[-2:])}"
236-
f'" is not supported by {self.__class__.__name__}'
237-
)
227+
suffix = "".join(pathlib.Path(filename).suffixes[-2:]).lower()
228+
229+
if suffix in self._supported_formats:
230+
logger = Logger(filename, *self.writer_args, **self.writer_kwargs)
231+
if isinstance(logger, FileIOMessageWriter):
232+
return logger
233+
elif isinstance(logger, Printer) and logger.file is not None:
234+
return cast(FileIOMessageWriter, logger)
235+
236+
raise Exception(
237+
f'The log format "{suffix}" '
238+
f"is not supported by {self.__class__.__name__}. "
239+
f"{self.__class__.__name__} supports the following formats: "
240+
f"{', '.join(self._supported_formats)}"
241+
)
238242

239243
def stop(self) -> None:
240244
"""Stop handling new messages.
@@ -306,6 +310,8 @@ class SizedRotatingLogger(BaseRotatingLogger):
306310
:meth:`~can.Listener.stop` is called.
307311
"""
308312

313+
_supported_formats = {".asc", ".blf", ".csv", ".log", ".txt"}
314+
309315
def __init__(
310316
self,
311317
base_filename: StringPathLike,

can/io/printer.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import logging
66

7-
from typing import Optional, TextIO, Union, Any
7+
from typing import Optional, TextIO, Union, Any, cast
88

99
from ..message import Message
1010
from .generic import MessageWriter
@@ -40,11 +40,18 @@ def __init__(
4040
:param append: If set to `True` messages, are appended to the file,
4141
else the file is truncated
4242
"""
43+
self.write_to_file = file is not None
4344
mode = "a" if append else "w"
4445
super().__init__(file, mode=mode)
4546

4647
def on_message_received(self, msg: Message) -> None:
47-
if self.file is not None:
48-
self.file.write(str(msg) + "\n")
48+
if self.write_to_file:
49+
cast(TextIO, self.file).write(str(msg) + "\n")
4950
else:
5051
print(msg)
52+
53+
def file_size(self) -> int:
54+
"""Return an estimate of the current file size in bytes."""
55+
if self.file is not None:
56+
return self.file.tell()
57+
return 0

test/test_rotating_loggers.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ def _get_instance(path, *args, **kwargs) -> can.io.BaseRotatingLogger:
1818
class SubClass(can.io.BaseRotatingLogger):
1919
"""Subclass that implements abstract methods for testing."""
2020

21+
_supported_formats = {".asc", ".blf", ".csv", ".log", ".txt"}
22+
2123
def __init__(self, *args, **kwargs) -> None:
2224
super().__init__(*args, **kwargs)
2325
self._writer = can.Printer(file=path / "__unused.txt")

0 commit comments

Comments
 (0)