Skip to content

Commit 5e5ca2b

Browse files
committed
Add compress method to logger
1 parent 56c5791 commit 5e5ca2b

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

can/io/logger.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@
66
import pathlib
77
from abc import ABC, abstractmethod
88
from datetime import datetime
9+
import gzip
910
from typing import (
1011
Any,
1112
Optional,
1213
Callable,
1314
cast,
15+
IO,
1416
Type,
17+
Tuple,
1518
)
1619
from types import TracebackType
1720

@@ -21,7 +24,7 @@
2124
from ..message import Message
2225
from ..listener import Listener
2326
from .generic import BaseIOHandler, FileIOMessageWriter
24-
from .asc import ASCWriter, GzipASCWriter
27+
from .asc import ASCWriter
2528
from .blf import BLFWriter
2629
from .canutils import CanutilsLogWriter
2730
from .csv import CSVWriter
@@ -36,13 +39,14 @@ class Logger(BaseIOHandler, Listener): # pylint: disable=abstract-method
3639
3740
The format is determined from the file format which can be one of:
3841
* .asc: :class:`can.ASCWriter`
39-
* .asc.gz: :class:`can.CompressedASCWriter`
4042
* .blf :class:`can.BLFWriter`
4143
* .csv: :class:`can.CSVWriter`
4244
* .db: :class:`can.SqliteWriter`
4345
* .log :class:`can.CanutilsLogWriter`
4446
* .txt :class:`can.Printer`
4547
48+
Or any of the above compressed using gzip (.gz)
49+
4650
The **filename** may also be *None*, to fall back to :class:`can.Printer`.
4751
4852
The log files may be incomplete until `stop()` is called due to buffering.
@@ -55,7 +59,6 @@ class Logger(BaseIOHandler, Listener): # pylint: disable=abstract-method
5559
fetched_plugins = False
5660
message_writers = {
5761
".asc": ASCWriter,
58-
".asc.gz": GzipASCWriter,
5962
".blf": BLFWriter,
6063
".csv": CSVWriter,
6164
".db": SqliteWriter,
@@ -85,7 +88,11 @@ def __new__( # type: ignore
8588
)
8689
Logger.fetched_plugins = True
8790

88-
suffix = "".join(s.lower() for s in pathlib.PurePath(filename).suffixes)
91+
suffix = pathlib.PurePath(filename).suffix.lower()
92+
93+
if suffix == ".gz":
94+
suffix, filename = Logger.compress(filename)
95+
8996
try:
9097
return cast(
9198
Listener, Logger.message_writers[suffix](filename, *args, **kwargs)
@@ -95,6 +102,17 @@ def __new__( # type: ignore
95102
f'No write support for this unknown log format "{suffix}"'
96103
) from None
97104

105+
@staticmethod
106+
def compress(filename: StringPathLike) -> Tuple[str, IO[Any]]:
107+
"""
108+
Return the suffix and io object of the decompressed file.
109+
File will automatically recompress upon close.
110+
"""
111+
real_suffix = pathlib.Path(filename).suffixes[-2].lower()
112+
mode = "ab" if real_suffix == ".blf" else "at"
113+
114+
return real_suffix, gzip.open(filename, mode)
115+
98116

99117
class BaseRotatingLogger(Listener, BaseIOHandler, ABC):
100118
"""

0 commit comments

Comments
 (0)