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 3 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
38 changes: 36 additions & 2 deletions can/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,16 @@ def main() -> None:
default=None,
)

parser.add_argument(
'-a',
'--append',
# action=argparse.BooleanOptionalAction, # Use when Python>=3.9
dest='append_mode',
type=bool,
help='Whether to overwrite or append to an existing log file if it exists.',
default=False
)

parser.add_argument(
"-v",
action="count",
Expand Down Expand Up @@ -201,12 +211,36 @@ 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 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, this 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 i, 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 action
if len(args) >= j+1:
action = args[j+1]
else:
break
# Consider the action, and update the results to accurately embody request
if action == '0' or action == 'False':
results.append_mode = False
elif action == '1' or action == 'True':
results.append_mode = True
else:
pass
Copy link
Contributor Author

@j-c-cook j-c-cook Jun 6, 2022

Choose a reason for hiding this comment

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

I added a manual argparse to search for boolean_args and correct the value of results.append_mode.

NOTE: Only required until Python>=3.9
NOTE: Please do not use this as a reason to advocate Python>=3.9.


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