starlink-grpc-tools/starlink_grpc_tools/logging.py
2023-09-01 13:30:54 -05:00

73 lines
2 KiB
Python

"""Configure logging."""
import logging
import pathlib
import sys
import traceback
import arrow
import urllib3
class Formatter(logging.Formatter):
def __init__(self):
# fmt = formatter_message(fmt, use_color)
logging.Formatter.__init__(self, "")
def format(self, record: logging.LogRecord):
message = record.msg
if len(record.args) > 0:
message = record.msg % record.args
created = arrow.get(record.created).to("America/Chicago")
name = record.name
if len(name) > 25:
name = name[:24] + "\u2026"
pathname = record.pathname
if len(pathname) > 15:
pathname = "\u2026" + pathname[-14:]
prefix = f"{created:YYYY-MM-DD HH:mm:ss.SSSSSS Z} [{name:^25s}] {pathname}:{record.lineno:<4d} {record.levelname:8s}" # noqa: E501
msg = f"{prefix} {message:s}"
if record.exc_info is not None:
formatted = traceback.format_exception(*record.exc_info)
for chunk in formatted:
line = chunk.splitlines()
for line in chunk.splitlines():
msg += f"\n{prefix} {line}"
return msg
def setup_logging(filename: pathlib.Path | None = None):
"""Set up logging."""
formatter = Formatter()
console = logging.StreamHandler(stream=sys.stderr)
console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
if filename is not None:
file = logging.FileHandler(filename=filename, encoding="utf-8")
file.setFormatter(formatter)
file.setLevel(logging.DEBUG)
root = logging.getLogger()
for handler in root.handlers:
root.removeHandler(handler)
handler.close()
root.addHandler(console)
if filename is not None:
root.addHandler(file)
root.setLevel(logging.DEBUG)
urllib3.disable_warnings()
logging.getLogger("urllib3.connectionpool").setLevel(logging.INFO)
logging.captureWarnings(True)