Skip to content

Commit

Permalink
Merge pull request #71 from jd/fix-ignore
Browse files Browse the repository at this point in the history
chore: add custom LogRecord classes to avoid ignore
  • Loading branch information
mergify[bot] authored Jul 1, 2022
2 parents c3729a9 + ce03370 commit a31956f
Showing 4 changed files with 48 additions and 21 deletions.
4 changes: 2 additions & 2 deletions daiquiri/__init__.py
Original file line number Diff line number Diff line change
@@ -15,7 +15,7 @@
import logging.handlers
import sys
import traceback
import types
import types as _ptypes
import typing

from daiquiri import output
@@ -112,7 +112,7 @@ def setup(
def logging_excepthook(
exc_type: typing.Optional[typing.Type[BaseException]],
value: typing.Optional[BaseException],
tb: typing.Optional[types.TracebackType],
tb: typing.Optional[_ptypes.TracebackType],
) -> None:
program_logger.critical(
"".join(traceback.format_exception(exc_type, value, tb))
33 changes: 19 additions & 14 deletions daiquiri/formatter.py
Original file line number Diff line number Diff line change
@@ -16,6 +16,8 @@

from pythonjsonlogger import jsonlogger

from daiquiri import types


DEFAULT_FORMAT = (
"%(asctime)s [%(process)d] %(color)s%(levelname)-8.8s "
@@ -42,22 +44,23 @@ class ColorFormatter(logging.Formatter):

COLOR_STOP = "\033[0m"

def add_color(self, record: logging.LogRecord) -> None:
def add_color(self, record: types.ColoredLogRecord) -> None:
"""Add color to a record."""
if getattr(record, "_stream_is_a_tty", False):
record.color = self.LEVEL_COLORS[record.levelno] # type: ignore[attr-defined]
record.color_stop = self.COLOR_STOP # type: ignore[attr-defined]
record.color = self.LEVEL_COLORS[record.levelno]
record.color_stop = self.COLOR_STOP
else:
record.color = "" # type: ignore[attr-defined]
record.color_stop = "" # type: ignore[attr-defined]
record.color = ""
record.color_stop = ""

def remove_color(self, record: logging.LogRecord) -> None:
def remove_color(self, record: types.ColoredLogRecord) -> None:
"""Remove color from a record."""
del record.color # type: ignore[attr-defined]
del record.color_stop # type: ignore[attr-defined]
del record.color
del record.color_stop

def format(self, record: logging.LogRecord) -> str:
"""Format a record."""
record = typing.cast(types.ColoredLogRecord, record)
self.add_color(record)
s = super(ColorFormatter, self).format(record)
self.remove_color(record)
@@ -118,24 +121,25 @@ def __init__(
self.extras_suffix = extras_suffix
super(ExtrasFormatter, self).__init__(*args, **kwargs)

def add_extras(self, record: logging.LogRecord) -> None:
def add_extras(self, record: types.ExtrasLogRecord) -> None:
if not hasattr(record, "_daiquiri_extra_keys"):
record.extras = "" # type: ignore[attr-defined]
record.extras = ""
return

extras = self.extras_separator.join(
self.extras_template.format(k, getattr(record, k))
for k in record._daiquiri_extra_keys # type: ignore[attr-defined]
for k in record._daiquiri_extra_keys
if k != "_daiquiri_extra_keys" and k not in self.keywords
)
if extras != "":
extras = self.extras_prefix + extras + self.extras_suffix
record.extras = extras # type: ignore[attr-defined]
record.extras = extras

def remove_extras(self, record: logging.LogRecord) -> None:
del record.extras # type: ignore[attr-defined]
def remove_extras(self, record: types.ExtrasLogRecord) -> None:
del record.extras

def format(self, record: logging.LogRecord) -> str:
record = typing.cast(types.ExtrasLogRecord, record)
self.add_extras(record)
s = super(ExtrasFormatter, self).format(record)
self.remove_extras(record)
@@ -146,6 +150,7 @@ class ColorExtrasFormatter(ColorFormatter, ExtrasFormatter):
"""Combines functionality of ColorFormatter and ExtrasFormatter."""

def format(self, record: logging.LogRecord) -> str:
record = typing.cast(types.ColoredLogRecord, record)
self.add_color(record)
s = ExtrasFormatter.format(self, record)
self.remove_color(record)
14 changes: 9 additions & 5 deletions daiquiri/handlers.py
Original file line number Diff line number Diff line change
@@ -28,6 +28,8 @@
syslog = None # type: ignore[assignment]


from daiquiri import types

# This is a copy of the numerical constants from syslog.h. The
# definition of these goes back at least 20 years, and is specifically
# 3 bits in a packed field, so these aren't likely to ever need
@@ -96,7 +98,8 @@ def emit(self, record: logging.LogRecord) -> None:
extras["EXCEPTION_INFO"] = record.exc_info

if hasattr(record, "_daiquiri_extra_keys"):
for k in record._daiquiri_extra_keys: # type: ignore[attr-defined]
record = typing.cast(types.ExtrasLogRecord, record)
for k in record._daiquiri_extra_keys:
if k != "_daiquiri_extra_keys":
extras[k.upper()] = getattr(record, k)

@@ -113,16 +116,17 @@ class TTYDetectorStreamHandler(_TTYDetectorStreamHandlerBase):
"""Stream handler that adds a hint in the record if the stream is a TTY."""

def format(self, record: logging.LogRecord) -> str:
record = typing.cast(types.TTYDetectionLogRecord, record)
if hasattr(self.stream, "isatty"):
try:
record._stream_is_a_tty = self.stream.isatty() # type: ignore[attr-defined]
record._stream_is_a_tty = self.stream.isatty()
except ValueError:
# Stream has been closed, usually during interpretor shutdown
record._stream_is_a_tty = False # type: ignore[attr-defined]
record._stream_is_a_tty = False
else:
record._stream_is_a_tty = False # type: ignore[attr-defined]
record._stream_is_a_tty = False
s = super(TTYDetectorStreamHandler, self).format(record)
del record._stream_is_a_tty # type: ignore[attr-defined]
del record._stream_is_a_tty
return s


18 changes: 18 additions & 0 deletions daiquiri/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import logging
import typing


class ColoredLogRecord(logging.LogRecord):
color: str
color_stop: str


class ExtrasLogRecord(logging.LogRecord):
extras_prefix: str
extras_suffix: str
extras: str
_daiquiri_extra_keys: typing.Set[str]


class TTYDetectionLogRecord(logging.LogRecord):
_stream_is_a_tty: bool

0 comments on commit a31956f

Please sign in to comment.