python-talk/logs.py

46 lines
1.4 KiB
Python
Raw Normal View History

2024-06-15 03:14:45 +00:00
#!/usr/bin/python3
from datetime import datetime as dt, timezone as tz
2024-06-15 03:14:45 +00:00
from sys import stdout, stderr
from typing import Union
def log(
message: str,
level: str = "LOG",
origin: str = None,
time: Union[dt, str] = "now",
) -> bytes:
if level in ["EXIT", "CRASH", "FATAL", "ERROR"]:
stream = stderr
else:
stream = stdout
if time == "now":
dtime = dt.now(tz.utc)
dtime.replace(tzinfo=tz.utc)
2024-06-15 03:14:45 +00:00
elif type(time) == str:
raise ValueError('Only "now" is an accepted string argument for time')
elif type(time) == dt:
dtime = time
else:
raise ValueError("time must either be a string or a dt object")
time = dtime.strftime("%d-%m-%Y %H:%M:%S")
log = ""
if not "\n" in message:
log = f"[{level}]{'['+origin+']' if origin else ''}[{time}] {message}"
print(
f"[{level}]{'['+origin+']' if origin else ''}[{time}] {message}",
file=stream,
2024-07-31 20:15:39 +00:00
flush=True,
2024-06-15 03:14:45 +00:00
)
else:
for line in message.split("\n"):
2024-07-31 19:07:05 +00:00
log = (
log + f"\r\n[{level}]{'['+origin+']' if origin else ''}[{time}] {line}"
)
2024-06-15 03:14:45 +00:00
print(
f"[{level}]{'['+origin+']' if origin else ''}[{time}] {line}",
file=stream,
2024-07-31 20:15:39 +00:00
flush=True,
2024-06-15 03:14:45 +00:00
)
2024-07-30 03:52:30 +00:00
return (log[5:] + "\r\n").encode("utf8")