# SPDX-License-Identifier: BSD-2-Clause # SPDX-FileCopyrightText: 2023 KDE e.V. # SPDX-FileContributor: Ingo Klöcker import logging from contextlib import contextmanager from pathlib import Path from typing import Union standardFormat = "%(asctime)s %(levelname)s %(name)s %(message)s" _taskLogFormatter = None @contextmanager def captureTaskLog(logFilePath: Union[str, Path]): with open(logFilePath, "w", encoding="utf-8") as logFile: # set up a logging handler for capturing messages when processing a task handler = logging.StreamHandler(logFile) handler.setLevel(logging.INFO) if _taskLogFormatter is not None: handler.setFormatter(_taskLogFormatter) logging.getLogger("sftpnotary").addHandler(handler) yield logging.getLogger("sftpnotary").removeHandler(handler) @contextmanager def captureTaskDebugLog(logFilePath: Union[str, Path]): with open(logFilePath, "w", encoding="utf-8") as logFile: # set up a logging handler for capturing debug logs when processing a task handler = logging.StreamHandler(logFile) handler.setLevel(logging.DEBUG) if _taskLogFormatter is not None: handler.setFormatter(_taskLogFormatter) logging.getLogger("sftpnotary").addHandler(handler) yield logging.getLogger("sftpnotary").removeHandler(handler) def setNameForTaskLogs(name: str): global _taskLogFormatter _taskLogFormatter = logging.Formatter(f"%(asctime)s %(levelname)s {name} %(message)s") def maskFollowingItem(v: list, x: str, mask="[MASKED]") -> list: """Returns a list where the item following the item that is equal to x in v is replaced with mask. If a replacement is made, then a copy of v is returned. v is never modified. Does nothing if x is not found in v. This function is mostly useful for masking sensitive information like passwords in command line arguments when they are logged.""" if x in v: copy = list(v) indexToMask = copy.index(x) + 1 copy[indexToMask] = mask return copy return v