55"""
66
77import logging
8+ import pathlib
9+ import typing
810
911from ..listener import Listener
1012from .generic import BaseIOHandler
1517from .sqlite import SqliteWriter
1618from .printer import Printer
1719
20+ from can .typechecking import PathLike
21+
1822log = logging .getLogger ("can.io.logger" )
1923
2024
@@ -28,36 +32,36 @@ class Logger(BaseIOHandler, Listener): # pylint: disable=abstract-method
2832 * .csv: :class:`can.CSVWriter`
2933 * .db: :class:`can.SqliteWriter`
3034 * .log :class:`can.CanutilsLogWriter`
31- * other: :class:`can.Printer`
35+
36+ The **filename** may also be *None*, to fall back to :class:`can.Printer`.
3237
3338 The log files may be incomplete until `stop()` is called due to buffering.
3439
3540 .. note::
36- This class itself is just a dispatcher, and any positional an keyword
41+ This class itself is just a dispatcher, and any positional and keyword
3742 arguments are passed on to the returned instance.
3843 """
3944
4045 @staticmethod
41- def __new__ (cls , filename , * args , ** kwargs ):
46+ def __new__ (cls , filename : typing . Optional [ PathLike ] , * args , ** kwargs ):
4247 """
43- :type filename: str or None or path-like
44- :param filename: the filename/path the file to write to,
45- may be a path-like object if the target logger supports
46- it, and may be None to instantiate a :class:`~can.Printer`
47-
48+ :param filename: the filename/path of the file to write to,
49+ may be a path-like object or None to
50+ instantiate a :class:`~can.Printer`
4851 """
49- if filename :
50- if filename .endswith (".asc" ):
51- return ASCWriter (filename , * args , ** kwargs )
52- elif filename .endswith (".blf" ):
53- return BLFWriter (filename , * args , ** kwargs )
54- elif filename .endswith (".csv" ):
55- return CSVWriter (filename , * args , ** kwargs )
56- elif filename .endswith (".db" ):
57- return SqliteWriter (filename , * args , ** kwargs )
58- elif filename .endswith (".log" ):
59- return CanutilsLogWriter (filename , * args , ** kwargs )
60-
61- # else:
62- log .warning ('unknown file type "%s", falling pack to can.Printer' , filename )
63- return Printer (filename , * args , ** kwargs )
52+ if filename is None :
53+ return Printer (* args , ** kwargs )
54+
55+ suffix = pathlib .PurePath (filename ).suffix
56+ if suffix == ".asc" :
57+ return ASCWriter (filename , * args , ** kwargs )
58+ if suffix == ".blf" :
59+ return BLFWriter (filename , * args , ** kwargs )
60+ if suffix == ".csv" :
61+ return CSVWriter (filename , * args , ** kwargs )
62+ if suffix == ".db" :
63+ return SqliteWriter (filename , * args , ** kwargs )
64+ if suffix == ".log" :
65+ return CanutilsLogWriter (filename , * args , ** kwargs )
66+
67+ raise ValueError (f'unknown file type "{ filename } "' )
0 commit comments