Skip to content

Enhance can.logger to consider the append option #1327

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jun 10, 2022
Merged
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
76 changes: 62 additions & 14 deletions can/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ def _create_base_argument_parser(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"-c",
"--channel",
help='''Most backend interfaces require some sort of channel.
For example with the serial interface the channel might be a rfcomm device: "/dev/rfcomm0"
With the socketcan interfaces valid channel examples include: "can0", "vcan0"''',
help=r"Most backend interfaces require some sort of channel. For "
r"example with the serial interface the channel might be a rfcomm"
r' device: "/dev/rfcomm0". With the socketcan interface valid '
r'channel examples include: "can0", "vcan0".',
)

parser.add_argument(
Expand All @@ -60,11 +61,10 @@ def _create_base_argument_parser(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"extra_args",
nargs=argparse.REMAINDER,
help="""\
The remaining arguments will be used for the interface initialisation.
For example, `-i vector -c 1 --app-name=MyCanApp` is the equivalent to
opening the bus with `Bus('vector', channel=1, app_name='MyCanApp')`
""",
help=r"The remaining arguments will be used for the interface "
r"initialisation. For example, `-i vector -c 1 --app-name="
r"MyCanApp` is the equivalent to opening the bus with `Bus("
r"'vector', channel=1, app_name='MyCanApp')",
)


Expand All @@ -82,8 +82,10 @@ def _append_filter_argument(
*args,
"--filter",
help="R|Space separated CAN filters for the given CAN interface:"
"\n <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask)"
"\n <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask)"
"\n <can_id>:<can_mask> (matches when <received_can_id> & mask =="
" can_id & mask)"
"\n <can_id>~<can_mask> (matches when <received_can_id> & mask !="
" can_id & mask)"
"\nFx to show only frames with ID 0x100 to 0x103 and 0x200 to 0x20F:"
"\n python -m can.viewer -f 100:7FC 200:7F0"
"\nNote that the ID and mask are always interpreted as hex values",
Expand Down Expand Up @@ -141,7 +143,8 @@ def _parse_additonal_config(unknown_args):

def main() -> None:
parser = argparse.ArgumentParser(
description="Log CAN traffic, printing messages to stdout or to a given file.",
description="Log CAN traffic, printing messages to stdout or to a "
"given file.",
)

_create_base_argument_parser(parser)
Expand All @@ -159,10 +162,25 @@ def main() -> None:
"--file_size",
dest="file_size",
type=int,
help="Maximum file size in bytes. Rotate log file when size threshold is reached.",
help="Maximum file size in bytes. Rotate log file when size threshold "
"is reached.",
default=None,
)

parser.add_argument(
"-a",
"--append",
# "action"=argparse.BooleanOptionalAction, # Use when Python>=3.9
dest="append_mode",
type=bool,
help="A boolean option for whether to overwrite or append to an "
"existing log file if it exists. To append to an existing log "
"file, pass `True` or `1`. To overwrite an existing log file, "
"pass `False`, `0`, or do not add the -a argument. E.g. -a True "
"or -a False.",
default=False,
)

parser.add_argument(
"-v",
action="count",
Expand Down Expand Up @@ -201,12 +219,42 @@ def main() -> None:
print(f"Connected to {bus.__class__.__name__}: {bus.channel_info}")
print(f"Can Logger (Started on {datetime.now()})")

# argparser.py in Python 3.7.11 does not properly consider boolean
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need any of this. Look at how the --fd argument is handled. It is also a boolean.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. I have modified my changes. This simplifies things. Thank you.

# arguments passed in from the command line. If a boolean is passed in,
# the variable must be converted to an integer 0 (False) or 1 (True).
# Once the project goes to a minimum of Python 3.9, the
# `BooleanOptionalAction` can be used and the following code block will no
# longer be required (Please do not use this as a reason to advocate a
# minimum Python version of 3.9).
boolean_args = ["-a", "--append"]
args = sys.argv[1:]
for _, bool_arg in enumerate(boolean_args):
for j, arg in enumerate(args):
if bool_arg == arg:
# Make sure the length of args is long enough to check the
# toggle, e.g. stop an index error from occurring.
# argparse.py should have already caught this, but this is a
# double check.
if len(args) - 1 >= j + 1:
toggle = args[j + 1]
else:
break
# Consider the action, and update the results to accurately
# embody request.
if toggle in ("0", "False"):
results.append_mode = False
elif toggle in ("1", "True"):
results.append_mode = True
else:
pass

options = {"append": results.append_mode}
if results.file_size:
logger = SizedRotatingLogger(
base_filename=results.log_file, max_bytes=results.file_size
base_filename=results.log_file, max_bytes=results.file_size, **options
)
else:
logger = Logger(filename=results.log_file) # type: ignore
logger = Logger(filename=results.log_file, **options) # type: ignore

try:
while True:
Expand Down