helpers: logging: fixes + details_to_stdout in color (MR 2252)

* Fix details_to_stdout which was broken due to a previous commit.
* Improve support for custom colors with "@COLOR@" (e.g. "@BLUE@"), stop
  it from being printed unformatted to the logfile.
* Rework how the logfd is handled so that --details-to-stdout won't
  disable all color output.

Signed-off-by: Caleb Connolly <caleb@postmarketos.org>
This commit is contained in:
Caleb Connolly 2024-06-14 03:14:32 +02:00 committed by Oliver Smith
parent 53bdb523e3
commit c4b4c41b8d
No known key found for this signature in database
GPG key ID: 5AE7F5513E0885CB

View file

@ -4,7 +4,7 @@ import logging
import os import os
from pathlib import Path from pathlib import Path
import sys import sys
from typing import TextIO from typing import Dict, TextIO
import pmb.config import pmb.config
logfd: TextIO logfd: TextIO
@ -24,7 +24,7 @@ class log_handler(logging.StreamHandler):
def __init__(self, details_to_stdout: bool=False, quiet: bool=False): def __init__(self, details_to_stdout: bool=False, quiet: bool=False):
super().__init__() super().__init__()
self.details_to_stdout = False self.details_to_stdout = details_to_stdout
self.quiet = False self.quiet = False
def emit(self, record): def emit(self, record):
@ -32,9 +32,9 @@ class log_handler(logging.StreamHandler):
msg = self.format(record) msg = self.format(record)
# INFO or higher: Write to stdout # INFO or higher: Write to stdout
if (not self.details_to_stdout and if (self.details_to_stdout or
not self.quiet and (not self.quiet and
record.levelno >= logging.INFO): record.levelno >= logging.INFO)):
stream = self.stream stream = self.stream
styles = pmb.config.styles styles = pmb.config.styles
@ -65,28 +65,13 @@ class log_handler(logging.StreamHandler):
f"{styles['GREEN']}*** ", f"{styles['GREEN']}*** ",
1, 1,
) )
.replace(
"@BLUE@",
f"{styles['BLUE']}",
)
.replace(
"@YELLOW@",
f"{styles['YELLOW']}",
)
.replace(
"@RED@",
f"{styles['RED']}",
)
.replace(
"@GREEN@",
f"{styles['GREEN']}",
)
.replace(
"@END@",
f"{styles['END']}",
)
) )
for key, value in styles.items():
msg_col = msg_col.replace(f"@{key}@", value)
# Strip from the normal log message
msg = msg.replace(f"@{key}@", "")
msg_col += styles["END"] msg_col += styles["END"]
stream.write(msg_col) stream.write(msg_col)
@ -94,9 +79,10 @@ class log_handler(logging.StreamHandler):
self.flush() self.flush()
# Everything: Write to logfd # Everything: Write to logfd
msg = "(" + str(os.getpid()).zfill(6) + ") " + msg if not self.details_to_stdout:
logfd.write(msg + "\n") msg = "(" + str(os.getpid()).zfill(6) + ") " + msg
logfd.flush() logfd.write(msg + "\n")
logfd.flush()
except (KeyboardInterrupt, SystemExit): except (KeyboardInterrupt, SystemExit):
raise raise
@ -131,19 +117,16 @@ def init(logfile: Path, verbose: bool, details_to_stdout: bool=False):
warning("Logging already initialized, skipping...") warning("Logging already initialized, skipping...")
return return
# Set log file descriptor (logfd) # Require containing directory to exist (so we don't create the work
if details_to_stdout: # folder and break the folder migration logic, which needs to set the
# version upon creation)
if not details_to_stdout and logfile.parent.exists():
logfd = open(logfile, "a+")
logfd.write("\n\n")
elif details_to_stdout:
logfd = sys.stdout logfd = sys.stdout
else: else:
# Require containing directory to exist (so we don't create the work logfd = open(os.devnull, "w")
# folder and break the folder migration logic, which needs to set the
# version upon creation)
dir = os.path.dirname(logfile)
if os.path.exists(dir):
logfd = open(logfile, "a+")
logfd.write("\n\n")
else:
logfd = open(os.devnull, "a+")
# Set log format # Set log format
root_logger = logging.getLogger() root_logger = logging.getLogger()