Add a log prefix. This enables logging the config file that contained the error or warning, which is helpful when regenerating all containers. Signed-off-by: Enno Tensing <tenno@suij.in>
60 lines
1.6 KiB
Python
60 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
|
|
# SPDX-FileCopyrightText: (C) 2025 Enno Tensing <tenno+containerctl@suij.in>
|
|
#
|
|
# SPDX-License-Identifier: GPL-2.0-only
|
|
|
|
"""Implement a simple logging framework."""
|
|
|
|
import datetime
|
|
from pathlib import Path
|
|
|
|
|
|
class Log:
|
|
"""Class for Logging."""
|
|
|
|
messages: list = []
|
|
logfile: Path
|
|
prefix: str = ""
|
|
|
|
def __init__(self, path: str) -> None:
|
|
"""Init for Log."""
|
|
if path == "":
|
|
path = "/dev/stdout"
|
|
self.logfile = Path(path)
|
|
|
|
def log_error(self, msg: str) -> None:
|
|
"""Log an error."""
|
|
now = self.timestamp()
|
|
prefix = "(EE)"
|
|
if self.prefix != "":
|
|
prefix += f" {self.prefix}:"
|
|
log_message = f"[{now}] {prefix} {msg}"
|
|
self.write_message(log_message)
|
|
|
|
def log_warning(self, msg: str) -> None:
|
|
"""Log a warning."""
|
|
now = self.timestamp()
|
|
prefix = "(WW)"
|
|
if self.prefix != "":
|
|
prefix += f" {self.prefix}:"
|
|
log_message = f"[{now}] {prefix} {msg}"
|
|
self.write_message(log_message)
|
|
|
|
def write_message(self, msg: str) -> None:
|
|
"""Write the message."""
|
|
print(msg)
|
|
if self.logfile == Path("/dev/stdout"):
|
|
return
|
|
with self.logfile.open("a+", encoding="utf-8") as f:
|
|
f.write(msg)
|
|
|
|
def timestamp(self) -> str:
|
|
"""Log timestamp."""
|
|
return datetime.datetime.now(tz=datetime.UTC).strftime(
|
|
"%Y-%m-%d %H:%M:%S",
|
|
)
|
|
|
|
def set_prefix(self, prefix: str) -> None:
|
|
"""Set a prefix."""
|
|
self.prefix = prefix
|