Skip to content

Commit 271a0c1

Browse files
committed
[app][cli] Finalize logging changes for #227
1 parent bf03c8a commit 271a0c1

File tree

7 files changed

+31
-29
lines changed

7 files changed

+31
-29
lines changed

docs/changelog.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -352,5 +352,6 @@ This version of DVR-Scan includes a new, faster background subtraction algorithm
352352
* [feature] various UI enhancements:
353353
* input videos can now be sorted
354354
* add button to open log folder
355-
* [feature] Add `max-area`, `max-width`, and `max-height` options to help suppress improbable motion events, such as those caused by rain or fog [#224](https://github.com/Breakthrough/DVR-Scan/issues/224) (thanks @elvis-epx)
356-
* [feature] Log files are now created with random names, and size limits have been removed. The number of logs to keep can be configured via `max-log-files`.
355+
* [feature] Add `max-area`, `max-width`, and `max-height` options to help suppress improbable motion events, such as those caused by rain or fog [#224](https://github.com/Breakthrough/DVR-Scan/issues/224) (thanks @elvis-epx)
356+
* [bugfix] Log files no longer append to the same file, and now have randomized suffixes to support multiple instances [#227](https://github.com/Breakthrough/DVR-Scan/issues/227)
357+
* Config option changes: logs are no longer appended to the same file, so `max-log-size` is no longer required, and `max-log-files` has been raised from 4 to 15

dvr-scan.cfg

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -192,8 +192,6 @@
192192
# `--logfile` after running `dvr-scan --help` or `dvr-scan-app --help`.
193193
#save-log = yes
194194

195-
# Max size of a debug log in bytes.
196-
197-
# Max number of debug logs to keep. Old ones are deleted automatically.
198-
# Disk space usage will never exceed this times debug-log-max-len
199-
#max-log-files = 4
195+
# Max number of debug logs to keep. If more than this amount are found
196+
# on startup, the oldest ones are purged.
197+
#max-log-files = 15

dvr_scan/app/__main__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def get_cli_parser():
8181
type=str,
8282
help=(
8383
"Appends application output to file. If file does not exist it will be created. "
84-
f"Debug log path: {LOGFILE_PATH}"
84+
f"Log path: {LOGFILE_PATH.parent}"
8585
),
8686
)
8787

@@ -147,7 +147,7 @@ def main():
147147
if settings.get("save-log"):
148148
setup_logger(
149149
logfile_path=LOGFILE_PATH,
150-
max_files=settings.get("max-log-files"),
150+
max_log_files=settings.get("max-log-files"),
151151
name_prefix="dvr-scan-app",
152152
)
153153
failed_to_load_config = False

dvr_scan/cli.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ def get_cli_parser(user_config: ConfigRegistry):
459459
type=str,
460460
help=(
461461
"Appends application output to file. If file does not exist it will be created. "
462-
f"Debug log path: {LOGFILE_PATH}"
462+
f"Log path: {LOGFILE_PATH.parent}"
463463
),
464464
)
465465

dvr_scan/config.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -369,11 +369,11 @@ def from_config(config_value: str, default: "RGBValue") -> "RGBValue":
369369
# Logging
370370
"verbosity": "info",
371371
"save-log": True,
372-
# TODO: max-log-size is not implemented. This is kept for backwards compatibility with older
373-
# config files. Re-implementing size-based rotation is likely overly complicated since log
374-
# files are not expected to be very large.
372+
# max-log-size is not implemented, but is kept for backwards compatibility with older
373+
# config files. Previously, logs would be appended to the same file until they reached this size
374+
# after which a new file would be created.
375375
"max-log-size": 20000,
376-
"max-log-files": 4,
376+
"max-log-files": 15,
377377
# Development
378378
"debug": False,
379379
}

dvr_scan/controller.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def parse_settings() -> ty.Optional[ScanSettings]:
101101
if config.get("save-log"):
102102
setup_logger(
103103
logfile_path=LOGFILE_PATH,
104-
max_files=config.get("max-log-files"),
104+
max_log_files=config.get("max-log-files"),
105105
name_prefix="dvr-scan",
106106
)
107107
failed_to_load_config = False

dvr_scan/shared/__init__.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
import string
2020
import typing as ty
2121
from contextlib import contextmanager
22-
from datetime import datetime
2322
from logging import FileHandler
2423
from pathlib import Path
2524

@@ -74,40 +73,44 @@ def logfile_path(name_prefix: str) -> Path:
7473
folder.mkdir(parents=True, exist_ok=True)
7574
# Generate a random suffix so multiple instances of dvr-scan don't try to write to the same
7675
# log file.
77-
random_suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
78-
return folder / Path(f"{name_prefix}-{datetime.now():%Y%m%d-%H%M%S}-{random_suffix}.log")
76+
random_suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=12))
77+
return folder / Path(f"{name_prefix}.{random_suffix}.log")
7978

8079

81-
def prune_log_files(log_folder: Path, max_files: int, name_prefix: str):
80+
def prune_log_files(log_folder: Path, max_log_files: int, name_prefix: str):
8281
"""Prune log files, keeping the latest `max_files` number of logs."""
8382
# Prune oldest log files if we have too many.
84-
if max_files > 0:
83+
if max_log_files > 0:
8584
# We find all DVR-Scan log files by globbing, then remove the oldest ones.
86-
log_file_pattern = str(log_folder / f"{name_prefix}-*.log")
85+
log_file_pattern = str(log_folder / f"{name_prefix}.*.log")
8786
log_files = list(glob.glob(log_file_pattern))
88-
if len(log_files) > max_files:
87+
if len(log_files) > max_log_files:
88+
logger.debug(
89+
"pruning oldest logs:"
90+
f" max-log-files = {max_log_files}, len(log_files) = {len(log_files)}"
91+
)
8992
log_files.sort(key=os.path.getmtime)
90-
for i in range(len(log_files) - max_files):
91-
logger.debug("Removing old log file: %s", log_files[i])
93+
for i in range(len(log_files) - max_log_files):
9294
try:
9395
os.remove(log_files[i])
96+
logger.debug("removed log: %s", log_files[i])
9497
except PermissionError:
9598
logger.warning(
96-
"Failed to remove old log file: %s. It might be in use by another "
97-
"DVR-Scan process.",
99+
"Failed to remove log file: %s. It might be in use by another process. "
100+
"Try raising `max-log-files` if this is the case.",
98101
log_files[i],
99102
)
100103

101104

102-
def setup_logger(logfile_path: Path, max_files: int, name_prefix: str):
105+
def setup_logger(logfile_path: Path, max_log_files: int, name_prefix: str):
103106
"""Initialize rolling debug logger."""
104-
prune_log_files(logfile_path.parent, max_files, name_prefix)
107+
prune_log_files(logfile_path.parent, max_log_files, name_prefix)
108+
logger.debug(f"writing logs to {logfile_path}")
105109
handler = FileHandler(str(logfile_path))
106110
handler.setLevel(logging.DEBUG)
107111
handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT_ROLLING_LOGS))
108112
# *WARNING*: This log message must come before we attach the handler otherwise it will get
109113
# written to the log file each time.
110-
logger.debug(f"writing logs to {logfile_path} (max_files: {max_files})")
111114
attach_log_handler(handler)
112115

113116

0 commit comments

Comments
 (0)